jquery基于单选按钮选择切换div

时间:2011-07-27 06:32:10

标签: jquery

我在调查表单上有一个单选按钮组,其html如下所示:

<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 to visible
 based on whether the user selected radio button with id 'compete_yes'.

这是我的尝试,但不起作用。

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'));
 });

有什么建议吗?

6 个答案:

答案 0 :(得分:16)

您的第一个问题是您正在使用$(this).is(':checked')来检查当前元素是否已被选中。它永远都是真的。

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

您的第二个问题是您使用hidden="true"字段。您应该使用CSS来隐藏字段。以下是您应该使用的HTML标记:

<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

答案 1 :(得分:2)

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

}

答案 2 :(得分:1)

您可以执行类似here

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

为什么在切换工作时验证它?它最多可以为您提供回电。你应该试试这个:

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

答案 5 :(得分:-3)

您可以尝试this one,但不是免费解决方案。

披露:我是开发人员。