开发者

just able to add dom elements but not remove them

开发者 https://www.devze.com 2023-03-19 08:41 出处:网络
i am not able to remove elements from the dom. i am using firfox. my code looks like this i have a form for which all text boxes should be filled before submission. my form looks like this

i am not able to remove elements from the dom. i am using firfox. my code looks like this

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,this code works in firefox but not in chrome                     
      {
         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,this code neither works in firefox nor in chrome 
      {
         var rem_msg=textboxes[i].parentNode.getElementsByTagName('h3');
         for(var j=0;j<rem_msg.length;j++)
            textboxes[i].parentNode.removeChild(rem_msg[j]);
      }
   }
}

Until i was not removing elements the code was working fine but removing element is neccessary because for example 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 sec开发者_开发问答ond text box empty so the h3 element of first text box should dissappear. the code looks really simple, i am getting the reference of a node and then passing in to appendChild or removeChild. Also i am not even able to add elements to the dom in google chrome


if you change the line that creates the error to if ((textboxes[i].type == "text" || textboxes[i].type == "password") && textboxes[i].value == "") possible will work


Try this one:

 rem_msg[j].parentNode.removeChild(rem_msg[j]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号