繁体   English   中英

如何在按钮单击时添加输入并创建新的 append 删除按钮以删除新输入?

[英]How to add input on button click and create the new append a remove button to remove the new input?

如何在按钮单击时添加输入字段这是给出的答案我想将其添加到我的表单中

这是我的代码段

 $('.add1').on('click', add); $('.remove1').on('click','.remove1', remove); function add() { var new_chq_no = parseInt($('#total_chq').val()) + 1; var new_input = "<input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'>"; $('#new_chq').append(new_input); $('#total_chq').val(new_chq_no); } function remove() { var last_chq_no = $('#total_chq').val(); if (last_chq_no > 1) { $('#new_' + last_chq_no).remove(); $('#total_chq').val(last_chq_no - 1); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-group row"> <label for="contact" class="col-2 col-form-label">Contact Name:</label> <div class="col-4" id="contactContainername"> <div class="flex contactname" style="margin-bottom:10px;"> <input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required> <input style="border-radius: 5px;" type="button" class="add1 btn-primary" value="Add More Field" style="cursor: pointer;"> <input type="button" class="remove1" value="x"><label style="cursor: pointer; padding-top: 5px;"> <i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span> </div> </div> </div> <div class="form-group row"> <label for="contact" class="col-2 col-form-label"></label> <div class="col-4" id="contactContainername"> <div id="new_chq" class="flex contactname" style="margin-bottom:10px;"> <input type="hidden" value="1" id="total_chq" style="margin-right: 10px; width: 200px;" name="contactname" class="form-control" placeholder="Name" required> </div> </div> </div>

我希望当按下更多字段时会出现一个带有按钮 x 的新输入,您可以在其中单击并删除新输入 这里是我的意思的图像

在此处输入图像描述

我该怎么做?

您可以做以下两件事之一

$('body').on('click','.remove1', remove);

或附加到您的元素

 var new_input = $("<input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'>");
new_input.on('click',remove)

但是要让您的代码正确运行,您还必须修复您的删除 function,这是它的外观示例

$('.add1').on('click', add);
$('body').on('click','.remove1', remove);

function add() {
  var new_chq_no = parseInt($('#total_chq').val()) + 1;
  var new_input = "<label><input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'></label>";

  $('#new_chq').append(new_input);

  $('#total_chq').val(new_chq_no);
}

function remove() {
  var last_chq_no = $('#total_chq').val();
    $(this).closest('label').remove()
  $('#total_chq' + '.remove1').val(last_chq_no - 1);
  
}

暂无
暂无

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

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