Add validation on dynamically added form elements in JavaScript

Js

Posted on 14 Oct 15 by Vickey
  1175



In some cases we add form elements by using DOM and we add multiple input box dynamically. For validate all fields we can use the below script. In the below code 'elementsclass' is a class of these elements, by this class we can get all elements and validate them one by one

function validate_form(){
    var error = 1;
    var time = document.getElementsByClassName("elementsclass");
    for (var i = 0; i < time.length; i++)
    {
       if (time[i].value=='') {
           error = 1;
           alert("Please insert value");
           break;
       }
	   else
	   {
            error = 0;
       }
    }
    if (error==0) {
        return true;
    }
    else{
    	return false; 
    }
}

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com