How to set default value for input field using jQuery?

I want to change the default value for the input field so that when I reset the form the value remains.

I have the following code that sets a value using jQuery, but when I press reset, the value becomes the original.

<form> Email: <input type="text" id="email" value="old value" /> <input type="reset" value="reset" /> </form> $(function(){ $("#email").val("New value"); }); 
+6
source share
4 answers

Reset clears all form values ​​(default behavior). If you want the values ​​to be visible again, you need to set them again. Therefore, you need to call the onclick method of the reset button and fill out the form again.

+2
source

You need to set the value attribute of the #email element, not the value itself.

 $("#email").attr("value", "New value"); 
+22
source

Reset clears the form by default, but if you want to control this behavior, here is how you do it. You need to use .val () Here are some examples of creating a single reset block and multiple drawers using a wrapped set.

Example: http://jsfiddle.net/HenryGarle/ZTprm/

 <b>Reset Single</b> <input type="text" id="TextBox"> <button id="reset">Reset</button> <hr> <b>Reset Many</b> <div id="Many"> <input type="text" value="1"> <input type="text" value="5"> <input type="text" value="2"> <button id="ResetMany">Reset</button> </div> <script> // Reset single $("#reset").click(function (e) { $("#TextBox").val("Value"); }); // Resets many given a selector // Could be a form, containing div $("#ResetMany").click(function (e) { var inputs = $("input", "#Many"); for (var i = 0; i < inputs.length; i++) { $(inputs[i]).val("Value"); } }); </script> 
+1
source

Try

 $('input[type="reset"]').click(function(){ $("#email").val("New value"); }); 
0
source

Source: https://habr.com/ru/post/895659/


All Articles