Reputation: 15949
I have a div that I want to show only if a certain value is selected from a drop down menu ( in this case , it is custom-css
)
On the fiddle ( http://jsfiddle.net/obmerk99/8xnzh/1/ ) it works ok...
jQuery(document).ready(function() {
jQuery("#k99-custom-1").change(function () {
jQuery("#k99-custom-1 option:selected").each(function ()
{
if( jQuery(this).attr("value") == "custom-css")
{
jQuery("#customcss").show();
}
else
{
jQuery("#customcss").hide();
}
});
}).change();
});
but in the real page , the select drop down is actually generated dynamically with an "add option" button , so that certain (first) select does not exists on page load (document ready ) and I think that this is the reason that it does not work ..
see the full one here in action ( not working ) : http://jsfiddle.net/obmerk99/ZcAzy/1/
What am i doing wrong in order to have the div shown if the "custom-css" value is selected ? ( now it is set to work only with the first one ( or second ) - but it would be great to make it work with all of the added select lists .. )
Upvotes: 0
Views: 1218
Reputation:
Try using delegation
, like so:
jQuery(function() {
// Here, `.on` is used in its `delegate` form, where it asigns an event to any
// element matching the selector
// regardless when it was added to the DOM
jQuery(document).on('change', "[id^='k99-custom-']", function(e) {
jQuery("[id^='k99-custom-'] option:selected").each(function(i) {
if (jQuery(this).attr("value") == "custom-css") {
jQuery("#customcss").show();
}
else {
jQuery("#customcss").hide();
}
});
})
})
I just noticed in a comment on another answer, you tried something like this. What you did wrong was to delegate the event
of selector [id^='k99-custom-']
to [id^='k99-custom-']
, which, as you can see, is itself. To delegate, you need to asign to either a parent element or the document
itself, as in my example. The most common use is simply to use $(document).on(...
Learn more about .delegate
and the .on
form of it!
Upvotes: 3