JQuery 'if' condition for checking multiple values

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

if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) 
+6
source share
4 answers

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

If you extract any of the values ​​again to do something, I would recommend storing the result of $ ('# test1') in a variable, so you do not need to query dom.

Example:

 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'); } 

It also improves the readability of the string;)

+4
source
 var c=0, b='#test', a=['first_value','second_value','third_value','fourth_value']; for(var i=0; i<4; i++) if($(b+i).val() == a[i]) c=1; if (c) //Do stuff here 

This will reduce the size of your code by 25 bytes ,-)

+1
source
 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; } }); 
+1
source

Demo Another idea: http://jsfiddle.net/h3qJB/ . Please let me know how this happens.

You can also make a chain, for example:

 $('#test1, #test2, #test3, #test4').each(function(){ //...use this.value here }); 

It is possible that the laws of De Morgan give you an idea of ​​how to make the logic a little more compact (although I'm not sure if this is a specific case or , it is as simple as comparing values).

The code

 var boolean1 = (($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value')) var boolean2 = (($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) if (boolean1 && boolean2) alert("bingo"); else alert("buzzinga"); 
+1
source

Source: https://habr.com/ru/post/915765/


All Articles