使用jQuery将选择选项从数据库填充到动态选择选项

时间:2017-11-14 12:37:25

标签: javascript php jquery

我从数据库中选择members的名称作为select选项。使用jQuery,我有一个动态添加按钮,可以使用append功能添加新的选择字段。但是,在附加中传递由php生成的选择选项的标准方法是什么?

我已经研究了一段时间,但无法让它发挥作用。所以任何建议都会非常有用。

这是页面结构。它看起来很乱,但请看看它。我已经将$members作为<?php echo $members; ?>传递给一个从一开始就存在的静态选择,但对于动态选择,我创建了一个变量var members并试图将其传递给append但它无效。

<?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>
<script> 
   var members = "<?php echo $members; ?>";

   $(document).ready(function() {
          var fixHelperModified = function(e, div) {
                var $originals = div.children();
                var $helper = div.clone();
                $helper.children().each(function(index) {
                   $(this).width($originals.eq(index).width())
                });
                return $helper;
             },
             updateIndex = function() {
                $('div.index').each(function(i) {
                   $(this).html(i + 1);
                });
             };
          $("#add").sortable({
             helper: fixHelperModified,
             stop: updateIndex
          }).disableSelection();
          $("#addNew").click(function() {
             $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option>"+members+"</select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
             updateIndex();
          });
          $("body").on('click', '#add .delete', function() {
             $(this).closest(".rem").remove();
             updateIndex();
          });
       });
</script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit"> 
</form>

如果您需要查看php的操作,则以下是没有jQuery的表单的摘要。

&#13;
&#13;
    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option></select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit"> 
</form>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

每个选项都有双引号,你把字符串放在相同的标记内,如果我理解它会破坏你的代码,尝试在单引号中包装或使用var myvar = <?php echo json_encode($myVarValue); ?>;

答案 1 :(得分:0)

每次用户点击添加按钮时,我不想让你使用jquery从已经生成的选项列表中添加一个select选项(用php生成)?

答案 2 :(得分:0)

如果那就是你想要的?你可以将php回显成一个javascript数组

<script>
var members = []; // this is the javascript array been initialized
<?php
require_once 'db_connect.php';

$members = '';
$query = "SELECT memberID, memberName FROM members";
$result = mysqli_query($connect, $query);

$i=0 // index for the array
while($row = mysqli_fetch_array($result))
{
$raw_option = '<option   value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
$option = htmlentities($raw_options); // there might be quotation that could break your javascript 
echo "members[{$i}] = '{$option}';"; // echoing the javascript first semi column is for javascript and second for php


$i++; // incrementing the index for the array
}
?>
</script>

然后jquery添加按钮可以从成员数组中选择每个选项

答案 3 :(得分:0)

我不理解你的许多代码,但如果你想要做的是点击时添加一个选项,这是我认为应该工作的

<select name='members' id="members_select">
<option value=''>Select member</option>
</select>
<button id="add">Add Option</button>
<script>
var current_member = 0; // global variable that tells what part index of the members array we currently are..
add_button = document.getElementById("add");
add_button.addEventListener('click') = function(){
   // i imagine the members array above is already set
  $('#members_select').append(members[current_member]);
  current_member++;
}
</script>