簡體   English   中英

jQuery-動態輸入框以及每行中的添加/刪除按鈕

[英]Jquery - Dynamic Input Box along with add/ remove button in every row

基於JQuery的UI,用戶可以在其中動態添加輸入框。 它應該如下所示。

默認外觀:

  • INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON]

單擊[Add_Button],添加另一行,如下所示,依此類推

  • INPUT_BOX [DISABLED_ADD_BUTTON] [REMOVE_BUTTON]
  • INPUT_BOX [DISABLED_ADD_BUTTON] [REMOVE_BUTTON]
  • INPUT_BOX [DISABLED_ADD_BUTTON] [REMOVE_BUTTON]
  • INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON]

以下方法創建了類似的方法,但是新添加的添加按鈕不起作用。 僅第一行的“添加”按鈕有效

     var x = 1; //initial text box count
     $(".add_field_button").click(function(e){ //on add input button click
                  e.preventDefault();
                  if(x < max_fields){ //max input box allowed
                      x++; //text box increment
                      $("#input_fields_wrap").append('<div style="padding-top:4px">\n<label></label>\n<input name="key_'+ x +'" class="key-value">\n<input name="value_'+ x +'" class="key-value">\n<button class="add_field_button" name="add" type="button">Add</button>\n<button name="remove" class="remove_field" type="button">Remove</button>\n</div>'); 
                  }
 });

   $("#input_fields_wrap").on("click",".remove_field", function(e){ //user click on remove text
                  e.preventDefault(); $(this).parent('div').remove(); x--;
});

使用的HTML代碼段:

        <div id="input_fields_wrap">
          <div>
            <label>Properties</label>
            <input class="key-value" name="key_0" />
            <input class="key-value" name="value_0" />
            <button type="button" name="add" class="add_field_button">Add</button>
            <button type="button" class="remove_field" name="remove">Remove</button>
           </div>
        </div>

我的要求是每行添加按鈕和刪除按鈕都處於活動狀態。 尋求幫助。

謝謝。

嘗試將event delegation用於添加按鈕,

$("#input_fields_wrap").on("click", ".add_field_button", function(e) { 

第一個添加按鈕將起作用,因為在您為其注冊事件時它將在DOM中可用。 但是在事件連接期間無法匹配稍后將添加的按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM