Reputation: 37
I have this code (code is working right now and is copied from another Stack Overflow thread):
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</Select>
<div id="red" class="colors" style="display:none"> .... </div>
<div id="yellow" class="colors" style="display:none"> ... </div>
<div id="blue" class="colors" style="display:none"> ... </div>
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
What I want to do with this is to get control with option selected when page load. If you run this into your browser, you will not get any div showing on page, but when you change option everything works.
So the question is how I can display any of those div elements when page load? I will need to have control over this, it will be great if that is possible to do with attribute "selected"?
Upvotes: 1
Views: 234
Reputation: 27022
Generally speaking, the way to do this is to trigger the event after binding it, something like this:
$('selector').on('someEvent', function() {
//...
}).trigger('someEvent');
You can also use the shortcut functions:
$('#colorselector').change(function(){
//...
}).change();
Upvotes: 1