【问题标题】:Update selectbox options and save to database更新选择框选项并保存到数据库
【发布时间】:2017-03-30 15:40:48
【问题描述】:

我必须选择框:

<select name="select1" id="select1" multiple="multiple">
<option value="8">Civics</option>
<option value="9">English</option>
<option value="10">Economics</option>
</select>

<select id="select2" size="4" multiple="multiple" name="select2[]">
<option value="1">Maths</option>
<option value="2">Physics</option>
<option value="3">Chemistry</option>
<option value="4">Biology</option>
<option value="5">History</option>
<option value="7">Social Studies</option>
<option value="11">Geography</option>
</select>

两个框的数据都是在页面加载时从数据库中获取的。 这个想法是从 select2 添加/删除选项并将其保存到数据库中的表中。我在更新表之前删除了表中的现有数据。

我面临的问题是在保存数据时,只有添加到 select2 的新选项才会被保存,如果我删除任何选项,我会收到索引越界错误。如何确保读取页面加载时 select2 中已经存在的值?

php代码如下:

<?php
if(isset($_POST['save']))
{
    $qry = 'delete * from table_sel2';
    $exec = mysqli_query($conn,$qry);


    foreach ($_POST['select2'] as $sel_val) 
    {       
        echo $sel_val;
        $sql = "insert into table_sel2 (select2,status_id) values (".$sel_val.",1)";
        $result = mysqli_query($conn,$sql);
    }
    $message = "Done!";     
}
?>

在选择框之间移动数据的jQuery代码:

$('#add').click(  
            function(e) 
            {  
                $('#select1 > option:selected').appendTo('#select2');  

            });                  

            $('#remove').click(                  
            function(e) 
            {  
                $('#select2 > option:selected').appendTo('#select1');  

            }); 

【问题讨论】:

  • 您的 HTML 中没有名称为 select2[] 的输入
  • 你的描述不清楚
  • @lazy_coder:更改了描述。
  • @AlexMohr 是一个错字。现在编辑代码。

标签: php jquery


【解决方案1】:

像这样提交表单时从 select2 中选择所有选项 -

    submit_bttn.click(function () {
      $('#select2 option').each(function () {
          $(this).attr('selected', true);
      });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多