jQuery从选择框中获取选定值不起作用

时间:2014-01-18 20:37:53

标签: 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_bedroom">Bedroom</option>
    <option value="pa_bathroom">Bathroom</option>
</select>

<button type="button" class="button button-primary add_attribute">Add</button>

和jQuery代码是:

$('.add_attribute').on('click', function () {
    var selected = $('#attribute_taxonomy option:selected');
    alert(selected.val());
});

不幸的是我得到了空白警报框,没有得到任何东西。但奇怪的是,当我使用相同的HTML&amp;创建jsFiddle时jQuery代码我得到了正确的输出。

为什么我什么都没得到。有替代解决方案吗?我对jQuery并不擅长,所以如果有人指导我解决这个问题,我会感激不尽。

我的样本&gt; JSFIDDLE

感谢。

3 个答案:

答案 0 :(得分:1)

只需使用:

var selected = $('#attribute_taxonomy');
alert( selected.val() );

答案 1 :(得分:1)

您需要获取select元素的值,而不是其选定的option

$('.add_attribute').on('click', function () {
    var selected = $('#attribute_taxonomy');
    alert(selected.val());
});

JS Fiddle demo

我还倾向于阻止用户与button进行交互,直到在select元素中进行选择(使用disabled(布尔)属性)和然后,一旦做出选择,阻止用户重新选择看起来像option标签的东西(注意这比它需要的更复杂,可能会采用一种可能改进的方法)。首先,HTML:

<!-- select element unchanged -->

<button type="button" class="button button-primary add_attribute" disabled>Add</button>

jQuery的:

$('#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());
});

JS Fiddle demo

一种稍微好一点的方法(在我看来)是正确使用HTML及其元素;使用optgroup关联相关的option元素,并设置label属性来解释该组的内容:

<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>

JS Fiddle demo

这种方法意味着总是设置一个带有值的选项(尽管最初是默认值,除非其中一个option被赋予selected属性),这意味着{{1不需要设置button属性设置/取消设置,以防止在没有值的情况下意外选择disabled

参考文献:

答案 2 :(得分:0)

相关问题