Dannyd86
Dannyd86

Reputation: 87

detect selections of 2 sets of radio buttons in jquery

I have a web page which asks the user two simple yes-no questions. Under each question there's a set of two radio buttons in which the user can choose either yes or no.

<p>Question 1 yes or no?</p>

<input type="radio" name="q1" id="q1-y" value="Yes">Yes
<input type="radio" name="q1" id="q1-n" value="No">No 

<p>Question 2 yes or no?</p>

<input type="radio" name="q2" id="q2-y" value="Yes">Yes
<input type="radio" name="q2" id="q2-n" value="No">No

If the user chooses yes for BOTH questions, it needs to display some HTML which will provide a link to a certain page. If the users answers no to one or both of the questions, then some alternative HTML will appear which will display another message.

There can't be a submit button like a form and this has to be a javascript/jquery based solution, not server side. The page needs to:

1) Detect when both sets of questions have been answered. Then 2) Instantly display certain HTML depending on if either a) YES has been answered to both, or b) if a NO has been given once or more.

Essentially, the logic should be something along the lines of:

if( /*both radio buttons answered*/ ){
   if( /*both answers are yes*/ ){
      /*show HTML set 1*/  
   } else {
      /*show HTML set 2*/
   }
}

I have tried looking at questions on this site, but I can't seem to find a solution to this specific problem. Let me know if anything needs clarifying.

Thanks very much!

Upvotes: 0

Views: 2350

Answers (4)

David Thomas
David Thomas

Reputation: 253318

One approach, given the following HTML (note the custom data-* attributes in the appended <div> elements, used to identify which choice those elements relate to):

<p>Question 1 yes or no?</p>
<input type="radio" name="q1" id="q1-y" value="Yes" />Yes
<input type="radio" name="q1" id="q1-n" value="No" />No
<p>Question 2 yes or no?</p>
<input type="radio" name="q2" id="q2-y" value="Yes" />Yes
<input type="radio" name="q2" id="q2-n" value="No" />No

<div class="result" data-relatesTo="Yes">All choices are 'yes'</div>
<div class="result" data-relatesTo="No">All choices are 'no'</div>

Which works with the following jQuery:

// caching the radio elements on the page:
var radios = $('input[type="radio"]'),
// getting the number of unique radio 'groups':
    radioGroups = $.unique($('input[type="radio"]').map(function () {
        return this.name;
    }).get());

// binding an anonymous function as a change-event handler:
radios.change(function () {
    // getting all the checked radio inputs:
    var checked = radios.filter(':checked'),
    // creating an object that maps to the relevant values/choices to be made:
        choice = {
            'yes': checked.filter(function () {
                return this.value.toLowerCase() === 'yes';
            }).get(),
                'no': checked.filter(function () {
                return this.value.toLowerCase() === 'no';
            }).get()
        };

    // if all groups have a checked radio input:
    if (checked.length === radioGroups.length) {
        // iterate over the '.result' div elements:
        $('div.result').each(function (i, el) {
            // using 'toggle(switch)' to show/hide the element,
            // the switch tests whether the choice related to the current
            // element is equal to the number of radioGroups. If it is,
            // it's shown, otherwise it's hidden.
            $(this).toggle(choice[el.getAttribute('data-relatesTo').toLowerCase()].length === radioGroups.length);
        });
    }
});

JS Fiddle demo.

Alternatively, with the same HTML, the following jQuery approach also works:

var radios = $('input[type="radio"]'),
    radioGroups = $.unique($('input[type="radio"]').map(function () {
        return this.name;
    }).get());

radios.change(function () {
    var checked = radios.filter(':checked'),
    // getting all the unique chosen values (in lowercase):
        opts = $.unique(checked.map(function(){
            return this.value.toLowerCase();
        }).get());

    if (checked.length === radioGroups.length) {
        // hide all the '.result' elements:
        $('div.result').hide()
            // filter the 'div.result' elements:
            .filter(function(){
                // if the number of opts (chosen values) is 1
                // (all choices are the same) and the 'data-relatesTo' attribute
                // of the current element we're filtering is equal to that single
                // option, then the element is retained in the selector
                return opts.length === 1 && this.getAttribute('data-relatesTo').toLowerCase() === opts[0].toLowerCase();
        })
        // and so we show it:
        .show();
    }
});

JS Fiddle demo.

References:

Upvotes: 0

matthias_h
matthias_h

Reputation: 11416

Different solution:

$( "input" ).change(function() {

 var buttons = jQuery("input:radio:checked").get();
 var values = $.map(buttons, function(element) {
    return $(element).attr("value");
 });

 if(values == "Yes,Yes") {
   alert("both yes");
 }
 else {
  //do something else
 }

});

Demo: Multiple Radiobuttons

Don't like to check the string like that but could be adjusted in a proper way.

Upvotes: 1

Hackerman
Hackerman

Reputation: 12305

Try this:

$(document).ready(function(){
$("#yep").hide();
$("#nope").hide();  

$(".nones").click(function(){
  $("#yep").hide();
  $("#nope").show();
});

$(".yipis").click(function(){
   var checkeo = 1;
   $( ".yipis" ).each(function( index ) {
      if($(this).is(":checked") == false)
      {
          checkeo = 0;
      };
    });
    if(checkeo){
        $("#nope").hide(); 
        $("#yep").show();
    }
});    
});

Working fiddle: http://jsfiddle.net/robertrozas/84o46mqd/

Upvotes: 1

jwatts1980
jwatts1980

Reputation: 7356

Here is a possible way to access the values you want. JSFiddle

HTML

<p>Question 1 yes or no?</p>

<input type="radio" name="q1" id="q1-y" value="Yes">Yes
<input type="radio" name="q1" id="q1-n" value="No">No 

<p>Question 2 yes or no?</p>

<input type="radio" name="q2" id="q2-y" value="Yes">Yes
<input type="radio" name="q2" id="q2-n" value="No">No

<p>
    <input type="button" id="finished" value="Submit" />
</p>

<div id="htmlarea"></div>

JavaScript

I find that jQuery is() function and the pseudo class :checked are helped when reading radio buttons.

$("#finished").click(function() {
    var q1y = $("#q1-y").is(":checked");
    var q1n = $("#q1-n").is(":checked");
    var q2y = $("#q2-y").is(":checked");
    var q2n = $("#q2-n").is(":checked");

    if (q1y && q2y) {
        $("#htmlarea").html("Both yes");
    } else if (q1n && q2n) {
        $("#htmlarea").html("Both no");
    } else {
        var html = "";
        if (q1y) html += "Q1 yes. ";
        if (q1n) html += "Q1 no. ";
        if (q2y) html += "Q2 yes. ";
        if (q2n) html += "Q2 no. ";
        if (html=="") html = "None selected";
        $("#htmlarea").html(html);
    }
});

Instead of setting the HTML text, use window.location.href = "http://someurl.com"; if you want to redirect to another webpage.

Upvotes: 0

Related Questions