簡體   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