繁体   English   中英

使用JavaScript添加新文本框

[英]Adding new text box using javascript

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

如何使用javascript实现它?

例:

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

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

谁能为此提供一个JavaScript代码?

未经测试,但这应该可以工作(假设存在具有正确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();

使用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();
  });
});

注意:我没有测试代码。

编辑:更改错误的引号

我希望您使用的是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'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM