简体   繁体   中英

jQuery Select -> Hide/Show div on selection

I have a page set up with quite a few different forms...each of these forms has a select field in it. Upon selection of one of the options, I want to display a div. When any of the other options are selected, I want to hide that same div. However, I am having troubles getting it to work.

The 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();

    }

});

Some of the 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>

Final jQuery (that works):

$(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();

        }

    });

});

尝试将代码包装在

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

replace 2nd and 3rd line

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

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

with

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM