user1484219
user1484219

Reputation: 15

Use jquery to display div based on form value selected

I want to display a div if a certain radio button in a form is selected, but hide that div if any other radio button in the form is selected, using jquery.

This is the code I have that isn't working:

$("select").change(function(){
if($("#radio1").is(":selected")){
    $("#grid_9 omega").slideDown("slow");
} else { $("#grid_9 omega").slideUp("slow"); } 
});

where the id for the radio button I want to have display the div "gid_9 omega" is "radio1".

Thanks for your help!

Upvotes: 1

Views: 244

Answers (2)

Ram
Ram

Reputation: 144689

you should not use space between characters of an ID name, also a select element has nothing to do with radio buttons, try this:

$("#radio1").change(function(){
if($(this).is(":checked")) {
    $(".omega").slideDown("slow"); // note that `omega` has no "hash" or "dot" sign and this returns undefined
} else if ($('.omega').is(':visible')) { // makes sure that omega is visible
   $(".omega").slideUp("slow"); 
} 
});

Upvotes: 0

SuperMykEl
SuperMykEl

Reputation: 623

I took the liberty of thinking that maybe omega was a class that you were referring to incorrectly.

First, there is no select here so that is not going to work for you. You need to test on all input[type=radio].

Next, radio button attribute for selected is actually checked=checked, so you need to test if the one you want to be checked is checked. If not, do nothing, if so, show your div.

A JSFiddle

Using a similar html structure to this below:

<form id="form1" name="form1" method="post" action="">
  <p>
    <label>
      <input type="radio" name="RadioGroup1" value="radio1" id="radio1" />
      Radio 1</label>
    <br />
    <label>
      <input type="radio" name="RadioGroup1" value="radio2" id="radio2" />
      Radio 2</label>
    <br />
    <label>
      <input type="radio" name="RadioGroup1" value="radio3" id="radio3" />
      Radio 3</label>
    <br />
  </p>
</form>
<div id="grid_9" class="omega" style="display:none">show me when Radio 1 is chosen​​​​​

your js would look like this:

$(document).ready(function() {
    $("input[type=radio]").on('click', function(){
        if ($('#radio1').is(':checked')){
            $("#grid_9.omega").slideDown("slow");
        } else { 
            $("#grid_9.omega").slideUp("slow");
        }
    });
});

Upvotes: 2

Related Questions