选择框中未选中的选项不会附加到另一个选择框中

时间:2013-01-12 07:01:48

标签: php jquery html ajax mysqli

我的应用程序中有2个选择框。现在,当用户提交页面时,所有在选择框#studentadd中被选中(突出显示)的学生都会被附加到#studentselect选择框。但是,未在第一个选择框中选择的选项将不会附加到第二个选择框。

我的问题是如何在'#studentadd'选择框中添加未选中的选项以附加到'#studentselect'选择框中?

问题是我的php / ajax,因为我所做的是使用ajax导航到单独的php文件,并将#studentadd选择框中的学生插入数据库。但插入仅适用于#studentdd选择框中的学生荧光笔。它不会对那些未在`#studentadd'中选择的选项执行插入。

以下是选择框#studentadd

<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
    <option value='1'>u08743 - Joe Cann</option>
    <option value='4'>u03043 - Jill Sanderson</option>
    <option value='7'>u08343 - Craig Moon</option>
</select>

以下是学生应加入的选择框:

<select id="studentselect" name="studenttextarea"></select>

下面是jquery / ajax:

 function submitform() {    

    $.ajax({
        type: "POST",
        url: "updatestudentsession.php",
data: { 
    addtextarea:$('#studentadd').val()
        },
        dataType:'json',  //get response as json
        success: function(result){
                    if(result.errorflag){

       //do your stuff on getting error message
      var newHtml="<span style='color: red'>"+result.msg+"</span>"; 
      $("#targetdiv").html(newHtml);  //i am displaying the error msg here

      $('#targetdiv').show();

    }else{
       //you got success message

       var newHtml="<span style='color: green'>"+result.msg+"</span>"; 
            $("#targetdiv").html(newHtml);


           //append students you want to add to assessment into student exist select box 
            var selectedOption = $('select#studentadd');
            $('select#studentselect').append(selectedOption.html()); 

             //blank #studentadd select box
             $('#studentadd').empty(); 

                $('#targetdiv').show();
        }
    }
  });        
}

下面是单独的php文件updatestudentsession.php,它可以从ajax访问并将数据插入到数据库中:

$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array(); 
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : array();   

$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";

if (!$insert = $mysqli->prepare($insertsql))
{
    // Handle errors with prepare operation here
}      

$success = true;

foreach($studentid as $id)
{ 
    $insert->bind_param("ii", $sessionid, $id);

    if($insert->execute() === false)
    {
        $success = false;
    }
}

$insert->close();

if($success)
{
    echo json_encode(array('errorflag'=>false,'msg'=>"Students have been successfully added into the Assessment"));
}
else
{
    echo json_encode(array('errorflag'=>true,'msg'=>"An error has occured, Students have not been added into the Assessment"));
}

1 个答案:

答案 0 :(得分:1)

啊,你想在提交时选择所有目标选项:

function submitform() {    
  $('#studentadd option').attr('selected', 'selected');

或者你的意思是

  $('#studentselect option').attr('selected', 'selected');

...