Reputation: 416
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?
Upvotes: 0
Views: 3039
Reputation: 436
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") );
Upvotes: 1
Reputation: 6414
In the W3 spec:
defaultValue of type DOMString When the type attribute of the element has the value "text", "file" or "password", this represents the HTML value attribute of the element. The value of this attribute does not change if the contents of the corresponding form control, in an interactive user agent, changes. See the value attribute definition in HTML 4.01.
Unfortunately it does not apply for hidden inputs, instead you could store and retrieve the value from the element data.
// Do this on ready
$("#field1").data("defaultValue", $("#field1").val());
$("#field2").data("defaultValue", $("#field2").val());
// Update the values
$("#field1").val("value1");
$("#field2").val("value2");
console.log($("#field1").val(), $("#field2").val());
// Restore the defaults
$("#field1").val($("#field1").data("defaultValue"));
$("#field2").val($("#field2").data("defaultValue"));
console.log($("#field1").val(), $("#field2").val());
Upvotes: 1
Reputation: 11
One possible solution could be, save the default value in a global variable when the page loads, and use the variable to set these fields wherever you want.
Upvotes: 0