BurebistaRuler
BurebistaRuler

Reputation: 6529

jQuery if/else statement when if condition contain or (||) two variables

I'm trying to get value of some elements and put them in one <select> list in <option> tag like: Verify if the radio was checked and which radio is checked take section elements values and insert them with split in <select> as <option>; In my example I have two sections/panels which can be selected through a radio input. My problem is when I do the radio select because I use something like:

var scheduler = $( "#first-radio:checked" );
var cronos = $( "#second-radio:checked" );

$("#add-button").click( function() {
  if ( scheduler || cronos ) {
                              alert('None of radio options were selected!');
  } else{ 
         alert("else where my code must run"); 
  }
});

and normally should take else alert if one of two check box are selected when Add val button is pressed instead take if statement all the time and show if alert and I don't understand why :|

Check fiddle:

Upvotes: 0

Views: 4149

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

The jQuery method will always return jQuery object which will always be truthy, so your code will always execute the if block.

Also the checked status will change during the runtime, so you can't use a status that was fetched when the DOM was initialized - you need to check the current status of the radio buttons in the click handler.

var scheduler = $("#first-radio");
var cronos = $("#second-radio");

$("#add-button").click(function () {   
    if (scheduler.is(':checked') || cronos.is(':checked')) {
        alert("else where my code must run");
    } else {
        alert('None of radio options were selected!');
    }
});

Demo: Fiddle

Upvotes: 5

Related Questions