UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Remove required attribute for all text boxes in a page - Javascript

Demo and code for how to remove required attribute for all text boxes in javascript

by Athil


Posted on 27 Jun 2018 Category: Javascript Views: 28

Edited on 28 Jun 2019


Here I am going to show how to take all text boxes in page and removing required field for all text boxes in the page.

DEMO

Removing Required attribute by taking all text boxes

var texts = document.getElementsByTagName('input');
        // LOOP THROUGH EACH ELEMENT.
        for (i = 0; i < texts.length; i++) {
            // CHECK THE ELEMENT TYPE.
            if (texts[i].type == 'text') {
                console.log('Id: ' + texts[i].id);
                document.getElementById(texts[i].id).required = false;                				
			
            }
        }

Adding Required attribute by taking all text boxes

 var texts = document.getElementsByTagName('input');
        // LOOP THROUGH EACH ELEMENT.
        for (i = 0; i < texts.length; i++) {
            // CHECK THE ELEMENT TYPE.
            if (texts[i].type == 'text') {
			       console.log('Id: ' + texts[i].id);
                   document.getElementById(texts[i].id).required = true;				
			}
        }

 

Full Demo Code

 <html> 
<h1> Demo for remove/Add required for all text boxes in a page </h1> 
 <form>
 txt1  <input type="text" required id="txt1">  </input> <br/>
 txt2  <input type="text" required id="txt2">  </input> <br/>
 txt3  <input type="text" required id="txt3">  </input> <br/>
 <br/> 
 
 <label id="lblstatus"> Form Loaded </label>  <br/>
 
<button type="submit" > Submit </button> <br/><br/>
<input type="button" value="Add required" onclick ="addrequiredallcontrols();"> </input> 
<input type="button" value="Remove required" onclick ="removerequiredAllcontrols();">  </input><br/>

 </form>
 <script>
 function removerequiredAllcontrols()
 {
		
        var texts = document.getElementsByTagName('input');
        // LOOP THROUGH EACH ELEMENT.
        for (i = 0; i < texts.length; i++) {
            // CHECK THE ELEMENT TYPE.
            if (texts[i].type == 'text') {
                console.log('Id: ' + texts[i].id);
                document.getElementById(texts[i].id).required = false;                				
				document.getElementById('lblstatus').innerHTML = "Removed required";
            }
        }
}
function addrequiredallcontrols()
{
		debugger;
       var texts = document.getElementsByTagName('input');
        // LOOP THROUGH EACH ELEMENT.
        for (i = 0; i < texts.length; i++) {
            // CHECK THE ELEMENT TYPE.
            if (texts[i].type == 'text') {
			       console.log('Id: ' + texts[i].id);
                   document.getElementById(texts[i].id).required = true;
				   document.getElementById('lblstatus').innerHTML = "Added required";
			}
        }
}
</script>		
</html>

 



Leave a Comment: