Show div when radio button selected
Asked Answered
I

5

24

I am novice in javascript and jQuery. In my html have 2 radio buttons and one div. I want to show that div if I check the first radio-button but otherwise I want it to be hidden

so: If radio button #watch-me is checked --> div #show-me is visible. If radio button #watch-me is unchecked (neither are checked or the second is checked) --> div #show-me is hidden.

Here is what I have so far.

 <form id='form-id'>
<input id='watch-me' name='test' type='radio' /> Show Div<br />
<input name='test' type='radio' /><br />
<input name='test' type='radio' />
 </form>
 <div id='show-me' style='display:none'>Hello</div>

and JS:

 $(document).ready(function () { 
$("#watch-me").click(function() {
 $("#show-me:hidden").show('slow');
 });
 $("#watch-me").click(function(){
 if($('watch-me').prop('checked')===false) {
    $('#show-me').hide();}
    });
});

How should I change my script to achieve that?

Illogical answered 16/1, 2014 at 21:25 Comment(0)
E
48

I would handle it like so:

$(document).ready(function() {
   $('input[type="radio"]').click(function() {
       if($(this).attr('id') == 'watch-me') {
            $('#show-me').show();           
       }

       else {
            $('#show-me').hide();   
       }
   });
});
Erythrite answered 16/1, 2014 at 21:37 Comment(2)
I think you can do it shortly like so; $('input[type="radio"]#watch-me').click(fun...Kamasutra
what if the radio button is checked by defaultPhaidra
C
9

Input elements should have value attributes. Add them and use this:

$("input[name='test']").click(function () {
    $('#show-me').css('display', ($(this).val() === 'a') ? 'block':'none');
});

jsFiddle example

Covington answered 16/1, 2014 at 21:37 Comment(0)
P
6
$('input[name=test]').click(function () {
    if (this.id == "watch-me") {
        $("#show-me").show('slow');
    } else {
        $("#show-me").hide('slow');
    }
});

http://jsfiddle.net/2SsAk/2/

Periderm answered 16/1, 2014 at 21:40 Comment(0)
S
1
 $('input[type="radio"]').change(function(){
      if($("input[name='group']:checked")){
      $(div).show();
    }
  });
Studied answered 5/1, 2016 at 9:31 Comment(1)
A code block alone does not provide a good answer. Please add explanations (why it solve the issue, where was the mistake, etc...)Diabolism
B
1
var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});

JSFIDDLE

Bacchic answered 26/5, 2020 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.