dtbonklcs575884485 2011-02-19 14:34
浏览 261
已采纳

默认情况下隐藏元素取决于下拉列表

I have a form element, that is hidden or show depending on a dropdown element in my form. I've been able to change the visibility when the dropdown changes.

Here's my code right now:

$("select[name=post_category]").change(function(){
var id = $("select[name=post_category]").val();
if(id != 3){
    $("dt#post_url-label").hide();
    $("dd#post_url-element").hide();
}
else{
    $("dt#post_url-label").show();
    $("dd#post_url-element").show();
}
});

What I want is the fields to be hidden, unless the page loads with id=3 (so i can't just hide them with CSS), in that case the field has to be visible from the start. Right now, the field is always visible on pageload.

Any suggestions how I should go about this?

  • 写回答

3条回答 默认 最新

  • dongya3627 2011-02-19 14:40
    关注

    Try this:

    $('select[name="post_category"]').change(function() {
        $('dt#post_url-label, dd#post_url-element').toggle( +this.value === 3 );
    }).change();
    

    The idea is to trigger the change event immediately. You should be able to achieve that by using either triggerHandler('change') or just change().

    Live demo 1: http://jsfiddle.net/XE78E/
    Live demo 2: http://jsfiddle.net/XE78E/1/

    The 2. demo shows that the element is visible if the 3-rd option is preselected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流