Reputation: 5401
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 add
h3
elements to the dom but cannot remove them.also the code works in firefox but not in google chrome.
Upvotes: 2
Views: 2013
Reputation: 38289
Problem is you are using the variable i
in two distinct loops. When the inner loop finishes it will always end up setting i
to rem_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 i
to e.g. j
and you're good to go.
Upvotes: 3
Reputation: 78650
I think it may be the malformed for
:
for(var i=0;i<rem_msg.length;;i++)
You have an extra ;
so I think the i++
isn't getting run.
Upvotes: 1