Reset form except one field with Javascript

For some reason, I need a reset form, but I want one field to remain unchanged.

This following code clears all the fields, but I would like the first to be immutable.

<form id="myForm"> <input id="01" type="text"/> <input id="02" type="text"/> <input id="03" type="text"/> <input id="04" type="text"/> </form> <button onclick="document.getElementById('myForm').reset()">Reset</button> 

If possible, I would like to avoid jQuery.

+7
source share
4 answers

Copy its value to a variable. Reset form. Return the variable back to the value.

+9
source

You can use the following code:

 var form = document.getElementById("myForm"); var inputs = form.getElementsByTagName("input") for (i = 0; i < inputs.length; i++) { if(i != 0) { inputs[i].value = ""; } } 
+1
source

I worked on the answer to this question , which is similar, and has now been marked as a duplicate. This question used jQuery , so the answer would be much shorter using things like event.data , detach() , etc. Below is the general algorithm and the vanilla version of the approach, which I would consider not just this question, but also more complex scenarios in which you want to exclude the entire subsection of the form.


Algorithm

  • Detach an element from it parent
  • Allow default behavior reset()
  • Reconnect the item in the right place in the DOM

Here is a very simple translation of this plan into code. This does not actually bind the element in the right place in the DOM. Please view the code snippet for a fully functional example.

 // within the form onreset handler, which fires // before the form children are actually reset var form = document.getElementById("myForm"), exclude = document.getElementById("_01"), parentNode = exclude.parentNode; parentNode.removeChild(exclude); // use a timeout to allow the default reset() behavior // before re-attaching the element setTimeout(function() { parentNode.appendChild(exclude); }); 

NOTE id change to _01 and refer to the “Side note” at the end of this answer for more information on this.


Important properties and methods


 var dataKey = 'data-exclude-selector'; function initiateReset(e) { e = e || window.event; var button = e.target, form = button.form, excludeSelector = button.getAttribute(dataKey); form.setAttribute(dataKey, excludeSelector); } function beforeReset(e) { e = e || window.event; var form = e.target, excludeSelector = form.getAttribute(dataKey), elements = form.querySelectorAll(excludeSelector), parents = [], siblings = [], len = elements.length, i, e, p, s; // When reset #5 is clicked, note the excludeSelector value is js escaped: // #\0030\0035 element attribute value becomes #\\0030\\0035 as js var value for (i = 0; i < len; i++) { el = elements[i]; parents.push(p = el.parentNode); siblings.push(s = el.nextSibling); p.removeChild(el); } setTimeout(function() { for (var j = 0; j < len; j++) { if (siblings[j]) { parents[j].insertBefore(elements[j], siblings[j]); } else { parents[j].appendChild(elements[j]); } } }); } 
 <form id="myForm" onreset="beforeReset()" data-exclude-selector=""> <input id="_01" type="text" placeholder="clear" /> <br /> <input id="_02" type="text" placeholder="clear" /> <br /> <input id="_03" type="text" placeholder="clear" /> <br /> <input id="_04" type="text" placeholder="clear" /> <br /> <input id="05" type="text" placeholder="clear" /> </form> <input value="Reset 1" type="reset" form="myForm" data-exclude-selector="#_01" onclick="initiateReset()" /> <input value="Reset 2" type="reset" form="myForm" data-exclude-selector="#_02" onclick="initiateReset()" /> <input value="Reset 3" type="reset" form="myForm" data-exclude-selector="#_03" onclick="initiateReset()" /> <input value="Reset 4" type="reset" form="myForm" data-exclude-selector="#_04" onclick="initiateReset()" /> <input value="Reset funky ID (05)" type="reset" form="myForm" data-exclude-selector="#\0030\0035" onclick="initiateReset()" /> <br/>&nbsp; <br /> <hr/> <br/> <form id="complexForm" onreset="beforeReset()" data-exclude-selector=""> <input class="exclude" type="text" placeholder="clear" /> <br /> <input class="exclude" type="text" placeholder="clear" /> <br /> <input type="text" placeholder="clear" /> <br /> <input type="text" placeholder="clear" /> <br /> <div class="childTest"> <input type="text" placeholder="clear" /> <br /> <input type="text" placeholder="clear" /> <div class="nestedTest"> <input type="text" placeholder="clear" /> <br /> <input type="text" placeholder="clear" /> </div> </div> </form> <input value="Exclude by class" type="reset" form="complexForm" data-exclude-selector=".exclude" onclick="initiateReset()" /> <input value="Exclude subsection" type="reset" form="complexForm" data-exclude-selector=".childTest" onclick="initiateReset()" /> 

extra work

  • Additional work needs to be done to handle the case where it would be necessary to allow reset for some child nodes of excluded nodes, but I believe that this could be handled in several different ways with little thought.

    • recursive version of this idea
    • @Quentin's idea can be expanded with cloneNode() to make a copy of the entire node, instead of separating it, allowing a full reset, then implementing a mechanism to determine which parts of the clone are systematically restored

Side Note (... rant?)

  • Although the HTML5 id attribute allows 01 to be used as valid, the specification continues to indicate that it can be used for other purposes.

3.2.5.1 id attribute

The id attribute indicates its element is a unique identifier (ID) . [DOM]

The value must be unique among all identifiers in the Main subtree element and must contain at least one character. The value should not contain space characters.

Note. There are no other restrictions on what form an identifier can take; in particular, identifiers can consist of simple digits, begin with a digit, begin with an underscore, consist only of punctuation marks, etc.

Note. A unique identifier element can be used for various purposes, primarily as a way of referencing specific parts of a document using fragment identifiers, as a way of targeting an element when writing scripts, and as a way of styling a certain element from CSS.

This may not be a problem for you, but it is something you need to know about. For example, document.querySelector[All]() uses a CSS style selector.

elementList = document.querySelectorAll(selectors);

...

  • Selector
  • is a string containing one or more CSS selectors , separated by commas.

According to the latest draft CSS Selectors specification

The identifier selector contains a “quantity sign” (U + 0023, #), followed immediately by the identifier value, which should be the CSS identifier.

And at the end of the rabbit hole there are rules for CSS identifiers

  • In CSS, identifiers (including element names, classes, and identifiers in selectors ) can contain only characters [a-zA-Z0-9] and ISO 10646 characters U + 00A0 and above, plus a hyphen (-) and underscore (_); they cannot begin with a number, two hyphens or hyphens, followed by a number. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For example, the identifier "B & W?" can be written as "B \ & W \?" or "B \ 26 W \ 3F".

    Note that Unicode is a code equivalent to ISO 10646 (see [UNICODE] and [ISO10646] ).

So, if you only use document.getElementById() , you may be ok with the value of the id element, like 01 , but in general I would avoid this. Yes, with document.querySelector[All]() and any other component that uses the CSS style selector, you can get around this limitation by executing the correct selector, but this will be an expected error, especially if several developers are involved. I included an example (5th reset) in the code snippet to complete if you need to interact with elements that have identifiers that have this format.

Checklist for hexadecimal codes

+1
source

Store the value of one value in a variable

Var partNumber = document.getElementById ('partNumber'). Value

Then reset the form

document.getElementById ('form') reset ().

Then reassign the value

document.getElementById ('PARTNUMBER') value = PARTNUMBER.

0
source

Source: https://habr.com/ru/post/1208215/


All Articles