Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

html - JQuery Validate Dropdown list

I'm using the validation plugin from here. I'm trying force the user to select an option in the drop down list so here's my html for the list:

Select the best option<br/>
<select name="dd1" id="dd1">
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> <br/><br/>?

And here's the the jquery validation stuff:

$("#everything").validate({
    onsubmit: true,
    rules: {
     dd1: {
      required: {
        depends: function(element) {
            return $("#dd1").val() == "none";
        }
      }
    },
    messages: {
     dd1: {
      required: "Please select an option from the list, if none are appropriate please select 'Other'",
     },
    }
});

I don't see any problems but even when the i select none from the drop down list and click submit, it won't validate it and so doesn't show any messages. Can anyone tell me what i'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...