I have a form for which all text boxes should be filled before submission. my form looks like this
<form name="form" method="post" action="url" onsubmit="return checkEmpty(this)" >
<div class="field">
<label>field1</label><input type="text" name="f1" />
</div>
<div class="field">
<label>field2</label><input type="text" name="f2" />
</div>
..
....
......
input type="submit" name="Submit" value="submit" />
</form>
what i do here is that when a form is submitted i check if any text box is empty and if there is any i create a dom element h3 and append it to the div of that corresponding field and if the text box is not empty i check if there is any text box attached to that corresponding field and if i find one i remove it. here is my javascript code
function checkEmpty(form) {
var textboxes=form.elements;
for(var i=0;i<textboxes.length;i++)
{
if((textboxes[i].type=="text" || textboxes[i].type=="password") && textboxes[i].textLength==0) //text box is empty
{
var msg=document.createElement('h3');
msg.innerHTML="u cant leave this field blank";
textboxes[i].parentNode.appendChild(msg);
return false;
}
else //text box is not empty
{
var rem_msg=textboxes[i].parentNode.getElementsByTagName('h3');
for(var j=0;j<rem_msg.length;j++)
textboxes[i].parentNode.removeChild(rem_msg[j]);
}
}
}
Now the browser freezes when i submit the form.
*Also my code doesnt work in ggogle chrome but only firefox*
Until i was not removing elements the code was working fine but removing element is neccessary because say a user doesnt enter any value in text box 1 on first attempt so an h3 element would be added but now he enters some text in first text box but leaves second text box empty so the h3 element of first text box should dissappear.
because of the answer below the code
is no more freezing the browser but
still i am only able to addh3
elements to the dom but cannot remove
them.also the code works in firefox
but not in google chrome.
Problem is you are using the variable
iin two distinct loops. When the inner loop finishes it will always end up settingitorem_msg.length, which will keep the outer loop from ever reaching its exit condition so you end up with an infinite loop.To fix your problem you simply need to rename the second
ito e.g.jand you’re good to go.