noclist
noclist

Reputation: 1819

jQuery - target second radiobutton only when first is checked

I have a set of yes/no radio buttons. I would like a modal window to open when the user clicks an unchecked 'no' radio button only if the yes radio button IS already checked. There is a state where none of the buttons will be checked and in this case I don't want the modal to appear.

My problem is I am showing this modal in a click event on the 'no' button. I have no way to tell if 'yes' was previously checked, since in this scope, we know 'no' is checked because we're inside of the click event for it. Any suggestions?

<span class="yesRadioButton" data-questionnumber="1">
    <input id="MHQPreQuestion1_rbQuestAnswerYes" name="YesNo" type="radio"value="Yes" checked="checked">
</span>
<span class="noRadioButton" data-questionnumber="1">
    <input id="MHQPreQuestion1_rbQuestAnswerNo" name="YesNo" type="radio"value="No">
</span>


$('.noRadioButton > input:radio:not(:checked)').click(function () {
    DialogOpen();
});

Upvotes: 1

Views: 67

Answers (1)

Pabs123
Pabs123

Reputation: 3435

You can set an attribute on the "yes" input when you click it, so you know if it has been previously set. Then you can grab the first input through jQuery and check its value before deciding whether you want to have the popup appear inside of the "no" click handler:

$('.noRadioButton > input').click(function() {
  var yesButton = $('.yesRadioButton > input');
  var yesValue = yesButton.attr('wasChecked');
  
  if (yesValue === "true") {
    //do your popup
  }

  yesButton.attr('wasChecked', false);

});   

$('.yesRadioButton > input').click(function() {
    $(this).attr('wasChecked', true);
}); 

Example here

edit: updated to work with radio buttons, i was thinking check boxes

Upvotes: 2

Related Questions