1

My form reset button is not working as expected.

I have a form with a textarea and a text input that is being submitted via Ajax. The Ajax response is then used for the values of the form inputs. When I click the reset button, the value of the text input field reverts to the value before the submission. However, the textarea maintains the value that was just submitted.

HTML:

<form id="formID" name="formName">
    <textarea name="taName" id="taID"></textarea><br>
    <input name="textName" id="textID"><br>
    <input id="submitID" name="submitName" class="buttons" value="Save" type="submit">
    <input id="resetID" name="resetName" class="buttons" value="Reset" type="reset">
</form>

JS:

$.ajax({
    url : "page.php",
        type: "post",
        data: "process=saveReturn",
        dataType: 'json',
        success : function (response) {
            var pcodesR = response[0];
            var erpageR = response[1];
            
            $("#taID").empty();                                         
            $("#taID")[0].append(pcodesR);
            $("#textID").val('');
            $("#textID").val(erpageR);
            console.log(pcodesR);
            console.log(erpageR);
...

The console log does show the correct, just submitted value for each input.

How can I make it so the ajax submitted value remains as the value for both inputs when the reset button is clicked and why does that already happen with the textarea but not the text input field?

Jeff
  • 495
  • 1
  • 5
  • 18

1 Answers1

1

make it so the ajax submitted value remains as the value for both inputs when the reset button

When you click a button type='reset' it restores to the "default" value. For a textarea this is defined by setting a text node inside the text area, eg:

<textarea>default value</textarea>

This is what you are doing with this code:

$("#taID").empty();                                         
$("#taID")[0].append(pcodesR);

...setting the default value; so that works for your text area.

The equivalent for a input type=text is to set the value attribute:

$("#textID").attr("value", erpageR);

Example:

$("#btn").click(() =>
{
    $("#taID").empty();                                         
    $("#taID")[0].append("default");

    $("#textID").attr("value", "default");
    
    // also set the values at this time as the above sets the default values only
    $("#taID").val("default");
    $("#textID").val("default");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formID" name="formName">
    <textarea id="taID"></textarea><br>
    <input id="textID"><br>
    <input id="submitID" name="submitName" class="buttons" value="Save" type="submit">
    <input id="resetID" name="resetName" class="buttons" value="Reset" type="reset">
</form>
<hr/>
<button type="button" id="btn">click to set default values via code</button>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57