我正在使用 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/