VincentHuang VincentHuang - 4 years ago 137
jQuery Question

jQuery get default value from hidden input field

I have the following

input fields


<input type="hidden" name="field1" id="field1" value="">
<input type="input" name="field2" id="field2" value="">


After I did some operations to assign value to them as

$("#fiedl1").val("value1");
$("#fiedl2").val("value2");


Then I want to get the DEFAULT value of them when I want to reset them to original value

$("#fiedl1").val( $("#field1").prop("defaultValue") );
$("#fiedl2").val( $("#field2").prop("defaultValue") );


However,
field1
is still kept the assigned value
value1
but
field2
is with default value
""
. It seems that the
hidden
field cannot be set to their defaultValue?

Answer Source

The easy way to do this is adding a data-default attribute to your html input tags:

<input type="hidden" name="field1" id="field1" value="" data-default="150">
<input type="input" name="field2" id="field2" value="" data-default="150">

And get the values with .data:

$("#field1").val( $("#field1").data("default") );
$("#field2").val( $("#field2").data("default") );

Test it!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download