javascript - 使用 jQuery 获取 2 个下拉菜单项的选定值

标签 javascript php jquery

我正在使用 sql 来检索下拉列表的值。我只能获得第一个下拉框项目。我如何获得第二个下拉值。我正在从sql中获取数据。

<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
    <?php while($row = mysql_fetch_array($query_parent)): ?>
    <option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
    <?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
    <?php while($row = mysql_fetch_array($query_parent1)): ?>
    <option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
    <?php endwhile; ?>
</select>
<br/><br/>

我的 jquery 如下所示

$(document).ready(function(){
$("#parent_cat").change(function(){
    var selectedCountry = $("option:selected").val(); 
      alert("You have selected the Country - " + selectedCountry);

});
});

我能够获取第一个下拉值,我怎样才能获取第二个下拉值

$(document).ready(function(){
$("#city").change(function(){
    var selectedCountry1 = $("option:selected").val(); 
      alert("You have selected the city- " + selectedCountry1);

});
});

我能知道我哪里错了

最佳答案

看起来您正在尝试在更改事件处理程序中获取所选城市的值。

在事件处理程序中this引用已更改的元素,因此您只需读取其值

$(document).ready(function () {
    $("#city").change(function () {
        var selectedCountry1 = this.value; //or $(this).val()
        //if you want to get the text of the selected option
        var text = $(this).find('option:selected').text(); //find the selected option inside the current select
        alert("You have selected the city- " + selectedCountry1);

    });
});

$(document).ready(function () {
    $("#parent_cat").change(function () {
        var selectedCountry = this.value; //or $(this).val()
        alert("You have selected the Country - " + selectedCountry);

    });
});
<小时/>

您的代码的问题是 $("option:selected") 返回所有选定的 option 元素,但是当您使用 getter . val() 它将仅返回第一个选定的 option 元素的值,因此您将在任何地方获得相同的值。

关于javascript - 使用 jQuery 获取 2 个下拉菜单项的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092402/

相关文章:

javascript - jquery css stylesswitcher 将 cookie 设置为 css

javascript - JavaScript 中的 while(i) 循环

javascript - 空数组为假,但在 IF 语句中它返回真

javascript - 如何制作一个显示英国时间但整个应用程序以印度时间运行的时钟

jquery - 我缺少什么? Django - Ajax

javascript - 使用具有固定位置元素的 JQuery Effect() 防止队列

javascript - API 请求返回两个对象 : How Do I Separate State in Redux with One Reducer?

javascript - 浏览器图像渲染

PHP - Windows 中的命令行参数未被传递

php - Wordpress 中的变音符号有效但未显示特定字体