【问题标题】:How can I add input field and select dynamically?如何添加输入字段并动态选择?
【发布时间】:2018-07-07 14:23:40
【问题描述】:

我有一个输入字段和一个带有 MySQL 值的选择选项。如何动态添加更多输入字段并使用 MySQL 值进行选择?我正在尝试解决这个问题,但结果很糟糕:

我想用它来更新我的数据库,我可以用它更新多个数据,但是删除以前的字段按钮不起作用,最后有 +1 添加更多按钮。我怎么解决这个问题?我正在尝试使用 append 方法,但它不适用于 MySQL 数据。

index.php

<div class="form-group add-field">
  <div class="partner">    
    <table>
      <tr>
        <td>
          <select name="partnerSelect[]" id="partnerSelect" class="form-control">
          <option disabled selected value> -- select an option -- </option>
          <?php                                       
            while($row = $partnerResult -> fetch_array()) {
          ?>
          <option value="<?php echo $row['partner_id'];?>"><?php echo $row['partner'];?></option>
          <?php
            }
          ?>
          </select>  
        </td>
        <td><input type="text" placeholder="Enter description" name="description[]" id="description" class="form-control" /></td>
      </tr>
    </table>
  </div>
  <div class="btn btn-warning add-more"><span>+ Add More</span></div>
</div>

<script>
$(document).ready(function(){

    var data_fo = $('.add-field').html();
    var sd = '<div class="btn btn-danger remove-add-more">Remove</div>';
    var data_combine = data_fo.concat(sd);
    var max_fields = 5; //maximum input boxes allowed
    var wrapper = $(".partner"); //Fields wrapper
    var add_button = $(".add-more"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
      e.preventDefault();
      if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append(data_combine); //add input box
        //$(wrapper).append('<div class="remove-add-more">Remove</div>')
      }
      // console.log(data_fo);
    });

    $(wrapper).on("click",".remove-add-more", function(e){ //user click on remove text
        e.preventDefault();
        $(this).prev('.partner').remove();
        //$(".add-more").prev('.user').remove(); It's remove all the buttons and inputs
        $(this).remove();
        x--;
    });
 });
</script>

【问题讨论】:

  • 您可以使用 jQuery Repeater 克隆字段http://briandetering.net/repeater

标签: javascript jquery html mysql


【解决方案1】:

你很接近,只是有几件事有点不对劲。我使您的代码保持相同的格式,但对其进行了一些清理。如果您有任何问题,请告诉我。

$(document).ready(function(){

    var data_fo = $('.partner').html();
    var sd = '<div class="btn btn-danger remove-add-more">Remove</div>';
    var max_fields = 5; //maximum input boxes allowed
    var wrapper = $(".partners"); //Fields wrapper
    var add_button = $(".add-more"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
      e.preventDefault();
      if(x < max_fields){ //max input box allowed
        x++; //text box increment
        var partnerClone = $('.partner').first().clone();
        $(sd).appendTo(partnerClone);
        $(wrapper).append(partnerClone);
      }
    });

    $(wrapper).on("click",".remove-add-more", function(e){ //user click on remove text
        e.preventDefault();
        $(this).parent('.partner').remove();
        $(this).remove();
        x--;
    });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group add-field">
  <div class="partners">  
    <div class="partner">
      <table>
        <tr>
          <td>
            <select name="partnerSelect[]" id="partnerSelect" class="form-control">
            <option disabled selected value> -- select an option -- </option>
            <?php                                       
              while($row = $partnerResult -> fetch_array()) {
            ?>
            <option value="<?php echo $row['partner_id'];?>"><?php echo $row['partner'];?></option>
            <?php
              }
            ?>
            </select>  
          </td>
          <td><input type="text" placeholder="Enter description" name="description[]" id="description" class="form-control" /></td>
        </tr>
      </table>
    </div>
  </div>
  <div class="btn btn-warning add-more"><span>+ Add More</span></div>
</div>

我把它放在一个 sn-p 中,这样你就可以在这里运行它。但是您可以返回并像以前一样将 Jquery 放在脚本标签中

【讨论】:

    【解决方案2】:

       <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> 
    <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
    <script>
    $(document).ready(function(){
    $("#AddData").html(AddTr())
    
    function AddTr(){
    var html="<tr id="+($('tr').length)+"><td align=\"center\">"+($('tr').length)+"</td><td><input type=\"text\" id=\"narration_"+($('tr').length)+"\" class=\"form-control sannarration valid\" ></td><td><input type=\"text\" id=\"txtremarksan_"+($('tr').length)+"\" class=\"form-control sannarration valid\"></td><td><input type=\"text\" id=\"DocSub_"+($('tr').length)+"\" class=\"form-control sannarration valid\" ></td><td align=\"center\"><a href=\"javascript:;\" class=\"onlyIcon EditsancationIcon\" onclick=\"Editsanctioncondtion(this);\" title=\"Edit\"><i class=\"fa fa-pencil fa-2x\" aria-hidden=\"true\"></i></a> <a href=\"javascript:;\" class=\"onlyIcon deleteIcon text-danger\" title=\"Delete\" onclick=\"Delete(this,event)\";\"><i class=\"fa fa-times fa-2x\" aria-hidden=\"true\"></i></a></td></tr>"
    return html;
    }
    
    $('#addrow').on('click',function(){
    $("table tbody").append(AddTr());
    })
    
    $('#Submit').on('click',function(){
    NodeId=[];
    TblHead=[];
    $('th').each(function(){
    TblHead.push($(this).text())
    })
    
    for(var i=1;i<=parseInt($('tr').length-1);i++)
    {
    Obj={};
    var index=0;
    $('tr[id="'+i+'"] td').each(function(){
    debugger
    Obj[TblHead[index]]=$("#"+$(this).children(':first').attr('id')).val();
    index++;
    })
    NodeId.push(Obj)
    }
    console.log(NodeId)
    alert(JSON.stringify(NodeId))
    })
    
    })
    function Delete(ele,event){
    if(($('tr').length-1)>1)
    {
    debugger;
         $(ele).closest("tr").remove();
    	 reset(parseInt(event.currentTarget.previousSibling.parentNode.parentNode.id)) 
        }
    	}
    function reset (Getid)
    {
    debugger;
    var count=Getid;
    $('tr').each(function(){
    if($(this)[0].id>=parseInt(Getid+1))
    {
    $(this).attr('id',count);
    $(this).children('td:first').text(count)
    $(this).children('td:first').next('td').children('input').attr('id','narration_'+count+'')
    $(this).children('td:first').next('td').next('td').children('input').attr('id','txtremarksan_'+count+'')
    $(this).children('td:first').next('td').next('td').next('td').children('input').attr('id','DocSub_'+count+'')
    count++;
    }
    })
    }	
                
            </script>
    
    <body>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <head>
            
            <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
            <link href="ASSETS/BT-CP/css/bootstrap-colorpicker.css" rel="stylesheet">
            <link rel="stylesheet" href="ASSETS/CSS/costum.css">
            
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
            <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
            <script src="ASSETS/BT-CP/js/bootstrap-colorpicker.js"></script>
            
        </head>
        
        <body>
    
          <table cellspacing="0" rules="all" class="table table-striped table-bordered table-hover" border="1" id="tblsanctioncondtion" style="border-collapse:collapse;">
    
                                                        <thead>
                                                            <tr>
                                                                <th align="center" scope="col">Sr.No</th>
                                                                <th scope="col">Narration</th>
                                                                <th scope="col">Remark</th>
                                                                <th scope="col">Documents Submittion Date</th>
                                                                <th align="center" scope="col">Action</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody id="AddData">
    													
    													</tbody>
                                                    </table>
    												<button type="button" class="btn btn-primary btn-small pull-right" id="addrow" style="margin-bottom:10px;"><i class="fa fa-plus-circle" aria-hidden="true"></i> Add</button>
    												<button type="button" class="btn btn-primary btn-small pull-right" id="Submit" style="margin-bottom:10px;"><i class="fa fa-check-circle" aria-hidden="true"></i> Submit</button>
        </body>
        </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多