When an option is selected the corresponding checkbox <div>
is automatically hidden using jQuery. For example, user selects Item 1 from the select box, and <div class="item1">
is immediately hidden.
Caveat: Both will be visible, so the user changing the select option must be accounted for (eg. user selects an option who's corresponding checkbox has already been checked). The checked state must be removed and the corresponding <div>
should hide.
Needs to be compatible with FF, Safari, Opera, IE7 + 8 (6 if possible, not required)
Update: The corresponding <div>
of the default selected option should be hidden on page load.
Update 2: This is now resolved. Thanks a ton to both Joel and ckramer. Both proposed solutions work perfectly. I chose ckramer's solution as the accepted answer because it required no extra markup, but both solutions work great!
<select>
<option selected="selected" id="item1" value="1">Item 1</option>
<o开发者_开发技巧ption id="item2" value="2">Item 2</option>
<option id="item3" value="3">Item 3</option>
</select>
<div class="item1">
<input type="checkbox" id="a-item1" value="5" />
<label class="checkbox" for="a-item1">Item 1</label>
</div>
<div class="item2">
<input type="checkbox" id="a-item2" value="6" />
<label class="checkbox" for="a-item2">Item 2</label>
</div>
<div class="item3">
<input type="checkbox" id="a-item3" value="7" />
<label class="checkbox" for="a-item3">Item 3</label>
</div>
I think something like this would work:
$(document).ready(function() {
dealWithSelect($("select").find("option:selected").attr("id"));
$("select").change(function(){
var selectedId = $(this).find("option:selected").attr("id");
$(this).find("option").each(function() {
var optionId = $(this).attr("id");
// could probably also use $("."+optionId).show(); here
$("div."+optionId).show();
});
dealWithSelect(selectedId);
});
});
function dealWithSelect(selectedId) {
$("."+selectedId).hide().find(":checkbox:checked").attr("checked","");
}
Update to address questions in comments
I've update the original code block, so it is all put together. To address the initial state, we've got the dealWithSelect
function. I opted for a slightly different approach to solve your second issue, which is to display all of the divs that have Ids that match select option values before hiding the appropriate div. The list of items shown should be bound by the list of options in the select, so the other divs on the page should not be shown.
Edit: had it right the first time.
$("select").change(function() {
var selected = $(this).val(); // 1, 2, 3, etc.
$("div:not(:visible)").show(); // show all
// if you add a class to the checkbox divs (i.e. "selectdiv") replace with: "div.selectdiv"
$(".item" + selected) // get the div
.hide()
.find("input:checked") // find the checkbox inside the div
.removeAttr("checked"); // uncheck the checkbox
});
To the Update:
$(function() {
$(".item" + $("select").val()).hide()
});
精彩评论