如何通过单击添加新的btn来将下拉元素添加到表单中,其中下拉选项包含数据库表中的数据

时间:2019-05-20 08:10:30

标签: jquery codeigniter

我想通过单击添加按钮()动态添加下拉菜单。下拉选项将来自我的mysql数据库。

我在jquery中尝试过以下方法,但是无法显示“ items”表中的项目记录。

<script type="text/javascript">
$(document).ready(function() {
    var x = 0;
    $('#save_btn').hide();

    $('#add_btn').click(function(e) {
    e.preventDefault();
    appendRow(); // appen dnew element to form 
    x++; // increment counter for form
    $('#save_btn').show(); // show save button for form
  });

    $('#input_wrapper').on('click', '.deleteBtn', function(e) {
    e.preventDefault();
    var id = e.currentTarget.id; // set the id based on the event 'e'
    $('div[id='+id+']').remove(); //find div based on id and remove
    x--; // decrement the counter for form.

    if (x === 0) { 
        $('#save_btn').hide(); // hides the save button if counter is equal to zero
    }
  });

  $('#save_btn').click(function(e) {
    e.preventDefault();
    var formData = $('#test_form').serializeObject(); // serialize the form
    var obj; //obj can be use to send to ajax call
    if(Array.isArray(formData.fn)) {
        for(var i = 0; i < formData.fn.length; i++) {
        obj = {};
        // set the obj for submittion
        obj.firstName = formData.fn[i];
        obj.lastName = formData.ln[i];
        // This object could be push into an array
        console.log('object from form array ', obj);
      };
    } else {
        obj = {};
      obj.firstName = formData.fn;
      obj.lastName = formData.ln;
      console.log('single obj from form ', obj);
    }
  });

  function appendRow() {
    $('#input_wrapper').append(
        '<div id="'+x+'" class="form-group" style="display:flex;">' +
          '<div>' +
            '<select name="items" class="form-control" placeholder="First 
              Name">**<option> Item one</option><option> Item 2</option>** 
             `enter code here`</select>' +
          '</div>' +
          '<div>'+
          '<input type="text" id="'+x+'" class="form-control" name="ln"                                         placeholder="Last Name"/>'+
          '</div>' +
          '<div>'+
            '<button id="'+x+'" class="btn btn-danger deleteBtn"><i class="glyphicon glyphicon-trash"></i></button>' +
          '</div>' +
        '</div>');
  }

});
</script>

我希望项目1部分包含显示项目表中记录的数据,而不是上面写的统计文本和值。

1 个答案:

答案 0 :(得分:0)

在控制器中,您需要将数据传递到视图,例如:

// $dropdown_options could be an associative array of value and label
$data['dropdown_options'] = $dropdown_options;
// Call your view with the packed data
return $this->load->view('your_form', $data);

在表单中,您需要将php数组转换为Javascript。

var dropdownOptions = <?php echo json_encode($dropdown_options) ?>;

使用Javascript数组后,就可以连接每个选项。

var optionString = "";
for (var i in dropdownOptions) {
  optionString += "<option>"+dropdownOptions[i]['label']+"</option>";
}
var selectString = "<select>"+optionString+"</select>";