JavaScript:隐藏字段的真实表单重置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2559616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: True form reset for hidden fields
提问by Bogdan Gusiev
Unfortunately form.reset() function doesn't reset hidden inputs of the form. Checked in FF3 and Chromium.
不幸的是 form.reset() 函数不会重置表单的隐藏输入。已检查 FF3 和 Chromium。
Does any one have an idea how to do the reset for hidden fields as well?
有没有人知道如何重置隐藏字段?
回答by Bogdan Gusiev
Seems the easiest way of doing that is having display: nonetext field instead of hidden field. At this case default reset process regularly.
似乎最简单的方法是显示:无文本字段而不是隐藏字段。在这种情况下,默认重置过程会定期进行。
回答by bobince
This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValuenonetheless. See this discussion: it's not (alas) going to change in HTML5.
不幸的是,根据标准,这是正确的。一个糟糕的规格疣 IMO。defaultValue尽管如此,IE 还是提供了可重置的隐藏字段。看到这个讨论:它不会(唉)在 HTML5 中改变。
(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)
(幸运的是,很少需要重置表单。作为 UI 功能,它通常不受欢迎。)
Since you can't get the original value of the valueattribute at all, you would have to duplicate it in another attribute and fetch that. eg.:
由于您根本无法获得value属性的原始值,因此您必须在另一个属性中复制它并获取它。例如。:
<form id="f">
<input type="hidden" name="foo" value="bar" class="value=bar"/>
function resetForm() {
var f= document.getElementById('f');
f.reset();
f.elements.foo.value= Element_getClassValue(f.elements.foo, 'value');
}
function Element_getClassValue(el, classname) {
var prefix= classname+'=';
var classes= el.className.split(/\s+/);
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)===prefix)
return classes[i].substring(prefix.length);
return '';
}
Alternative ways of smuggling that value in might include HTML5 data, another spare attribute like title, an immediately-following <!-- comment -->to read the value from, explicit additional JS information, or extra hidden fields just to hold the default values.
走私该值的替代方法可能包括 HTML5 data、另一个备用属性(如 )title、立即跟随<!-- comment -->以从中读取值、显式附加 JS 信息或仅用于保存默认值的额外隐藏字段。
Whatever approach, it would have to clutter up the HTML; it can't be created by script at document ready time because some browsers will have already overridden the field's value with a remembered value (from a reload or back button press) by that time that code executes.
无论采用哪种方法,它都会使 HTML 变得混乱;它不能在文档就绪时由脚本创建,因为在该代码执行时,某些浏览器已经用记住的值(来自重新加载或按下后退按钮)覆盖了该字段的值。
回答by ForOhFor
Another answer, in case anyone comes here looking for one. Serialize the form after the page loads and use those values to reset the hidden fields later:
另一个答案,以防有人来这里寻找。在页面加载后序列化表单,然后使用这些值重置隐藏字段:
var serializedForm = $('#myForm').serialize();
Then, to reset the form:
然后,重置表单:
function fullReset(){
$('#myForm').reset(); // resets everything except hidden fields
var formFields = decodeURIComponent(serializedForm).split('&'); //split up the serialized form into variable pairs
//put it into an associative array
var splitFields = new Array();
for(i in formFields){
vals= formFields[i].split('=');
splitFields[vals[0]] = vals[1];
}
$('#myForm').find('input[type=hidden]').each(function(){
this.value = splitFields[this.name];
});
}
回答by Anthony Estelita
I found it easier to just set a default value when the document is loaded then trap the reset and reset the hidden puppies back to their original value. For example,
我发现在加载文档时设置默认值更容易,然后捕获重置并将隐藏的小狗重置回其原始值。例如,
//fix form reset (hidden fields don't get reset - this will fix that pain in the arse issue)
$( document ).ready(function() {
$("#myForm").find("input:hidden").each(function() {
$(this).data("myDefaultValue", $(this).val());
});
$("#myForm").off("reset.myarse");
$("#myForm").on("reset.myarse", function() {
var myDefaultValue = $(this).data("myDefaultValue");
if (myDefaultValue != null) {
$(this).val(myDefaultValue);
}
});
}
Hope this helps someone out :)
希望这可以帮助某人:)
回答by Alan
You can use jQuery - this will empty hidden fields:
您可以使用 jQuery - 这将清空隐藏字段:
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).val('');
});
Tip: just make sure you're not resetting csrf token field or anything else that shouldn't be emptied. You can narrow down element's specification if needed.
提示:只需确保您没有重置 csrf 令牌字段或任何其他不应清空的内容。如果需要,您可以缩小元素的规格。
If you want to reset the field to a default value you can use(not tested):
如果要将字段重置为默认值,可以使用(未测试):
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).each(function() {
var $t = $(this);
$t.val($t.data('defaultvalue'));
});
});
and save the default value in the data-defaultvalue="Something"property.
并将默认值保存在data-defaultvalue="Something"属性中。
回答by aidonsnous
$('#form :reset').on('click',function(e)({
e.preventDefault();
e.stopImmediatePropagation();
$("#form input:hidden,#form :text,#form textarea").val('');
});
For select, checkbox, radio, it's better you know (hold) the default values and in that event handler, you set them to their default values.
对于选择、复选框、单选,最好知道(保持)默认值,并在该事件处理程序中将它们设置为默认值。
回答by Rutvik kakadiya
You can reset hidden input field value using below line, you just need to change your form id instead of frmForm.
您可以使用以下行重置隐藏的输入字段值,您只需要更改表单 ID 而不是frmForm.
$("#frmForm input:hidden").val(' ');
回答by Aaron Digulla
Create a button and add JavaScript to the onClickevent which clears the fields.
创建一个按钮并将 JavaScript 添加到onClick清除字段的事件中。
That said, I'm curious why you want to reset these fields. Usually, they contain internal data. If I would clear them in my code, the post of the form would fail (for example after the user has entered the new data and tries to submit the form).
也就是说,我很好奇您为什么要重置这些字段。通常,它们包含内部数据。如果我在我的代码中清除它们,表单的发布将会失败(例如在用户输入新数据并尝试提交表单之后)。
[EDIT] I misunderstood your question. If you're worried that someone might tamper with the values in the hidden fields, then there is no way to reset them. For example, you can call reset()on the form but not on a field in the form.
[编辑] 我误解了你的问题。如果您担心有人可能篡改隐藏字段中的值,则无法重置它们。例如,您可以调用reset()表单,但不能调用表单中的字段。
You could think that you could save the values in a JavaScript file and use that to reset the values but when a user can tamper with the hidden fields, he can tamper with the JavaScript as well.
您可能认为您可以将值保存在 JavaScript 文件中并使用它来重置值,但是当用户可以篡改隐藏字段时,他也可以篡改 JavaScript。
So from a security point of view, if you need to reset hidden fields, then avoid them in the first place and save the information in the session on the server.
所以从安全的角度来看,如果你需要重置隐藏字段,那么首先要避免它们,并将会话中的信息保存在服务器上。
回答by ChrisR
How I would do it is put an event listener on the change event of the hidden field. In that listener function you could save the initial value to the DOM element storage (mootools, jquery) and then listen to the reset event of the form to restore the initial values stored in the hidden form field storage.
我会怎么做是在隐藏字段的更改事件上放置一个事件侦听器。在该侦听器函数中,您可以将初始值保存到 DOM 元素存储(mootools、jquery),然后侦听表单的重置事件以恢复存储在隐藏表单字段存储中的初始值。
回答by ChrisR
This will do:
这将:
$("#form input:hidden").val('').trigger('change');

