1

我有一个网页。有一个按钮叫做添加。单击此添加按钮时,必须添加 1 个文本框。这应该只发生在客户端。我想允许用户最多添加 10 个文本框。

如何使用 javascript 实现它?

例子:

  • 仅显示 1 个文本框
  • 用户点击添加 >
  • 显示 2 个文本框
  • 用户点击添加 >

我还想提供一个名为“删除”的按钮,用户可以通过该按钮删除多余的文本框

任何人都可以为此提供一个javascript代码吗?

4

3 回答 3

1

未经测试,但这应该有效(假设存在具有正确 id 的元素);

var add_input = function () {

    var count = 0;

    return function add_input() {
        count++;
        if (count >= 10) {
            return false;
        }
        var input = document.createElement('input');
        input.name = 'generated_input';
        document.getElementbyId('inputs_contained').appendChild(input);
    }

}();

add_input();
add_input();
add_input();
于 2009-08-09T10:39:59.083 回答
1

使用jQuery框架的解决方案:

<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>

jQuery脚本代码:

$(function(){
  $(".addbutton").click(){
     if(".addedfields").length < 10){
       $(".addedfields").append(
         '<li><input type="text" name="field[]" class="textbox" />' + 
         '<input type="button" class="removebutton" value="remove"/></li>'
       );
     }
  }

  // live event will automatically be attached to every new remove button
  $(".removebutton").live("click",function(){
     $(this).parent().remove();
  });
});

注意:我没有测试代码。

编辑:更改了错误的引号

于 2009-08-09T10:41:48.860 回答
1

我希望你正在使用 jQuery。

<script src="jquery.js" type="text/javascript"></script> 
<script type="text/javascript"><!--


    $(document).ready(function(){

    var counter = 2;
    $("#add").click(function () {
    if(counter==11){
        alert("Too many boxes");
        return false;
    }   
        $("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
        ++counter;
    });

    $("#remove").click(function () {
    if(counter==1){
        alert("Can u see any boxes");
        return false;
    }   
        --counter;
        $("#d"+counter).remove();
    });
  });
// --></script>
</head><body>

 <div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>
于 2009-08-09T10:43:07.780 回答