根据选定的单选按钮输入显示/隐藏 DIV

Show/hide DIV based on selected radio button input

本文关键字:显示 隐藏 DIV 输入 单选按钮      更新时间:2023-09-26

我正在尝试根据选择单选按钮的值切换具有相同数据属性值的多个 DIV。

但我不确定下面的代码有什么问题。

默认情况下,加载时始终选择第一个单选按钮,如何触发它以显示匹配值的 3 个 DIV?

标记:

<nav id="gift-subs-options">
    <ul>
        <li class="selected">
            <label>
                <input type="radio" name="subscription-period" value="3mths" checked />
                <span class="period">3 months</span>                        
            </label>
        </li>
        <li>
            <label>
                <input type="radio" name="subscription-period" value="6mths" />
                <span class="period">6 months</span>
            </label>
        </li>
        <li>
            <label>
                <input type="radio" name="subscription-period" value="12mths" />
                <span class="period">12 months</span>
            </label>
        </li>
    </ul>
</nav>
<div class="prices" data-period="3mths">A 1</div>
<div class="prices" data-period="6mths">B 1</div>
<div class="prices" data-period="12mths">C 1</div>
<div class="prices" data-period="3mths">A 2</div>
<div class="prices" data-period="6mths">B 2</div>
<div class="prices" data-period="12mths">C 2</div>
<div class="prices" data-period="3mths">A 2</div>
<div class="prices" data-period="6mths">B 2</div>
<div class="prices" data-period="12mths">C 3</div>

.JS:

$(document).ready(function() {
    $(".prices").hide();
    $("input[name$='subscription-period']").click(function() {
        var test = $(this).val();
        $(".prices[data-period]='" + test + "'").show();
    });
});
如果您想

测试,请摆弄:http://jsfiddle.net/calebo/cRKwY/

你给出的内容在语法上是错误的。你需要这样给出:

$(".prices[data-period='" + test + "']").show();

刷新之前还要隐藏其他div

$(".prices").hide();

完整代码:

$(document).ready(function() {
    $(".prices").hide();
    $("input[name$='subscription-period']").click(function() {
        var test = $(this).val();
        $(".prices").hide();
        $(".prices[data-period='" + test + "']").show();
    });
});

小提琴:http://jsfiddle.net/praveenscience/Lgk7B/

$(document).ready(function() {
    $(".prices").hide();
    $("input[name='subscription-period']").click(function() {
        var test = $(this).val();
        $(".prices[data-period ='" + test + "']").show();
    });
});

读取属性等于选择器

演示

$(document).ready(function () {
    $(".prices").hide();
    $("input[name$='subscription-period']").change(function () {
        var test = this.value;
        $(".prices").hide();
        $(".prices[data-period='" + test + "']").show();
    });
});

使用以下:

$(document).ready(function() {
   $(".prices").hide();
   var defaultval=$("input[name$='subscription-period']").val();
   $(".prices[data-period='" + defaultval + "'").show();
   $("input[name$='subscription-period']").change(function() {
      $(".prices").hide();
      var test = $(this).val();
      $(".prices[data-period='" + test + "'").show();
  });
});

这是工作演示: http://jsfiddle.net/cRKwY/2/