0

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:

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference between $( "#first-radio:checked" ) and (scheduler.is(':checked') ?
$( "#first-radio:checked" ) will return an object. scheduler.is(':checked') will return a boolean.
the thing is $(SELECTOR) always returns a jQuery object even it is not there so your if condition is always true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.