Nirm
Nirm

Reputation: 7

Jquery - finding values of radio buttons and changing the css of another element

I have a radio button group

<input type="radio" name="Q1" value="Yes />
<input type="radio" name="Q1" value="No />

I also have 2 divs

<div id="Q4" style="display:none"> Some content</div>
<div id="Q5" style="display:none"> Some content</div>

This is what I would like to do using Jquery

If someone clicks radio button with value Yes - set div id=Q4 to display:block. If someone clicks radio button with value No - set div id=Q4 to display:none and set div id=Q5 display:block

I have been trying and not very successful. I have used alerts in the jQuery to try and understand what I am doing wrong. Can anyone please help

$('input[type="radio"]').click(function(){
var userClick= $('input:radio[name=Q1]:checked').val();
switch(userClick){
  case 'Yes':
alert('Number1');
   case 'No':
     alert('Number2');    
  }
});

Upvotes: 0

Views: 306

Answers (4)

j08691
j08691

Reputation: 207901

Here's a simple way to do what you're describing:

$('input[name=Q1]').click(function () {
    $('#Q4,#Q5').hide();
    if ($(this).val() == "Yes") $('#Q4').show();
    if ($(this).val() == "No") $('#Q5').show();
});

jsFiddle example

Upvotes: 0

c0deNinja
c0deNinja

Reputation: 3986

Hey you can use jQuery's show() and hide() methods to show your divs.

Try something like this:

$(document).ready(function() {
    $('input[type="radio"]').click(function(){
        var userClick= $('input:radio[name=Q1]:checked').val();

        if(userClick === "Yes") {
            $("#Q4").show();
            $("#Q5").hide();
        } else if(userClick === "No") {
            $("#Q5").show();
            $("#Q4").hide();
        }
    });
});

Upvotes: 0

Raman
Raman

Reputation: 1376

You can use the change event handler on the radio buttons using the name property of the checkboxes and handle the display. Something like this:

$("input[@name='Q1']").change(function(){
    var selected = this.value;

    if (selected === "Yes") {
        $("#Q5").css("display", "none");
        $("#Q4").css("display", "block");            
    }
    else {
        $("#Q4").css("display", "none");
        $("#Q5").css("display", "block");   
    }
});

And also double quotes at the end of value are missing in checkboxes. Hope this is just a ty[o in the questions only. otherwise please correct that also.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can do

$('input[type="radio"]').change(function(){
    var value = this.value;

    if (value === "Yes") {
        $("#Q4").css("display", "block");
        $("#Q5").css("display", "none");
    }
    else {
        $("#Q5").css("display", "block");
        $("#Q4").css("display", "none");
    }
});

Here's a nice working demo: http://jsfiddle.net/byvvx/

Upvotes: 1

Related Questions