Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A jQuery 'if' condition to check multiple values

In the code below, is there a better way to check the condition using jQuery?

if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
like image 290
user1060990 Avatar asked May 15 '12 08:05

user1060990


2 Answers

Unless there are other concerns, like if you will reuse the #test1, ... fields for more processing, yours should be good.

If you will fetch any of the values again to do something I would recommend storing the $('#test1') result in a variable so that you do not need to requery the dom.

Ex:

var t1 = $('#test1');
if((t1.val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) {
    t1.val('Set new value');
}

This also improves readability of the row ;)

like image 195
David Mårtensson Avatar answered Oct 03 '22 00:10

David Mårtensson


var values = ['first_value', 'second_value', 'third_value', 'fourth_value'];
$('#test1, #test2, #test3, #test4').each(function(index, el) {
   if($.inArray(this.value, values)) {
     // do some job;
     return false; // or break;
   }
});
like image 31
The System Restart Avatar answered Oct 03 '22 00:10

The System Restart