【问题标题】:jQuery Select -> Hide/Show div on selectionjQuery Select -> 在选择时隐藏/显示 div
【发布时间】:2011-11-07 15:06:06
【问题描述】:

我有一个页面设置了很多不同的表单...每个表单都有一个选择字段。选择其中一个选项后,我想显示一个 div。 When any of the other options are selected, I want to hide that same div.但是,我无法让它工作。

jQuery:

$('select').change(function() {

    daytimestamp = $('select').attr('id');

    val = $('select option:selected').val();

    alert(daytimestamp);

    alert(val);

    if( val == 'Other Event' ) {

        // We need to show the description div

        $('#event_description_' + daytimestamp).show();

    }

    else {

        // We need to hide the description div

        $('#event_description_' + daytimestamp).hide();

    }

});

部分 HTML:

<form name='add_cal_event_1320105600' id='add_cal_event_1320105600' action='' method='POST'>
<input type='hidden' name='event_timestamp' value='1320105600' />
Title: <input type='text' name='cc_title' width='100%' /><br />
Time: <input type='text' name='cc_time' size='8' /> <br />
Event type: <select name='cc_event_type' id='1320105600'>
<option value='Wedding'>Wedding
<option value='Rehearsal Dinner'>Rehearsal Dinner
<option value='Other Event'>Other Event
<option value='Event Pending'>Event Pending
</select>
<div id='event_description_1320105600' style='display:none;'>Event Title: <input type='text' name='cc_event_type_override' value='' /><br />Event Description: <input type='text' name='cc_event_description' value='' /></div>
Location: <input type='text' name='cc_location' /><br />
<textarea name='cc_description' class='mceEditor' cols='35'></textarea><br />
<input type='submit' onclick='javascript: jQuery("#add_cal_event_1320105600").submit();' name='submit_form' value='Add Event' />
</form>

最终的 jQuery(有效):

$(document).ready(function(){

    $('select').change(function() {

        daytimestamp = $(this).attr('id');

        val = $('#' + daytimestamp + ' option:selected').val();

        if( val == 'Other Event' ) {

            // We need to show the description div

            $('#event_description_' + daytimestamp).show();

        }

        else {

            // We need to hide the description div

            $('#event_description_' + daytimestamp).hide();

        }

    });

});

【问题讨论】:

  • 这里似乎工作正常jsfiddle.net/bryanjamesross/RF9Fg/1
  • 究竟是什么问题。清楚地解释你的问题
  • 这里也是,期望的行为是什么?
  • 我想这意味着它与页面上的其他代码有 jQuery 冲突?

标签: jquery select option


【解决方案1】:

尝试将您的代码包装在

$(document).ready(function(){});

【讨论】:

  • 这使得通用代码工作正常,然后我也必须进行调整。谢谢!
【解决方案2】:

替换第 2 行和第 3 行

daytimestamp = $('select').attr('id');

val = $('select option:selected').val();

daytimestamp = $(this).attr('id');

val = $(this).find('option:selected').val();

【讨论】:

  • 你可以写val = $('select option:selected').val();而不是var value = $('select#id').val();
  • 哦 - 也许我正在使用的更新版本是这个原因?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多