0

I am using jQuery validation plugin, it works fine for all fields but, when I use it for select it doesn't work

HTML

<form>
    <select id="name" name="name">
        <option>Select</option>
        <option value='select'>Select</option>
        <option value='abc'>ABC</option>
        <option value='xyz'>XYZ</option>    
    </select>
    <input type='submit' value='Submit' />
</form>

SCRIPT

var f=$("form").validate({
    rules: {
        name:{
            required:
                 function(element) {
                     st=($(element).val() == '') || ($(element).val() == 'select');
                     return st;
                }
        }
    },
    messages: {
        name: {required: "Please select name"}
});

Also, I want to stop submition after validation, no matter whether the form is valid or not.

Note I don't want to use $.validator.addMethod.

I've already searched

  1. jQuery select box validation
  2. jQuery validate select box
  3. http://www.coldfusionjedi.com/demos/jqueryvalidation/test4.html
2
  • @Zenith <option>Select</option> is default empty, isn't it? Commented May 17, 2013 at 7:39
  • You're right :) Can you not just use return false to stop submission? Commented May 17, 2013 at 7:41

2 Answers 2

1
if($("#name :selected").val() == '') 
    return false;
Sign up to request clarification or add additional context in comments.

Comments

0

I'm going to say it's a plugin that's slightly overcomplicating an simple error check! Then again, I found the same thing you're attempting to do on the Developer's Github Demo page.

Fiddle: http://jsfiddle.net/hAWR3/14/

<script>
    $("#formsubmission").submit(function(event){ 

        /** Cache Result **/
        var tmp = $('#selectname').val();
        console.log( "Selected Name: " + tmp );

        if ( tmp == 'select' || tmp == 'Select' ) {

            /** Prevent the submission **/
            event.preventDefault();
            console.log( 'Unvalidated!' ); 

        } else {

            /** Submit as normal!! **/
            console.log( 'Validated!' );   
        }

    });
</script>

<form method="post" id="formsubmission">
    <select id="selectname" name="name">
        <option>Select</option>
        <option value='select'>Select</option>
        <option value='abc'>ABC</option>
        <option value='xyz'>XYZ</option>    
    </select>
    <input type='submit' value='Submit' />
</form>

Note: if there's no value within the like in your html example, it take the encased value inside the <option></option>'s!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.