最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - A jQuery 'if' condition to check multiple values - Stack Overflow

programmeradmin1浏览0评论

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

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'))
Share Improve this question edited Apr 17, 2013 at 3:28 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked May 15, 2012 at 8:38 user1060990user1060990 1791 gold badge2 silver badges8 bronze badges 2
  • I think your question could be posted on codereview.stackexchange.com instead of stackoverflow – pomeh Commented May 15, 2012 at 8:40
  • There's nothing built in, no. – Matt Commented May 15, 2012 at 8:41
Add a comment  | 

4 Answers 4

Reset to default 5

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

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;
   }
});
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 decrease your code size by 25 bytes;-)

Demo: just another idea is at http://jsfiddle.net/h3qJB/. Please let me know how it goes.

You can also do chaining like:

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

It might be that De Morgan's laws gives you an idea of how to make the logic a bit more compact (although I am not sure what is the specific case or is it as simple as comparing values).

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");
发布评论

评论列表(0)

  1. 暂无评论