我有一个与 Select2 一起使用的字段,名为 location
,用户可以在其中输入一个或多个位置。然后我有一个复选框 noCity
如果没有location
,用户可以检查一下。
我尝试归档的内容:何时 noCity
已选中,location
被禁用,占位符被删除,并且所有值被清除。
我已归档:当 noCity
已选中,location
被禁用、未选中时、启用以及加载表单时和 noCity
已检查,禁用也正确完成。
我的问题:我似乎无法删除字段 location
的值,也不是占位符。 .attr("placeholder", '', this)
和.val('', this)
似乎不起作用,其他尝试也失败了。
到目前为止我的代码:
$('#location').select2({
placeholder: 'Enter a city'
});
$("#noCity").click(function () {
if (jQuery(this).prop("checked")) {
jQuery("#location")
.prop("disabled", this)
.attr("placeholder", '', this)
.val('', this)
;
} else {
jQuery("#location")
.prop("disabled", false)
.attr("placeholder", 'Enter the name of the city')
.val('')
;
}
});
if ($('#noCity').is(':checked')) {
jQuery('#location')
.prop('disabled', this)
.attr('placeholder', '')
.val('');
}
和 html:
Location: <select id="location" multiple="multiple" style="width: 300px">
<option>New York</option>
<option>Hong Kong</option>
<option>Amsterdam</option>
</select>
<br>
<label>No city:<input id="noCity" type="checkbox"></label>
这是一个JSFiddle
我的问题:我怎样才能确保 noCity
时已选中,location
被禁用,占位符被删除,所有值被清除(同时当 noCity
被取消选中时,字段 location
被再次启用并且占位符返回)?
编辑:我的问题类似于 this one ,但是我尝试在未选中复选框(仍然不起作用)时实现此操作,并且我使用 Select2 版本 4,其工作方式不同。
最佳答案
您只需将以下代码添加到 noCity is selected 事件中即可。我运行测试,没问题:))
$("#location").select2().val("0").trigger("change");
关于javascript - jQuery 禁用并清除 (Select2) 字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521901/