如何正确获取选择框的选定索引

时间:2014-08-12 18:20:47

标签: jquery

<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function () {
var $article = null;

$('#category').change(function () {
var $categoryName = $("#category").attr('value');

 if ($article == null) {
 $article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"></select>').appendTo('.query');
 $("#business").load("php.php", {categoryName:$categoryName});
 }

 });

});
</script>

category是我的选择框中的id / class / name,每个选项都是通过php填充的,并且给出了一个值=“$ row ['colName']”,我试图将选中的值传递给php关于变化的文件。所以我可以将该值传递给下一个查询WHERE子句。

你能帮我纠正吗

  var $categoryName = $("#category").attr('value');

行获取#category的选定索引并选择w.e选项的值?

这是php.php

 <?php
    $con = mysqli_connect(,,,,);
    // Check connection
    $myVar = $_GET["categoryName"];
    if (mysqli_connect_errno())
       {
       echo "<option>Failed to connect to the Database</option>" ;
       }
     echo "<option>Select A Business To View Listing</option>";
     $result = mysqli_query($con,"SELECT BName, Category FROM Business WHERE Category=$myVar");
     while($row = mysqli_fetch_array($result)) {
      echo "<option class='".$row['BName']."'>".$row['BName']."</option>";
      }
     // Free result set
     mysqli_free_result($result);
     mysqli_close($con);
 ?>

1 个答案:

答案 0 :(得分:1)

var $categoryName = $(this).val();

这是使用jQuery获取输入元素当前值的正确方法。