duanque2413 2017-03-30 05:14
浏览 44
已采纳

更新选择框选项并保存到数据库

I've to select boxes:

<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>

The data for both the boxes is fetched from the db on page load. The idea is to either add/delete options from the select2 and save it to a table in the db. I delete the existing data in the table before updating it.

The issue I'm facing is while saving the data, only the new options which are added to the select2 are getting saved and if I remove any options, I'm getting an index out of bounds error. How do I make sure that the values which are already there in the select2 on page load are read as well?

The php code is as follows:

<?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 code to move data between the selectboxes:

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

            });                  

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

            }); 
  • 写回答

1条回答 默认 最新

  • dqwh1208 2017-03-30 07:40
    关注

    Select all options from select2 upon form submission like this -

        submit_bttn.click(function () {
          $('#select2 option').each(function () {
              $(this).attr('selected', true);
          });
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?