Javascript 通过jQuery自定义函数验证选择选项列表
我试图在使用自定义验证函数,但它不起作用。以下是我的代码:Javascript 通过jQuery自定义函数验证选择选项列表,javascript,jquery,Javascript,Jquery,我试图在使用自定义验证函数,但它不起作用。以下是我的代码: $(function () { function selectInput(elem) { inputData = $.trim(elem.val()); if (inputData == "na") { $('error').html('Please Select From The List'); } else { ret
$(function () {
function selectInput(elem) {
inputData = $.trim(elem.val());
if (inputData == "na") {
$('error').html('Please Select From The List');
} else {
return inputData;
}
}
$("#pro").on("click", function (e) {
if (selectInput($('#uselect'))) {
alert('Correct Selection');
}
else{console.log("There is an Error! But Where?!")}
e.preventDefault();
});
});
HTML是
<form>
<select id="#uselect">
<option value="na">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="Submit" id="pro" />
</form>
<div id="error"></div>
如何修复它?查看您的ID以选择
<select id="#uselect">
<select id="uselect">
它里面有一个 松开锁紧螺母
<select id="#uselect">
使用
清除select标记中的:
到
首先,您的id中有,所以请管理它 然后,您将得到1或2作为值,而不是
value="1"
value="2"
如果未选择任何内容,则您将获得na我通过从DOM就绪事件中删除函数实现来停止它,如下所示
//DOM-Ready Event Listner
$(function () {
$("#pro").on("click", function (e) {
if (selectInput($('#uselect'))) {
alert('Correct Selection');
} else {
console.log("There is an Error! But Where?! Bahh"); //<--Added a ';'
}
e.preventDefault();
});
});
//Separated Implementation
function selectInput(elem) {
inputData = $.trim(elem.val());
if (inputData == "na") {
$('error').html('Please Select From The List');
} else {
return inputData;
}
}
您缺少一个字符:添加一个:
$('error').html();
像这样:
$('#error').html();
并移入:
<select id="#uselect">
像这样:
$('error').html();
$('#error').html();
<select id="#uselect">
<select id="uselect">