简体   繁体   中英

JQuery form validation question

I have a search form where it has about ten fields. Couple of them are input elements of type "text" and couple of them are select boxes. User should select at least one criteria to search. I can write something like "if input1!=null && input2!= null..." for all 10 fields to check whether user selected at least one criteria.

But I feel like this is lot of code. Is there any I can just write one line of code to meet this requirement (that is user should select at lease one search criteria) using jquery?

$('input[value!=""]').length

This shows the number of input fields that have text in them (different from ""). Try it here

You should try JQuery validate plugin. It's very easy to use.

$('input, select').each(function(){
 var current = $(this);
 if( current.val() == //yourcriteria// ) {
   //do stuff!
 }
});

Something like

var somethingSelectedInEach = true;

$("select").each(function(i, el){
    if($(this).val() == null){
        somethingSelectedInEach = false;
        return false;
    }
});

if(somethingSelectedInEach){
    alert("Yaay! You selected something in each select!");
} else {
    alert("Booo. You forgot to select something in each select!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM