I'm fairly new to jQuery and am trying to understand some piece of code I just wrote.
I have a simple HTML
<body>
<div id="theDiv">
<button>This is the div</button>
</div>
</body>
And my script looks like this
$(document).ready(function(){
$("button").on("click",function(){
$("<div></div>").attr("id","myDiv").appendTo("#theDiv");
$("<select></select>").addClass("mySelects").appendTo("#myDiv");
});
$(".mySelects").on("click",function(){
console.log("Do some stuff here");
$('<option value="Text">Text</option>').appendTo(".mySelects")
});
});
So what I want to do is add a new div
with a select
and add the select
to a class. The scpipt above does not work, I'm not sure why, whereas the code below does the trick
$(document).ready(function(){
$("button").on("click",function(){
$("<div></div>").attr("id","myDiv").appendTo("#theDiv");
$("<select></select>").addClass("mySelects").appendTo("#myDiv");
$(".mySelects").on("click",function(){
console.log("Just added the class");
$('<option value="Text">Text</option>').appendTo(".mySelects")
});
});
});
I hope some of you jQuery Gurus can explain me what's going on since I don't really know enough to understand it by myself.
Here's the fiddle I've been using http://jsfiddle.net/k1stLsft/2/
Cheers.
Here are a couple of alternatives that add select option. The first one is with delegate, like George suggested:
Fiddle