почему динамически добавленные поля не удаляются нажатием кнопки «удалить»? - PullRequest
0 голосов
/ 28 ноября 2018

вот мой код, при добавлении поля ввода, нажав кнопку добавления, чтобы появилось поле, но после попытки удалить эти поля, удалив кнопку, чтобы она не работала.

$(document).ready(function() {
    //@naresh action dynamic childs
    var next = 0;
    $("#add-more").click(function(e) {
        e.preventDefault();
        var addto = "#field" + next;
        var addRemove = "#field" + (next);
        next = next + 1;
        var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12"   name="PeriodFrom[]"   class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text"  name="PeriodTo[]" placeholder="Check Out Date"  class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed"    value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years"  id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS"   value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB"  name="MaxCNB[]"   value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
        var newInput = $(newIn);
        var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
        var removeButton = $(removeBtn);
        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source', $(addto).attr('data-source'));
        $("#count").val(next);

        $('body').on('click', '.remove-me', function(e) {
            e.preventDefault();
            var fieldNum = this.id.charAt(this.id.length - 1);
            var fieldID = "#field" + fieldNum;
            $(this).remove();
            $(fieldID).remove();
        });
    });

});
<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   </head>
   <body>
      <div id="right-panel" class="right-panel">
         <div class="content mt-3" >
            <div class="animated fadeIn">
               <div class="row" style="border:none;">
                  <div class="col-md-12">
                     <div class="card" >
                        <div class="card-header">
                           <div class="row"  >
                              <i class="fa fa-hotel" style="font-size:24px;"></i>
                              <h4 style=" font-family: 'Ubuntu',sans-serif;margin-left:20px;"> Manage Hotels </h4>
                           </div>
                        </div>
                        <div class="card-body">
                           <form method="post" action="<?php echo base_url(); ?>Admin/Insert-Hotels">
                              <div class="card-body card-block">
                                 <div class="form-group">
                                    <div class="col-6" id="content">
                                       <label for="vat" ></label><input type="text" id="datepicker_recurring_start"   name="PeriodFrom[]"   class=" datepicker_recurring_start" placeholder="Check In Date" value="" required="required">
                                    </div>
                                    <div class="col-6" id="content">
                                       <label for="street" ></label><input type="text"  id="datepicker-13" name="PeriodTo[]"  class=" datepicker_recurring_start" placeholder="Check Out Date" value="" required="required">
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <div class="col-6">
                                       <label for="vat" ></label><input type="text" id="DoubleBed" name="MaxDoubleBed[]"    value="" placeholder="Max Rate Double Bed" required="required">
                                    </div>
                                    <div class="col-6">
                                       <label for="postal-code" ></label><input type="text" id="SigleBed" name="MaxSigleBad[]"   value="" placeholder="Max Rate Sigle Bed" required="required">
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <div class="col-6">
                                       <label for="postal-code" ></label><input type="text" id="CNB"  name="MaxCNB[]"   value="" required="required" placeholder="Max Rate CNB">
                                    </div>
                                    <div class="col-6">
                                       <label for="postal-code" ></label> 
                                       <select name="cityID" id="cityID" class="-md " required="required">
                                          <option value="">Select Country and City</option>
                                          <?php
                                             foreach ($fatch_hotels_country as $key => $fatch_hotels_country) {
                                             
                                                 echo "<option value='".$fatch_hotels_country->id."'>".$fatch_hotels_country->citiesName."</option>";
                                             }
                                             ?>
                                       </select>
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <label for="postal-code" ></label>
                                    <label for="company" ></label><input type="text" id="HotelName" name="Star"   value="" required="required" placeholder="Star">
                                 </div>
                              </div>
                              <!-----------------------------------   Add More Data Start -------------------------->
                              <div class=" form-group">
                                 <div id="field">
                                    <div id="field0">
                                    </div>
                                 </div >
                                 <!-----------------------------------   Add More Data End -------------------------->
                              </div>
                        </div>
                        <div class="modal-footer">
                        <input type="reset"  class="btn btn-danger" value="Reset">
                        <input type="submit"  class="btn btn-primary" value="Insert">
                        <button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
                        </div>
                     </div>
                  </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
      </div>
      </div>
      </div>
      </div>
      </div>
   </body>
</html>

здесь вы можете видеть, я пытаюсь добавить поля ввода, нажав кнопку «Добавить еще» справа внизу справа.во время отображения полей вы можете увидеть кнопку «удалить» справа вверху динамически добавленных полей ввода.при нажатии на эту кнопку, чтобы эти поля не были удалены.

Ответы [ 3 ]

0 голосов
/ 28 ноября 2018

Кажется, что удаляемый идентификатор div ошибается, поэтому

Измените

var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;

на

 var fieldNum = +this.id.charAt(this.id.length - 1);
 var fieldID = "#field" + parseFloat(fieldNum + 1);

и добавьте

next = fieldNum;

в $('body').on('click', '.remove-me', function(e) {

ДЕМО ЗДЕСЬ

0 голосов
/ 28 ноября 2018

<html><head>
    <style>
        
    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script><style type="text/css">.as-console-wrapper { position: fixed; bottom: 0; left: 0; right: 0; max-height: 150px; overflow-y: scroll; overflow-x: hidden; border-top: 1px solid #000; display: none; }
.as-console { background: #e9e9e9; border: 1px solid #ccc; display: table; width: 100%; border-collapse: collapse; }
.as-console-row { display: table-row; font-family: monospace; font-size: 13px; }
.as-console-row:after { display: table-cell; padding: 3px 6px; color: rgba(0,0,0,.35); border: 1px solid #ccc; content: attr(data-date); vertical-align: top; }
.as-console-row + .as-console-row > * { border: 1px solid #ccc; }
.as-console-row-code { width: 100%; white-space: pre-wrap; padding: 3px 5px; display: table-cell; font-family: monospace; font-size: 13px; vertical-align: middle; }
.as-console-error:before { content: 'Error: '; color: #f00; }
.as-console-assert:before { content: 'Assertion failed: '; color: #f00; }
.as-console-info:before { content: 'Info: '; color: #00f; }
.as-console-warning:before { content: 'Warning: '; color: #e90 }
@-webkit-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-moz-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-ms-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
.as-console-row-code, .as-console-row:after { -webkit-animation: flash 1s; -moz-animation: flash 1s; -ms-animation: flash 1s; animation: flash 1s; }</style>
    </head>
<body>
    

   
      <title></title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   
   
      <div id="right-panel" class="right-panel">
         <div class="content mt-3">
            <div class="animated fadeIn">
               <div class="row" style="border:none;">
                  <div class="col-md-12">
                     <div class="card">
                        <div class="card-header">
                           <div class="row">
                              <i class="fa fa-hotel" style="font-size:24px;"></i>
                              <h4 style=" font-family: 'Ubuntu',sans-serif;margin-left:20px;"> Manage Hotels </h4>
                           </div>
                        </div>
                        <div class="card-body">
                           <form method="post" action="&lt;?php echo base_url(); ?&gt;Admin/Insert-Hotels">
                              <div class="card-body card-block">
                                 <div class="form-group">
                                    <div class="col-6" id="content">
                                       <label for="vat"></label><input type="text" id="datepicker_recurring_start" name="PeriodFrom[]" class=" datepicker_recurring_start" placeholder="Check In Date" value="" required="required">
                                    </div>
                                    <div class="col-6" id="content">
                                       <label for="street"></label><input type="text" id="datepicker-13" name="PeriodTo[]" class=" datepicker_recurring_start" placeholder="Check Out Date" value="" required="required">
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <div class="col-6">
                                       <label for="vat"></label><input type="text" id="DoubleBed" name="MaxDoubleBed[]" value="" placeholder="Max Rate Double Bed" required="required">
                                    </div>
                                    <div class="col-6">
                                       <label for="postal-code"></label><input type="text" id="SigleBed" name="MaxSigleBad[]" value="" placeholder="Max Rate Sigle Bed" required="required">
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <div class="col-6">
                                       <label for="postal-code"></label><input type="text" id="CNB" name="MaxCNB[]" value="" required="required" placeholder="Max Rate CNB">
                                    </div>
                                    <div class="col-6">
                                       <label for="postal-code"></label> 
                                       <select name="cityID" id="cityID" class="-md " required="required">
                                          <option value="">Select Country and City</option>
                                          <!--?php
                                             foreach ($fatch_hotels_country as $key =--> $fatch_hotels_country) {
                                             
                                                 echo "<option value="&quot;.$fatch_hotels_country->id.&quot;">".$fatch_hotels_country-&gt;citiesName."</option>";
                                             }
                                             ?&gt;
                                       </select>
                                    </div>
                                 </div>
                                 <div class=" form-group">
                                    <label for="postal-code"></label>
                                    <label for="company"></label><input type="text" id="HotelName" name="Star" value="" required="required" placeholder="Star">
                                 </div>
                              </div>
                              <!-----------------------------------   Add More Data Start -------------------------->
                              <div class=" form-group">
                                 <div id="field">
                                    <div id="field0">
                                    </div>
                                 </div>
                                 <!-----------------------------------   Add More Data End -------------------------->
                              </div>
                        </form></div>
                        <div class="modal-footer">
                        <input type="reset" class="btn btn-danger" value="Reset">
                        <input type="submit" class="btn btn-primary" value="Insert">
                        <button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
                        </div>
                     </div>
                  </div>
                  
               </div>
            </div>
         </div>
      </div>
      
      
      
      
      
   

    <script type="text/javascript">
        $(document).ready(function() {
    //@naresh action dynamic childs
    var next = 0;
    $("#add-more").click(function(e) {
        e.preventDefault();
        var addto = "#field" + next;
        var addRemove = "#field" + (next);
        next = next + 1;
        var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12"   name="PeriodFrom[]"   class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text"  name="PeriodTo[]" placeholder="Check Out Date"  class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed"    value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years"  id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS"   value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB"  name="MaxCNB[]"   value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
        var newInput = $(newIn);
        var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div class="field"></div>';
        var removeButton = $(removeBtn);
        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source', $(addto).attr('data-source'));
        $("#count").val(next);

        $('body').on('click', '.remove-me', function(e) {
            e.preventDefault();
            var fieldNum = parseInt(this.id.charAt(this.id.length - 1))+1;
            var fieldID = "#field" + fieldNum;
            $(this).remove();
            $(fieldID).remove();
        });
    });

});
    </script>

<div class="as-console-wrapper"><div class="as-console"></div></div></body></html>
0 голосов
/ 28 ноября 2018

Попробуйте это

$(document).ready(function() {
  //@naresh action dynamic childs
  var next = 0;
  $("#add-more").click(function(e) {
      e.preventDefault();
      var addto = "#field" + next;
      var addRemove = "#field" + (next);
      next = next + 1;
      var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--> <div class="form-group"> <div class="col-6"> <label for="vat" ></label><input type="text" placeholder="Check In Date" id="datepicker-12"   name="PeriodFrom[]"   class=" datepicker_recurring_start" value=""></div><div class="col-6"><label for="street" ></label><input type="text"  name="PeriodTo[]" placeholder="Check Out Date"  class=" datepicker_recurring_start" value=""></div></div><div class="form-group"><div class="col-6"><label for="vat" ></label><input type="text" id="DoubleBad" name="DoubleBad" placeholder="Double Bed"    value=""></div><div class="col-6"><label for="street" ></label><input type="text" placeholder="Above 12 Years"  id="EXTRA_ADL_ABOVE_12_YRS" name="EXTRA_ADL_ABOVE_12_YRS"   value=""></div></div><div class=" form-group"> <label for="postal-code" > </label><label for="postal-code" ></label><input type="text" id="CNB"  name="MaxCNB[]"   value="" required="required" placeholder="Max Rate CNB"> </div> </div>';
      var newInput = $(newIn);
      var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
      var removeButton = $(removeBtn);
      $(addto).after(newInput);
      $(addRemove).after(removeButton);
      $("#field" + next).attr('data-source', $(addto).attr('data-source'));
     $("#count").val(next);
 });

  $(document).on('click', '.remove-me', function(e) {
      e.preventDefault();
      var fieldNum = this.id.charAt(this.id.length - 1);
      var fieldID = "#field" + fieldNum;
      $(this).remove();
      $(fieldID).remove();
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...