[英]How to change a border color of html select tag if value is empty or 0
我有分配给它的类名select2
4个select
标签。 如果没有选择的选项或值为空或0的值,我想使边框变为红色。我试图使用jquery添加类,但它会使所有select.select2
边框变为红色。
<style>
.errorType {
border-color: #F00 !important;
}
</style>
<select name="category" class="form-control select2" id="category" onChange="search_Operator(this.value)">
<option value="0"> Select Operator Category</option>
<option value="1">one</option> <option value="2"> two</option>
</select>
<select name="operatorName" class="form-control select2" id="operatorName" onChange="">
<option value="0"> Select operator Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="regionName" class="form-control select2" id="regionName">
<option value="0"> Select region Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="type" class="form-control select2" id="type">
<option value="0"> Select type </option>
</select>
$(function () {
$(".select2").select2();
});
$(".select2-selection").addClass('errorType');
任何想法?
提前致谢。
为了检查页面上每个select元素的值,我向Submit按钮的click事件附加了一个函数:
$(function () {
$('.form-control-select2').select2();
$('#submit_btn').on('click', function(){
var submit_form = true;
$(".form-control-select2").each(function(){
var selected_value = $(this).val();
if (selected_value==0 || selected_value=='') {
$(this).next().find('.select2-selection').addClass('errorType');
submit_form = false;
} else {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
return submit_form;
});
});
在这里提琴: https : //jsfiddle.net/64a41thz/21/ 。
另外,如果要在进行有效选择时删除红色边框,请添加以下代码:
$('.form-control-select2').on('change', function(){
if ($(this).val()!=0 && $(this).val()!='') {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
在这里提琴: https : //jsfiddle.net/64a41thz/24/ 。
如图所示,将您的选择标签放入id="submit"
的表单中
<form class="" action="" method="post" id="submit">
并在具有此属性的4个选择标签下方添加一个按钮
onclick="return submit_form('form#submit')"
该按钮应该是这样的,
<button type="button" class="btn btn-default" onclick="return submit_form('form#submit')">Submit</button>
在你的jQuery中
function submit_form (form_id) {
$(form_id).find('select[name]').each(function (index, node) {
if (node.value == 0) {
var id = "select#" + node.id;
$(id).addClass('errorType');
}
});
}
这将搜索具有名称作为属性的选择标记,如果找到,它将获取名称的值并检查其是否为空。 如果发现为空,它将添加新类,将选择标记变成红色边框。
希望这会有所帮助
这可以解决问题。 您只需要将#yourButton替换为您使用的实际ID即可。
$(document).on("click", "#yourButton", function() {
$(".select2").each(function(index, element) {
$(element).removeClass("errorType");
if ($(element).val() === "0") {
$(element).addClass("errorType");
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.