Javascript jQuery从selectbox获取选定值不工作
我正在从事Woocommerce(WordPress)项目,我的任务是在用户单击按钮时从下拉列表中获取所选值 我的HTML是:Javascript jQuery从selectbox获取选定值不工作,javascript,jquery,html,wordpress,Javascript,Jquery,Html,Wordpress,我正在从事Woocommerce(WordPress)项目,我的任务是在用户单击按钮时从下拉列表中获取所选值 我的HTML是: <select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy"> <option value="">Custom product attribute</option> <option value="pa_be
<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy">
<option value="">Custom product attribute</option>
<option value="pa_bedroom">Bedroom</option>
<option value="pa_bathroom">Bathroom</option>
</select>
<button type="button" class="button button-primary add_attribute">Add</button>
不幸的是,我得到了一个空白的警报框,没有得到任何东西。但奇怪的是,当我使用相同的HTML和jQuery代码创建JSFIDLE时,我得到了正确的输出
为什么我什么也得不到。有其他的解决办法吗?我不擅长jQuery,所以如果有人指导我解决这个问题,我会非常感谢
我的样本>
谢谢。只需使用:
var selected = $('#attribute_taxonomy');
alert( selected.val() );
您需要获取
select
元素的值,而不是其selected选项的值
:
$('.add_attribute').on('click', function () {
var selected = $('#attribute_taxonomy');
alert(selected.val());
});
我还倾向于阻止用户与按钮进行交互,直到在select
元素中做出选择(使用disabled
(布尔)属性),然后,一旦做出选择,就阻止用户重新选择看起来是选项的标签(请注意,这比需要的更复杂,下面可能会有一种改进的方法)。首先,HTML:
<!-- select element unchanged -->
<button type="button" class="button button-primary add_attribute" disabled>Add</button>
(在我看来)更好的方法是正确地使用HTML及其元素;使用optgroup
将相关的选项
元素与标签
属性集相关联,以解释该组的内容:
<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy">
<optgroup label="Custom product attribute">
<option value="pa_bedroom">Bedroom</option>
<option value="pa_bathroom">Bathroom</option>
</optgroup>
</select>
卧室
浴室
这种方法意味着始终设置带有值的选项(尽管最初设置为默认值,除非其中一个选项
s被赋予了所选
属性),这意味着按钮
不需要设置/取消设置其属性,以防止意外选择没有值的选项
参考资料:
- HTML:
- jQuery:
发生了什么?您是否至少收到了警报?您是否动态加载页面(通过ajax)?检查开发人员控制台(或firebug控制台)对于任何错误!@Krishna是的,我得到警报框,但没有得到值。只是空的弹出窗口。不,我没有使用ajax。@Saurabh Hi,我从控制台检查,我得到了这个错误:Uncaught TypeError:object不是我代码中的函数。@lumos你应该首先修复它(检查文件/行号)。某个位置的错误可能会导致其他位置的代码不起作用。
$('#attribute_taxonomy').on('change', function(){
// cache the $(this) jQuery object since we're potentially using it twice:
var $this = $(this);
// if there are no disabled options we run the following jQuery:
if (!$this.find('option:disabled').length) {
$this
// find the option that has no value set:
.find('option[value=""]')
// set its 'disabled' property to true (to disable it)
.prop('disabled', true)
// go back to the original selector ($(this))
.end()
// move to the next element (if it's a button element):
.next()
// unset its 'disabled' property (to enable it):
.prop('disabled',false);
}
});
$('.add_attribute').on('click', function () {
var selected = $('#attribute_taxonomy');
alert(selected.val());
});
<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy">
<optgroup label="Custom product attribute">
<option value="pa_bedroom">Bedroom</option>
<option value="pa_bathroom">Bathroom</option>
</optgroup>
</select>