如何使用jQuery重置jquery选择的选项? [英] How do I reset a jquery-chosen select option with jQuery?

查看:69
本文介绍了如何使用jQuery重置jquery选择的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多事情,但似乎没有任何效果.

I have tried numerous things and nothing seems to be working.

我正在使用jQuery和选择插件.

I am using jQuery and Chosen plugin.

我尝试过的方法:

var select = jQuery('#autoship_option');

select.val(jQuery('options:first', select).val());

jQuery('#autoship_option').val('');

jQuery('#autoship_option').text('');

jQuery('#autoship_option').empty('');

jQuery("#autoship_option option[value='']").attr('selected', true);

选择后,它始终显示活动自动装载"选项.我似乎无法清除选择.

It always shows the Active Autoship option once it has been selected. I can't seem to get it to clear the selection.

以下是选择框:

<select id="autoship_option" data-placeholder="Choose Option..." 
style="width: 175px;" class="chzn-select">
    <option value=""></option>
    <option value="active">Active Autoship</option>
</select>

任何人熟悉选择"并能够清除带有一个选项的选择框? (将来它将有更多选择.

Anyone familiar with Chosen and being able to clear a select box with one option? (It will have more options in the future.

推荐答案

select元素的值设置为空字符串 是正确的方法.但是,这只会更新根select元素.自定义chosen元素不知道根select已被更新.

Setting the select element's value to an empty string is the correct way to do it. However, that only updates the root select element. The custom chosen element has no idea that the root select has been updated.

为了通知chosen已修改select,您必须触发chosen:updated:

In order to notify chosen that the select has been modified, you have to trigger chosen:updated:

$('#autoship_option').val('').trigger('chosen:updated');

或者,如果不确定第一个选项是否为空字符串,请使用以下命令:

or, if you're not sure that the first option is an empty string, use this:

$('#autoship_option')
    .find('option:first-child').prop('selected', true)
    .end().trigger('chosen:updated');

在此处阅读文档(找到标题为动态更新选择的部分).

Read the documentation here (find the section titled Updating Chosen Dynamically).

PS .选择的较早版本使用的事件稍有不同:

P.S. Older versions of Chosen use a slightly different event:

$('#autoship_option').val('').trigger('liszt:updated');

这篇关于如何使用jQuery重置jquery选择的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆