非常基本的显示/隐藏div与jQuery中的单选按钮

时间:2017-08-23 08:44:21

标签: jquery

我有两个单选按钮(#bill和#invoice)。当我点击radiobutton #invoice时,我想要一个div出现(#periods)。当我点击#bill时,我希望#periods隐藏。当我点击#invoice时,我希望它再次出现。

我已尝试过所有内容(.prop,:checked,length ===等)。有人可以帮我解决这个非常基本的问题吗?

if ($("#invoice:checked").length == 1) {
        $('#periods').hide();
        $('#periods').show();

    } 
    else if ($("#bill:checked").length == 1) {
        $('#periods').hide();
    }
    else {
            $('#periods').hide();
        }
    });

3 个答案:

答案 0 :(得分:1)

检查输入是否检查的最简单方法:检查。

if($(element).is(':checked')){ /* IS CHECKED */}

问候!

答案 1 :(得分:0)

要实现这一目标,您可以在两个无线电上放置一个公共类。然后,您可以将change事件处理程序挂钩到它们,并根据所选无线电的值显示#periods div。试试这个:



$('.radio').change(function(){
  $('#periods').toggle(this.value == 'bill');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="type" value="bill" class="radio" checked />Bill<br />
<input type="radio" name="type" value="invoice" class="radio" />Invoice<br /><br />

<div id="periods">
  #PERIODS
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我认为最简洁的写法如下:

$("#periods").toggle($("#invoice").prop("checked"))

如果发票和账单交替,这是有效的,根据我的理解是这种情况。