Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: True form reset for hidden fields

Unfortunately form.reset() function doesn't reset hidden inputs of the form. Checked in FF3 and Chromium.

Does any one have an idea how to do the reset for hidden fields as well?

like image 234
Bogdan Gusiev Avatar asked Apr 01 '10 10:04

Bogdan Gusiev


People also ask

What does reset () do in JavaScript?

In JavaScript, the reset() method does the same thing as the HTML reset button. It is used to clear all the values of the form elements. It can be used to set the values to default.

How do you reset form fields?

The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.

Which is correct for hidden form field?

The <input type="hidden"> defines a hidden input field.


2 Answers

Seems the easiest way of doing that is having display: none text field instead of hidden field. At this case default reset process regularly.

like image 52
Bogdan Gusiev Avatar answered Sep 20 '22 17:09

Bogdan Gusiev


This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValue nonetheless. See this discussion: it's not (alas) going to change in HTML5.

(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)

Since you can't get the original value of the value attribute at all, you would have to duplicate it in another attribute and fetch that. eg.:

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

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.

like image 25
bobince Avatar answered Sep 19 '22 17:09

bobince