问题
I'm trying to toggle multiple DIVs that have the same data attribute value based on the value of the select radio button.
But I'm not sure what's wrong with my code below.
By default, the first radio button is always selected on load, how do I trigger it to show the 3 DIVs of the matching value?
Mark-up:
<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();
});
});
Fiddle if you wanted to test: http://jsfiddle.net/calebo/cRKwY/
回答1:
What you have given is syntactically wrong. You need to give this way:
$(".prices[data-period='" + test + "']").show();
Also hide other div
s before refreshing.
$(".prices").hide();
Full Code:
$(document).ready(function() {
$(".prices").hide();
$("input[name$='subscription-period']").click(function() {
var test = $(this).val();
$(".prices").hide();
$(".prices[data-period='" + test + "']").show();
});
});
Fiddle: http://jsfiddle.net/praveenscience/Lgk7B/
回答2:
$(document).ready(function() {
$(".prices").hide();
$("input[name='subscription-period']").click(function() {
var test = $(this).val();
$(".prices[data-period ='" + test + "']").show();
});
});
回答3:
Read attribute equals selector
DEMO
$(document).ready(function () {
$(".prices").hide();
$("input[name$='subscription-period']").change(function () {
var test = this.value;
$(".prices").hide();
$(".prices[data-period='" + test + "']").show();
});
});
回答4:
Use following :
$(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();
});
});
Here is the working demo : http://jsfiddle.net/cRKwY/2/
来源:https://stackoverflow.com/questions/19419276/show-hide-div-based-on-selected-radio-button-input