0

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?

1
  • its because u are overwriting the default value every time your code runs.. Commented Feb 5, 2017 at 9:24

3 Answers 3

1

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!!

Sign up to request clarification or add additional context in comments.

1 Comment

I like your solution!
1

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());

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.