如何从<select>和所选</select>中的每个更改中选择当前

时间:2014-09-28 08:14:15

标签: javascript php jquery html5 mysqli

我试图创建一个动态,其中所选的选项应该被捕获在php的变量中,因为我将其用作放入mysql的where子句中的条件。当用户选择另一个选项时,另一个标签会改变

<form method="GET" action="">
    <select name="docSpec" id="docSpec">

<?php   
    $docSpecQuery = "select DISTINCT specialty from doctors"; // i was going to put a where condition here so i could only project names of the doctor with the selected specialty.
    $docquery = "select doctorName from doctors";
    $docSpec = mysqli_query($conn,$docSpecQuery);
    $docresult = mysqli_query($conn,$docquery); 

    //this php block is for my options, i used a loop                                   
    while ($row = mysqli_fetch_row($docSpec))
    {
        echo "<option value='$row[0]'>$row[0]</option>";
    }
    unset($row);
?>
    </select>                                   
    <script type="text/javascript">     
        $('#docSpec').on("change",function(){
            var option = $("option:selected",this).val();
            alert(option);
        }); 
    </script>
</form>

我希望我很清楚,如果你想在我的代码中澄清一些内容,我会等待。 告诉我你是否需要我的代码的其他部分。我需要帮助

1 个答案:

答案 0 :(得分:0)

PHP在服务器上执行,这意味着当您打印<select>运行jQuery代码时,您无法直接影响mysql查询。但是,您可以将查询移动到另一个脚本,并使用ajax调用来定位它,该调用返回select和options,或者理想情况下,返回数据集,以便您可以通过编程方式创建它。

您的php脚本将执行与现在相同的操作,但是从条件查询的url中获取值。例如,你可以在mysite.com/select.php使用这个php,并像gynecologist一样传递变量mysite.com/select.php?spec=gynecologist,然后用$_GET['spec']读取它并在查询中使用它。

在您的javascript中,您可以通过调用以下内容来获取该HTML:

$('#docSpec').on("change",function(){
    $.get( "mysite.com/select.php?spec="+$(this).find("option:selected"), 
    function( data ) {
        //data contains the output for the php file, update the dom 
        //with it or whatever
    });
});