我正在使用jQuery多选下拉框。由于它的默认属性,我无法使用它的name属性验证它。所以我想用id验证。我使用this作为参考。但我的想法不起作用。我不知道我的错误在哪里?
HTML
<form id="form1" method="post" action="">
<div>
<select name="offer" id="offer1">
<option value="">Select one</option>
<option value="aaaaa">aaaaaaaaaaa</option>
<option value="bbbbb">bbbbbbbbbbb</option>
<option value="cccccc">ccccccccccc</option>
</select>
</div>
</form>
<input type="submit" id="submit1" value="Save" />
JS
$(function () {
$("#submit1").click(function () {
alert("submit")
var $off = $("#offer1").attr("name");
var $params = {
debug: true,
rules: {},
messages: {}
};
$params['rules'][$off] = "off";
$params['messages'][$off] = "Select an offer";
$("#form1").validate($params);
});
});
答案 0 :(得分:2)
试试这个
HTML CODE
<form id="RNA" name="RNA">
<select size="5" name="sampleMut[]" multiple="multiple" id="sampleMut">
<option value="41" >41</option>
<option value="48" >48</option>
<option value="65" >65</option>
<option value="102" >102</option>
</select>
<input type="submit" />
</form>
JavaScript代码
$(function(){
$('form').submit(function(){
var options = $('#sampleMut > option:selected');
if(options.length == 0){
alert('no value selected');
return false;
}
});
});
您可以从此选择中选择多个值。 options.length
为您提供了多少个值。
答案 1 :(得分:0)
将<option>
代码包含在内<select>
代码
<select name="offer" id="offer1>
<option value="">Select one</option>
<option value="aaaaa">aaaaaaaaaaa</option>
<option value="bbbbb">bbbbbbbbbbb</option>
<option value="cccccc">ccccccccccc</option>
</select>
答案 2 :(得分:0)
请在添加规则和消息时删除[]
答案是:
$(function () {
$("#submit1").click(function () {
alert("submit");
var $off = $("#offer1").attr("name");
var $params = {
debug: true,
rules: {},
messages: {}
};
//// Please note here
$params.rules [$off] = "required";
$params.messages[$off] = "Select an offer";
//
$("#form1").validate($params);
});
});
答案 3 :(得分:-1)
试试这个:
$(function () {
$("#submit1").click(function(){
alert("submit");
$("#form1").validate({
rules: {
offer: "required"
},
messages: {
offer: "Select an Offer"
}
});
});
});