Joh*_*ohn -1 jquery jquery-validate
早上好,我想知道您是否可以在这个问题上对我有所帮助:当另一个输入值满足条件时,我将根据需要对select元素应用验证。我正在使用验证jQuery插件来做到这一点。这是伪代码:(if(textbox == "valueX"){mySelectEelement is required;}表示我必须从select元素中选择一个值。)。因此出于某种原因,select元素未采用我想应用的验证。
请查看我为此目的在Plunker上创建的完整示例代码:
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script>
$( function() {
$.validator.setDefaults({
//debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
borough: {
required: false
}
}
});
$('#state').on('change', function () {
if ($(this).val().toUpperCase() == "NY" || $(this).val().toUpperCase() == "NEW YORK") {
$('#borough').rules('add', {
required: true
});
} else{
$('#borough').rules('remove');
}
});
} );
</script>
</head>
<body>
<form id="myform">
<div>
<p id="pid"></p>
<input id='text' type='text' value='other'/>
</div>
<br/>
<input type="text" id="state" name="state" />
<select name="borough" id="borough">
<option value="" select="selected"></option>
<option value="Staten Island">Staten Island</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Queens">Queens</option>
<option value="NY">NY</option>
</select>
</form></body> </html>
Run Code Online (Sandbox Code Playgroud)
无需外部处理程序和功能。你可以使用depends属性下required的内部rules对象包含您的条件逻辑...
$("#myform").validate({
rules: {
borough: {
required: {
depends: function(element) {
if ($('#state').val().toUpperCase() == "NY" || $('#state').val().toUpperCase() == "NEW YORK") {
return true;
} else {
return false;
}
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
没有depends... 也可以正常工作。
$("#myform").validate({
rules: {
borough: {
required: function(element) {
if ($('#state').val().toUpperCase() == "NY" || $('#state').val().toUpperCase() == "NEW YORK") {
return true;
} else {
return false;
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1450 次 |
| 最近记录: |