Reputation: 4596
jQuery('#sbox-window').on('change', '#filter-by-site', function(){
console.log(jQuery(this).val());
console.log('change');
});
<div id="sbox-window">
<div id="sbox-content">
<p>
<select id="filter-by-site">
<option value="null">Filter cameras by site</option>
<option value="1">Site 1</option>
<option value="2">Site 2</option>
<option value="3">Site 3</option>
</select>
</p>
</div>
</div>
Nothing happens... With deprecated live()
all works fine. Where is problem?
Upvotes: 1
Views: 139
Reputation: 30463
Use:
jQuery(document).on('change', '#sbox-window #filter-by-site', function(){
console.log(jQuery(this).val());
console.log('change');
});
Because when you do jQuery('#sbox-window')
there is no such element yet (because DOM constructs sequentially and you define the block lower), so you call on
method for empty array of elements, and of course there is no effect.
As was mentioned there is another option:
$(document).ready(function() {
$('#sbox-window').on('change', '#filter-by-site', function(){
console.log($(this).val());
console.log('change');
});
});
Upvotes: 1
Reputation: 5747
Use latest version of jquery library, its working fine
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Upvotes: 0
Reputation: 74738
you can use this way too:
jQuery(document).on('change', '#filter-by-site', function(){
console.log(jQuery(this).val());
console.log('change');
});
Upvotes: 0
Reputation: 2138
Actually this works. Is it possible that you are attaching the event to "sbox-window" that is part of a Jquery Template or to some other means that generate the div dynamically?. Depending on the implementation the "sbox-window" div doesn't exist during the document, ready so you'll nee to bubble up to a higher Dom-Object--- worst case to the document... but I wouldn't recommend that... This is also why "live" works.
Upvotes: 3
Reputation: 1944
You could just use $.bind on the element.
Or, far better, you can do it without using jquery at all just with:
document.querySelector('#filter-by-site').addEventListener('change', changeHandler);
function changeHandler(e) {
console.log('change');
}
Upvotes: 0
Reputation: 50573
It's working fine, see a working example, so what you seem to lack it's execute your query code on a DOM ready handler.
$(document).ready(function() {
$('#sbox-window').on('change', '#filter-by-site', function(){
console.log($(this).val());
console.log('change');
});
});
Upvotes: 0
Reputation: 74420
Maybe at time you are using delegation, #sbox-window
is not already in DOM.
Wrap it in ready callback function:
$(function(){
jQuery('#sbox-window').on('change', '#filter-by-site', function(){
console.log(jQuery(this).val());
console.log('change');
});
});
.live() use document as delegate.
Upvotes: 0