jquery 如何将动态输入字段提交到数据库中?

ycggw6v2  于 2023-06-29  发布在  jQuery
关注(0)|答案(2)|浏览(144)

我显示的输入字段动态这是为我工作。
我必须提交表格。我已经尝试了一些代码如下,但它不工作。
我正在使用CodeIgniter。

控制器代码

public function register(){
$save = array(
   'pp_fileStatus' => $this->input->post('pp_fileStatus');
   'reasonDate' => $this->input->post('reasonDate');
   'reasonAmt' => $this->input->post('reasonAmt');
 );
$afterxss=$this->security->xss_clean($save);
        if ($afterxss) 
        { 
          $this->db->insert('tbl_register',$afterxss);
            $response['error'] = "true";
            $response['msg']   = "Successfully";
        
      }else{
          $response['error'] = "false";
          $response['msg']   = "Sometning wrong! please check the internet connection and try again";
      } 
   echo json_encode($response);          
}

我动态添加字段并递增名称。我在这里要用什么名字?

$save = array(
       'pp_fileStatus' => $this->input->post('pp_fileStatus');
       'reasonDate' => $this->input->post('reasonDate');
       'reasonAmt' => $this->input->post('reasonAmt');
     );

下面是动态添加输入字段的代码。

$(document).ready(function() {
  var maxField = 10; //Input fields increment limitation
  var x = 1; //Initial field counter is 1
  var count = 2;
  var numberIncr = 1; // used to increment the name for the inputs
  var addrm = '';

  //Once add button is clicked
  $(document).on('click', '#clicktoadd', function() {
    //Check maximum number of input fields
    if (x < maxField) {
      x++; //Increment field counter
      numberIncr++;
      $(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>');
    }
    count++;

  });
  $(document).on('change', '.pp_fileStatus', function(event) {

    if (($(this).val() == '1') || ($(this).val() == '3')) {
      $(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '"  class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '"  class="form-control commnumber dynamicVal" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '"  class="form-control" placeholder="Remark">');
    } else {
      $(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '"  class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '"  class="form-control dynamicVal" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
    }
  });

});


$('#register').on('submit', function(event) {
  event.preventDefault();
  // adding rules for inputs with class 'comment'
  $('.dynamicVal').each(function() {
    $(this).rules("add", {
      required: true
    })
  });
  // test if form is valid 
  if ($('#register').validate().form()) {
    $.ajax({
      //url:"process.php",
      url: baseUrl + "/Customer_control/register",
      type: "POST",
      dataType: "json",
      data: $('#register').serialize(),

      success: function(data) {
        alert("success");
      },
    }); // AJAX Get Jquery statment
  }
  //alert('hellow');
});
$('#register').validate({
  errorPlacement: function(error, element) {
    if (element.is("select")) {
      error.insertAfter(element.parent());
    } else {
      error.insertAfter(element);
    }

  }
});
<div id="clicktoadd"><a href="javascript:void(0);" class="btn btn-bg">Add More</a></div>
<form action="#" method="post" id="register" name="register">
  <div class="row">
    <div class="medication_info">
    </div>
  </div>

  <input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>

接下来我可以尝试什么?

idv4meu8

idv4meu81#

您可以在HTML表单中为多个名称使用数组,然后使用PHP中的Foreach循环(CodeIgniter)获取值。
下面是你应该如何修改你的代码:更改此行:

$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')

收件人:

$(".medication_info").append('<select name="pp_fileStatus[]" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')

注意:我只是将**select字段名改为“pp_fileStatus[]"**并删除了numberIncr变量
现在你可以在你的控制器中访问这个字段名的值了。

$pp_fileStatus = $this->input->post('pp_fileStatus');

这里$pp_fileStatus是一个数组,包含pp_fileStatus的所有值。

您也可以对其他表单字段执行相同操作

所以你可以通过给变量加1来避免给字段命名。
希望这能解决你的问题。
你可以像这样更新你的register函数:

public function register(){

    $insert_array = [];

    $pp_fileStatus = $this->input->post('pp_fileStatus');
    $reasonDate    = $this->input->post('reasonDate');
    $reasonAmt    = $this->input->post('reasonAmt');
    $remark    = $this->input->post('remark');

    foreach ($pp_fileStatus as $key => $value) {

        $insert_array[] = array(
                                   'pp_fileStatus' => $value,
                                   'reasonDate' => $reasonDate[$key],
                                   'reasonAmt' => $reasonAmt[$key],
                                   'remark' => $remark[$key]
                                 );

    }

    $this->db->insert_batch('tbl_register',$insert_array);
}

根据您的需要更新此功能

yhxst69z

yhxst69z2#

你需要为你的提交动作创建一个函数,你在文档加载时调用(make available),在附加了DOM之后,也可以用你的change事件调用。
简化示例:

$(document).ready(function() {
  my_submit(); // enables your submit calls
  $(document).on('change', '.pp_fileStatus', function(event) {
    // your append code
    my_submit(); // again, enables your submit calls
  })
}
function my_submit(){
  $('#register').on('submit', function(event) {
    // your code
  })
  $('#register').validate({
    // your code
  })
}

相关问题