I use the following jQuery function to perform a slideDown on a DIV, based on the value of a SELECT dropdown:
$(function()
{
$('#show-options').change(function(){
if($(this).val() != '')
{
$('#' + $(this).val()).slideDown();
}
});
});
HTML:
<select id="show-options">
<option value="">Select an Option</option>
<option value="vehicle-type">Vehicle Type</option>
<option value="vehicle-colour">Vehicle Colour</option>
</select>
<div id="vehicle-type" style="display: n开发者_如何学JAVAone;">
<!--form elements in here-->
</div>
<div id="vehicle-colour" style="display: none;">
<!--form elements in here-->
</div>
Now when the form is submitted, any DIVs that were displayed before submission need to be displayed automatically. I can check for the GET variables in my PHP but I need the jQuery code that will mimic the 'change' function - I think this has something to do with triggers or binds.
I do this a lot actually. The easiest way I've found is to just trigger the event after binding it like so:
function showByVal(val) {
$('#' + val).slideDown();
}
$(function()
{
$('#show-options').change(function(){
if($(this).val() != '')
{
showByVal($(this).val());
}
});
showByVal('<? echo $_GET["PreviousVal"]; ?>');
});
As long as the value is set ahead of time (by your PHP Code) then the event will fire after it binds and setup the initial display.
try this:
$("#" + $("#show-options :selected").val()).slideDown();
of course you'll have to write in php the selected attribute to the right option
If you're doing this in response to form submission, why not simply show the DIV (i.e., not make the style "display: none;") when you render the page for those things that have been displayed. You'd need to either keep track, using hidden fields would be one way, or only show those sections that have both been displayed and had an item in the section selected. Either way you can use the inputs that you get from the form to determine which sections have the default visibility set to be shown.
Whenever I need to do something like this I'll do $('#ele').trigger('change')
thus not having to do anything special so when the page loads it just triggers the change event of the select list and as long as the correct value is set once the page loads it calls your already defined change handler.
精彩评论