[英]I want to disabled remaining select options from my dropdown of select2() library
I want to disable remaining select options from my dropdown of select2()
library but I can't. 我想从
select2()
库的下拉列表中禁用剩余的选择选项,但我不能。 I am generating a dynamic list of some brands in which I have some values like "All brands", "Honda", "Accord" etc., I want to disable all the select options if a user checks "all brands". 我正在生成一些动态列表中的一些品牌,其中我有一些价值,如“所有品牌”,“本田”,“雅阁”等,如果用户检查“所有品牌”,我想禁用所有选择选项。
How can I do this? 我怎样才能做到这一点?
Here's my jQuery code: 这是我的jQuery代码:
$("select.select2").change(function () {
var selectedCountry = $(this).val();
if (selectedCountry == 'all_brands') {
$("dynamicList").prop("disabled", true)
}
});
And this is my HTML & PHP code: 这是我的HTML和PHP代码:
<label class="text-danger">Select Brands</label>
<select class="form-control select2" id="brandAll" multiple="multiple" name="brand_id" data-placeholder="Select Brand to Deal" style="width: 100%;">
<option value="all_brands" id="checking123">All Brands</option>
<?php
foreach ($brand_list as $brand) {
echo "<option value='$brand->id' class='dynamicList'>$brand->name</option>";
}
?>
</select>
In order to disable element using class selector try this: 要使用类选择器禁用元素,请尝试以下操作:
$(".dynamicList").attr('disabled','disabled');
Note: this will disable all options, probably you would need to exclude the option with `"All Brands"`` 注意:这将禁用所有选项,可能需要用“所有品牌”``排除选项
$(".dynamicList").attr('disabled','disabled');
$("#checking123").removeAttr('disabled');
Bug #1 you are using multiple="multiple"
then $(this).val()
returns an array, not a single value. Bug#1你使用
multiple="multiple"
然后$(this).val()
返回一个数组,而不是一个值。
Bug #2 you need to fix class selector: dynamicList
-> .dynamicList
Bug#2你需要修复类选择器:
dynamicList
- > .dynamicList
Here is the full code: 这是完整的代码:
$("select.select2").change(function (){
var selectedCountry = $(this).val();
if (selectedCountry.length > 0 && selectedCountry[0] == 'all_brands') {
$(".dynamicList").attr('disabled','disabled');
}
});
Edit: 编辑:
I would recommend to fix also html style, use double quotes for attributes: 我建议修复html样式,使用双引号作为属性:
echo '<option value="' . $brand->id . '" class="dynamicList">' . $brand->name . '</option>';
or even like this: 或者甚至喜欢这样:
<label class="text-danger">Select Brands</label>
<select class="form-control select2" id="brandAll" multiple="multiple" name="brand_id" data-placeholder="Select Brand to Deal" style="width: 100%;">
<option value="all_brands" id="checking123">All Brands</option>
<?php foreach ($brand_list as $brand) { ?>
<option value="<?php echo $brand->id ?>" class="dynamicList"><?php echo $brand->name ?></option>
<?php } ?>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.