开发者

jquery toggle div based on radio button selection

开发者 https://www.devze.com 2023-03-22 23:20 出处:网络
I have a radio button group on a survey form whose html looks like: <label>Would you like to compete?</label>

I have a radio button group on a survey form whose html looks like:

<label>Would you like to compete?</label>
      <input type="radio"  name="compete" value="2" id="competenoradio" >
      <label for="compete_no">No</label>
      <input type="radio" name="compete" value="1" id="competeyesradio">
      <label for="compete_yes">Yes</label>
      <div id="competeyes">
        <label class="competeyestxt" hidden=true>Which Location?</label>
        <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true">
        </textarea>
      </div>

The div at the bottom with id 'competeyes' need to be toggled between invisible 开发者_C百科to visible
 based on whether the user selected radio button with id 'compete_yes'.

Here is my attempt at it, which does not work.

Attempt 1:
$('#competeyesradio').bind('change',function(){
  $('#competeyes').toggle($(this).is(':checked'));
});


Attempt 2:

$('div.input input:radio').bind('change',function(){
   $('#competeyes').toggle($(this).is(':checked'));
});

Attempt 3:

$('[name=compete]').bind('change',function(){
  $('#competeyes').toggle($(this).is(':checked'));
 });

Any suggestions?


Your first problem is that you are using $(this).is(':checked') to check if the current element is checked. It will always be true.

$('input[name="compete"]').bind('change',function(){
    var showOrHide = ($(this).val() == 1) ? true : false;
    $('#competeyes').toggle(showOrHide);
 });

Your second problem was that you were using hidden="true" for the fields. You should use CSS to hide the fields. Here is the HTML markup you should be using:

<label>Would you like to compete?</label>

<input type="radio"  name="compete" value="2" id="competenoradio" >
<label for="compete_no">No</label>

<input type="radio" name="compete" value="1" id="competeyesradio">
<label for="compete_yes">Yes</label>

<div id="competeyes" style="display:none">
    <label class="competeyestxt">Which Location?</label>
    <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt"></textarea>
</div>

Here is a demo


$('input[id=competeyesradio]:checked')(function(){ $('#competeyes').toggle();

}


You could do something like what is found here

$('input:radio').bind('change',function(){
    $('#competeyes').toggle($(this).attr('id') == 'competeyesradio');
});


$("#competenoradio[checked]")( 
    function() { 
      $('#competeyes').toggle();
    } 
);


Why are you validating it when toggle just works? At most, it provides you a call back. You should try this:

$('#competeyes').toggle();


You can try this one, although not a free solution.

Disclosure: I'm the developer.

0

精彩评论

暂无评论...
验证码 换一张
取 消