Dirty Bird Design
Dirty Bird Design

Reputation: 5553

Can 2 conditionals be combined like this?

I want to 1)display an alert if ("#one") is checked and ("#two") isn't checked. Then display a different alert if both are checked. What I have does the first part right, then displays both alerts on the second part.

$("#one").click(function() {
    if($(this).is(":checked") && $("#two").is(":not(:checked)")) {
    alert("foo");
    } else {
        if($(this).is(":checked") && $("#two").is(":checked")) {
            alert("foo foo");
        }
    }
});

Upvotes: 0

Views: 111

Answers (5)

Jordan
Jordan

Reputation: 1238

I'd refactor a bit to get rid of the nested ifs and dry things up a bit:

$("#one").click(function() {
    if(!this.checked) { return }
    var message = $("#two").is(':checked') ? 'foo foo' : 'foo';
    alert(message)
});

Upvotes: 1

Adam Ayres
Adam Ayres

Reputation: 8910

JSfiddle with solution

HTML:

<form>
   <input id="one" type="checkbox" />
   <input id="two" type="checkbox" />
</form>

JS:

var one = $("#one");
var two = $("#two");

one.click(function() {    
    if (one.is(":checked"))  {
        if (two.is(":checked")) {
           alert("foo foo"); 
        } else {
           alert("foo");
        }  
    }
});

Upvotes: 1

andypaxo
andypaxo

Reputation: 6641

It looks fine to me. Example of this in action here: http://jsfiddle.net/andypaxo/9vJGL/

Is this the behaviour that you want?

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

$("#one").click(function() {
    if(this.checked) {
       var $two = $("#two");
       if (!$two.is(":checked")) {
            alert("foo");
       } else {
            alert("foo foo");
       }
    }
});

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359966

You're overcomplicating it, I think.

$("#one").click(function() {
    var thisIsChecked = this.checked,
        twoisChecked = $('#two').get(0).checked;

    if(thisIsChecked) {
         if (twoisChecked) {
            alert('foo foo');    //  <----
         }                       //      |  note the switch
         else {                  //      |
            alert('foo');        //  <----
         }
    }
});

See also: When to use Vanilla JavaScript vs. jQuery?

Upvotes: 3

Related Questions