[英]jquery: val() method not working
I have a dropdown element populated through jquery ajax 我有一个通过jquery ajax填充的下拉元素
<select name="category" class="form-control"></select>
This is the jquery code for populating the dropdown 这是用于填充下拉列表的jquery代码
$.post(
"get_categories.php",
{
id: 1
}, function(data) {
$($('select[name=category]')).html(data);
}
);
To see whether the dropdown was successfully populated i use console.log 要查看是否已成功填充下拉列表,我使用console.log
}, function(data) {
$($('select[name=category]')).html(data);
console.log(data)
}
This is what i've got in the browser console window 这是我在浏览器控制台窗口中得到的
<option value='1'>Stuffed Toy</option><option value='1'>Plushie</option><option value='1'>Memorabilia</option>
The dropdown was indeed succesfully populated to test whether value will change when i select another option i included this snippet: 确实成功填充了该下拉列表,以测试当我选择包含以下代码段的另一个选项时值是否会更改:
$('select[name=category]').change(function(){
console.log($(this).val());
});
After changing options this is what ive got 更改选项后,这是我得到的
<option value='1'>Stuffed Toy</option><option value='1'>Plushie</option><option value='1'>Memorabilia</option>
1
value of dropdown wont change at all. 下拉菜单的值完全不会改变。 What i've been doing wrong?
我做错了什么?
To get the value from a dropdown you can use native javascript this.value
. 要从下拉列表中获取值,您可以使用本地javascript
this.value
。
$('select[name=category]').change(function(){
var selectedValue = this.value;
});
First try to see whether the event is getting invoked or not by putting a console.log
inside the change event. 首先尝试通过将
console.log
放在change事件中来查看事件是否被调用。
This is btw the php code 这是PHP代码
<?php
$id = $_REQUEST['id'];
include 'connect.php';
$query = "SELECT DISTINCT category FROM tbl_product";
$result = db_query($query);
$count = 1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $count;
echo "<option value='".$count."'>".$row['category']."</option>";
$count++;
}
}
?> ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.