Javascript InnerHTML Erases Data In Form Elements

前端 未结 4 1846
灰色年华
灰色年华 2021-01-22 05:32

I have this form with a button that allows you to add fields to the form.

相关标签:
4条回答
  • 2021-01-22 05:46

    For one thing, try spelling it "label" not "lable". For another, you are setting the "innerHTML" property of d, so of course you are wiping out any existing values.

    0 讨论(0)
  • 2021-01-22 05:47

    When you set the innerHTML property, the browser parses the HTML and creates a new DOM tree for it, then replaces the current DOM tree with the new one. This destroys any data that isn't in the HTML.

    You need to append DOM elements using createElement and appendChild or using jQuery (easier).

    0 讨论(0)
  • 2021-01-22 05:50

    Give the <ol> element an ID:

    <ol id="answers">
        ...
    </ol>
    

    Then change the first line in your function to:

    var d=document.getElementById("answers");
    

    Once you make the changes mentioned above, it should work. I have tested it in Firefox, Chrome, Safari, and IE8. And as others have mentioned, you should also correct your spelling of "label".

    0 讨论(0)
  • 2021-01-22 06:03

    The value attribute of the HTML element is not updated to reflect the current value of the input element... see this related question

    You can avoid using the innerHTML property entirely by using createElement and appendChild.

    Instead of:

    d.innerHTML+='<li><lable for=' + y + '>Answer:</lable><input name="' + y + '" id="' + y    + '" type="text" size="66"/> </li>';
    

    You can try:

    var li = document.createElement('li');
    li.for = y;
    li.innerHTML = 'Answer:'
    
    var input = document.createElement('input');
    input.name=y;
    input.id = y;
    input.size=66;
    
    d.appendChild(li);
    d.appendChild(input);
    
    0 讨论(0)
提交回复
热议问题