jQuery下拉根据值隐藏显示div [英] jQuery dropdown hide show div based on value
问题描述
这是一个经典问题,但找不到最佳方法.我有一个带有 id project_billing_code_id 和 3 个值 (1, 2, 3) 的下拉列表.
this is a classic question but can't find the best approach. I have a dropdown with id project_billing_code_id and 3 values (1, 2, 3).
如果选择的值 = 1,则显示 id 为 1 且仅此 1 的 div.div 2 和 3 必须隐藏.我还想在加载视图时实现这一点,而不仅仅是在更改时实现.
If value selected = 1 then show div with id one and only this one. div two and three must be hidden. I also want to make this happen when view is loaded so not only on change.
$(document).ready(function() {
$("#hourly").hide();
$("#per_diem").hide();
$("#fixed").hide();
$("#project_billing_code_id").change(function() {
if ($("#project_billing_code_id").val() == '1') {
$("#hourly").show();
}
else if ($("#project_billing_code_id").val() == '2') {
$("#per_diem").show();
}
else if ($("#project_billing_code_id").val() == '3') {
$("#fixed").show();
}
else {
$("#hourly").hide();
$("#per_diem").hide();
$("#fixed").hide();
}
});
});
推荐答案
你已经接近了.您可能需要对行为进行一些小的调整,以确保隐藏所有 div 并且在页面加载时显示正确的 div.
You were close. You probably want a few small tweaks to the behaviours to make sure all the divs hide and that correct div is showing on page load.
试试这里的代码:http://jsfiddle.net/irama/ZFzrA/2/
或者在这里获取更新的 JS 代码:
Or grab the updated JS code here:
hideAllDivs = function () {
$("#hourly, #per_diem, #fixed").hide();
};
handleNewSelection = function () {
hideAllDivs();
switch ($(this).val()) {
case '1':
$("#hourly").show();
break;
case '2':
$("#per_diem").show();
break;
case '3':
$("#fixed").show();
break;
}
};
$(document).ready(function() {
$("#project_billing_code_id").change(handleNewSelection);
// Run the event handler once now to ensure everything is as it should be
handleNewSelection.apply($("#project_billing_code_id"));
});
让我们知道你的进展!
这篇关于jQuery下拉根据值隐藏显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!