如何从单选按钮添加或隐藏选择标记是和否?

时间:2017-02-08 12:26:10

标签: jquery

我有一个带有10个标签的大表格,旁边有选择或输入。在这个表格的最后我有两个单选按钮内联(是,否)我希望选择“否”在这个第十个标签的下面创建另一个新的第十一个标签(带选择标签)并选择“是”到从下面隐藏第11个标签(使用select标签)。

<div class="form-group">
  <label class="control-label col-sm-3"> Is that new? </label>
    <div class="col-sm-4">
        <label class="radio-inline"> <input type="radio" name="optradio"
            id="buy_no"/>No </label>
        <label class="radio-inline"> <input type="radio" name="optradio"
            id="buy_yes"/>Yes </label>
    </div>
</div>
<div class="form-group">
    <label class="control-label col-sm-3" id="label_form"> Months</label>
    <div class="col-sm-1">
        <select class="form-control input-lg" placeholder="Month"
        name="month_change" id="month_change">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
        </select>
    </div>
</div>

选择否:

enter image description here

选择是:

enter image description here

2 个答案:

答案 0 :(得分:2)

使用 .is(':checked')查看是否在jQuery中选中了复选框。

if($('#buy_no').is(':checked')) { 
// Show the div you want to show.
}

if($('#buy_yes').is(':checked')) { 
// Hide the div you want to hide.
}

请务必将此代码放入 document.ready

答案 1 :(得分:1)

只需根据id事件

上所选的单选按钮的valueonchange显示或隐藏它

将类month_change添加到div并隐藏div而不是选择框

$(function(){
  $('.month_change').hide();
  $('input[name="optradio"]').on('change', function() {
      if($(this).attr('id') == 'buy_no') {
        $('.month_change').show();
      }else {
        $('.month_change').hide();
      }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-sm-3"> Is that new? </label>
    <div class="col-sm-4">
        <label class="radio-inline"> <input type="radio" name="optradio"
            id="buy_no"/>No </label>
        <label class="radio-inline"> <input type="radio" name="optradio"
            id="buy_yes"/>Yes </label>
    </div>
</div>
<div class="form-group month_change">
    <label class="control-label col-sm-3" id="label_form"> Months</label>
    <div class="col-sm-1">
        <select class="form-control input-lg" placeholder="Month"
        name="month_change" id="month_change">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
        </select>
    </div>
</div>