最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to add text boxes dynamically without losing values of previous textboxes? - Stack Overflow

programmeradmin0浏览0评论

i am using innerHTML to add text boxes dynamically. The code sample is as follows:

<html>
<head>
  <script type="text/javascript" >
  var i=0;
  function add()
  {
    var tag = "<input type='text' name='" + i + "' /> <br/>";
    document.getElementById("y").innerHTML += tag;
    i++;
  }
  </script>
</head>

<body>
  <input type="button" id="x" value="Add" onclick="add();" />
  <div id="y"></div>
</body>

</html

Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(

What if I want to add textbox in this situation:

function add() {
   var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
   document.getElementById("addskills").innerHTML += element;
   i++;
}

i am using innerHTML to add text boxes dynamically. The code sample is as follows:

<html>
<head>
  <script type="text/javascript" >
  var i=0;
  function add()
  {
    var tag = "<input type='text' name='" + i + "' /> <br/>";
    document.getElementById("y").innerHTML += tag;
    i++;
  }
  </script>
</head>

<body>
  <input type="button" id="x" value="Add" onclick="add();" />
  <div id="y"></div>
</body>

</html

Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(

What if I want to add textbox in this situation:

function add() {
   var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
   document.getElementById("addskills").innerHTML += element;
   i++;
}
Share Improve this question edited Feb 2, 2013 at 18:09 xpda 15.8k8 gold badges53 silver badges83 bronze badges asked Jan 23, 2013 at 15:31 nbbknbbk 1,1022 gold badges14 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Yes, through DOM Manipulation:

function add() {
    var tag = document.createElement('input'); // Create a `input` element,
    tag.setAttribute('type', 'text');          // Set it's `type` attribute,
    tag.setAttribute('name', i);               // Set it's `name` attribute,

    var br = document.createElement('br');     // Create a `br` element,

    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(tag);                        // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.

(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)

Now, to add this:

<li class="ie7fix" style="width:620px;">
    <div class="m_elementwrapper" style="float:left;">
        <label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
            <span>
                <span class="pspan arial" style="text-align:right;font-size:14px;">
                    <span class="ispan" xml:space="preserve">
                    </span>
                </span>
            </span>
        </label>
        <div style="float:left;width:475px;" class="m_elementwrapper">
            <input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent">
            <div class="fielderror">
            </div>
        </div>
    </div>
    <div style="clear:both;font-size:0;">
    </div>
</li>

You'll need:

function add() {
    // Create elements
    var d1 = c('div'),  s1 = c('span'), ip = c('input'),
        d2 = c('div'),  s2 = c('span'), li = c('li'),
        d3 = c('div'),  s3 = c('span'), la = c('label'),
        d4 = c('div');
    // You can "chain" `appendChild`.
    // `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
    li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
    d1.appendChild(d2).appendChild(ip);
    d2.appendChild(d3);
    li.appendChild(d4);

    setAttributes(
        [li, d1, la, s2, s3, d2, ip, d3, d4],
        [
            {'class':"ie7fix",              'style':"width:620px;"  },
            {'class':"m_elementwrapper",    'style':"float:left;"   },
            {'class':"fieldlabel",          'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
            {'class':"pspan arial",         'style':"text-align:right;font-size:14px;"  },
            {'class':"ispan",               'xml:space':"preserve"  },
            {'class':"m_elementwrapper",    'style':"float:left;width:475px;"   },
            {'class':"fieldcontent",        'type':"text",      'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
            {'class':"fielderror"   },
            {'style':"clear:both;font-size:0;"  }
        ]
    );
    var br = document.createElement('br');     // Create a `br` element,
    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(li);                         // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
    var el = elements.length,
        al = attributes.length;
    if(el === al){
        for(var n = 0; n < el; n++){
            var e = elements[n],
                a = attributes[n];
            for(var key in a){
                e.setAttribute(key, a[key]);
            }
        }
    }else{
        console.error("Elements length " + el + " does not match Attributes length " + al);
    }
}

// Alias for shorter code.
function c(type){
    return document.createElement(type);
};

use jquery library

<html>
<head>
  <script src='jquery.js' type="text/javascript"></script>
  <script type="text/javascript" >
      var i=0;
      function add()
      {
        var tag = "<input type='text' name='" + i + "' /> <br/>";
        var div_content=$('#y').append(tag);
        i++;
      }
    </script>
</head>
<body>
   <input type="button" id="x" value="Add" onclick="add();" />
   <div id="y"></div>
</body>
</html>

I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:

<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
    values=new Array();
    for(z=0;z<i;z++) {
        values.push(document.getElementById(z).value);
        }
    }
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
    for(z=0;z<i;z++) {
        document.getElementById(z).value=values[z];
    }
}
i++;
}
</script>
</head>

<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论