Reputation: 5992
I need to execute the following script on newly added element
$(".select").selectmenu();
The newly added element is:
<div class="Div11" >
<label>Choisir Une Colonne</label>
<select class="select">
<option value="Sum">Somme</option>
<option value="Max">Max</option>
<option value="Avarage">Moyenne</option>
<option value="Min">Min</option>
</select>
<label>Choisir Une Colonne</label>
<select class="select">
<option value="Col1">Col1</option>
<option value="Col2">Col2</option>
<option value="Col3">Col3</option>
<option value="Col4">Col4</option>
</select>
</div>
I wrote the following script:
$(document).on('change ready', 'select', function() {
alert('ok');
$(".select").selectmenu();
});
However, this doesn't work. What's going wrong with this script?
Upvotes: 0
Views: 60
Reputation: 34107
No need of event here.
Once you set the html contents you need to call $(".select").selectmenu();
If you are setting the html content inside the success handler of $.ajax()
you need to call $(".select").selectmenu();
there.
If you don't have control over this you need to use MutationObserver to check when a DOM node is added.
Upvotes: 1
Reputation: 1073
First, giving an element a class of its own name is redundant. The full selector would be div.Div11
and select.select
. Maybe choose a class name that's a little more descriptive.
Second, I don't think the document ever fires a change event (There are DOM mutation events https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events and observers https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver, but I'm not sure those are considered best practices). So you're only binding to the selects that already exist when the page loads. When you dynamically add code, you have to add the event listener after it exists in the DOM.
I'm not sure how you're adding your html, but you could do something like this:
$(document).on('ready', function () {
$('your html').appendTo(document).find('select').selectmenu();
});
EDIT: Although, if you have more than one select you may have to call .selectmenu()
on each one.
$(document).on('ready', function () {
$('your html').appendTo(document).find('select').each(function() {
$(this).selectmenu();
});
Upvotes: 1
Reputation: 13506
The reason is that select
element is you add later,not exist when the page on load.
Suppose <div class="Div11"></div>
is fixed(means it exist when the page on load),you can change to below:
$(document).ready(function(){
$(".Div11").on("change","select",function(event){
alert("ok");
$(this).selectmenu();
})
});
Upvotes: 1