简体   繁体   English

jQuery从隐藏的输入字段获取默认值

[英]jQuery get default value from hidden input field

I have the following input fields 我有以下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 "" . 但是, field1仍保持分配的值value1field2保留默认值"" It seems that the hidden field cannot be set to their defaultValue? 似乎无法将hidden字段设置为其默认值?

The easy way to do this is adding a data-default attribute to your html input tags: 最简单的方法是在html输入标签中添加data-default属性:

<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 : 并使用.data获取值:

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

Test it!! 测试一下!

In the W3 spec : W3规范中

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. DOMString类型的defaultValue当元素的类型属性的值为“文本”,“文件”或“密码”时,这表示元素的HTML值属性。 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. 请参见HTML 4.01中的value属性定义。

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

一种可能的解决方案是,在页面加载时将默认值保存在全局变量中,然后使用该变量在所需的任何位置设置这些字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM