• support@answerspoint.com

How to validate bootstrap multiselect dropdown using jquery

12132

I am trying to validate Bootstrap multiselect dropdown using the code given below, the form is getting validated but i did'nt get the proper output, the validation message is above the selectbox and the message gets multiplied when clicking on the submit button and after selecting option the message did'nt gets removed. Please help to solve my problem.

  <script type="text/javascript">
        $(document).ready(function() {
        $.validator.addMethod("needsSelection", function (value, element) {
            var count = $(element).find('option:selected').length;
            return count > 0;
          });

        $.validator.messages.needsSelection = 'Select Atleast One College'; 

          $("#User").validate({
                  rules: {    
                    'college[]': {
                    needsSelection: true
                    }
                  },
              }
          });

 $("#submit").click(function(e) {
    var isvalidate=$("#User").valid();
    if(isvalidate=="true")
    {

    }
    else
    {
        $("#User").submit();
    }
 });

});

    <form id="User" name="User" method="post" enctype="multipart/form-data" action="index">   
        <select data-placeholder="Choose College Name" name="college[]" class="chosen-select" id="college" multiple tabindex="4">
                    <option value=""></option>
                    <option value="1">abc</option>
                    <option value="2">abc1</option>
        </select>
    <a id="submit">Submit</a>
    </form>

1Answer


0

This is not a direct answer to your question, but may provide a solution to your problem.

First, change the anchor tag to a button -- because anchor tags have built-in navigation behaviour that you must counter (event.preventDefault()) and therefore add needless complexity. How about a button (input or button tags) or a div tag, or a p?)

Next, a simpler structure to evaluating your form:

jsFiddle Demo

HTML: (just changed your anchor submit button to:

<input id="dosubmit" type="submit" value="Submit" />

Note: do not use "submit" as the id for a submit button, as that is a reserved keyword

javascript/jQuery:

$('#User').submit(function(e){
    var col = $('#college').val();
    if ( col==null || col=='' || col=='Please choose one:' ){
        $('#college').css('background','yellow').focus();
        return false;
    }else{
        $('#college').css('background','transparent');
        alert('Form submitted');
        //continue to submit the form - but not now
        return false;
    }
});

Please consider this verification script for your project.

 
  • answered 8 years ago
  • Sandy Hook

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 12132 times
  • active 9 years ago

Best Rated Questions