jQuery下拉列表根据值隐藏显示div [英] jQuery dropdown hide show div based on value

查看:141
本文介绍了jQuery下拉列表根据值隐藏显示div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个经典问题,但找不到最好的方法。我有一个下拉列表,其中包含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为id且只有这一个。 div二和三必须隐藏。
我也想让视图被加载,所以不仅在更改。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆