[英]Apply custom validation in select2
I am using select2 which is working fine now. 我正在使用现在工作正常的select2。 I want to validate it that its value can not be blank.
我想验证它的值不能为空。 I don't want to use jQuery validator plugin because there is other fields on form as well code for validation for form's other field is pre-written i am just applying select2 to every drop down.
我不想使用jQuery验证器插件,因为表单上还有其他字段以及用于验证表单的其他字段的代码是预先编写的,我只是将select2应用于每个下拉列表。 I have tried for solution on net but every answer is using jquery validator plugin.
我试过在网上解决方案,但每个答案都使用jquery验证器插件。
My code is 我的代码是
$('.select2-use').select2({
placeholder: "Select",
allowClear: true
});
<select id="type" name="type" class="form-control select2-use">
<option value="">select type</option>
<option value="U">User</option>
<option value="A">Admin</option>
</select>
My current validation is 我目前的验证是
if (type == '') {
$("#type").closest("span[class='select2-selection--single']").css('border-color','#a94442'); //which is not working
console.log($("#type").find('span.select2-selection--single'));
flag++;
} else {
$('.select2-selection--single').css('border-color','');
}
How can i change the border color of select2 span in red as error. 如何将select2 span的边框颜色更改为红色作为错误。
Try with below code: 试试以下代码:
if (type == '') {
$("#type").next("span.select2-container").find("span[class='select2-selection--single']").css('border-color','#a94442');
console.log("match found");
flag++;
} else {
$("#type").next("span.select2-container").find("span[class='select2-selection--single']").css('border-color','');
}
Whenever we convert normal dropdown
to select2
dropdown; 每当我们将正常
dropdown
转换为select2
下拉列表时; then this plugin creates its own DOM structure and hides the original dropdown
. 然后这个插件创建自己的DOM结构并隐藏原始
dropdown
。 So the generated DOM gets placed just next to the original dropdown
. 因此生成的DOM就位于原始
dropdown
旁边。 To deal with its DOM; 处理其DOM; we need to use
$.next()
to traverse next in DOM and then we can grab any of its child element by $.find()
. 我们需要使用
$.next()
遍历DOM中的next,然后我们可以通过$.find()
获取它的任何子元素。 Hope it will help you. 希望它会对你有所帮助。
apply style on .select2-choice
. 在
.select2-choice
上应用样式。
Following is the best way to do it. 以下是最好的方法。
Add the following css class: 添加以下css类:
.select2-container .select2-choice {
border: 1px solid transparent !important;
box-shadow: none;
border-radius: 0;
}
.select2-container .select2-choice.show-error {
border: 1px solid #EC644B !important;
}
On error condition do this. 出错时请执行此操作。
jQuery("#yourtargetselect2 .select2-choice").addClass("show-error");
With your code it would be 用你的代码就可以了
if (type == '') {
$("#type").closest(".select2-choice").css('border-color','#a94442'); //which is not working
flag++;
} else {
$('.select2-choice').css('border-color','');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.