我正在尝试在tabout上验证我的DropDownlist。下拉列表如图所示
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Select a Provider Type:</label>
<div class="col-sm-10" id="ProviderType">
<select class="form-control">
<option>Select a Provider Type</option>
<option>Doctor</option>
<option>Facility</option>
</select>
</div>
</div>
我已经编写了以下代码来获取标签上的提醒
$("#ProviderType").on("blur", function () {
if ($("this")[0].selectedindex <= 0)
alert("Please choose a Provider");
});
以上代码无效,
所以我尝试了这个无效的代码
$("#ProviderType option:selected").on("blur", function () {
if ($("this").text() == "Select a Provider Type")
alert("Please choose a Provider");
});
任何帮助都会受到赞赏。谢谢。
正如所建议的那样,我使用.bind()方法进行了一些事件处理。
$("#Certification").bind("blur",function () {
alert("Event binding is working fine.")
});
我在下拉列表中看到一个警告。我仍然没有看到错误。请指导我。
答案 0 :(得分:1)
解决方案1 - 将空值设置为第一个选项
解决方案可以是将空值设置为第一个选项,然后检查所选值
$("#Certification").bind("blur",function () {
var selected_value = $(this).val();
if(selected_value==null || selected_value=='') {
alert("Please choose a Provider");
}
});
这可用于在元素失去焦点后立即检查值。然而,该解决方案可能对用户来说很烦人,因为他们可能想要回来并做出新的选择。因此,您可以评估第二种解决方案。
解决方案2 - 隐藏第一个选项
另一个解决方案可能是隐藏列表中的第一个选项,以便用户无法选择它,然后检查所选值,即在表单提交时。
$("#myform").submit(function() {
var selected_value = $("#Certification").val();
if(selected_value==null || selected_value=='') {
alert("Please choose a Provider");
return false;
}
return false; // remove this line in real form submission
});
<强> Fiddle 强>