Issue creating new elements in jQuery

66 views Asked by At

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.

3

There are 3 answers

1
jyrkim On BEST ANSWER

Here are a couple of alternatives that add select option. The first one is with delegate, like George suggested:

   $("body").delegate(".mySelects", "click",function(){
        console.log("Just added the class");
        $('<option value="Text">Text</option>').appendTo(".mySelects")
    });


    $(document).on("click", ".mySelects",function(){
        console.log("Just added the class");
        $('<option value="Text">Text</option>').appendTo(".mySelects")
    });

Fiddle

0
kevintechie On

The <select> with class .mySelects doesn't exist until the button is clicked.

0
Shriike On

As a couple people have already said when you're setting the onclick event the element that you want the event on doesn't exist yet. You need to use a jQuery delegate like this.

$("body").on("click", ".mySelects", function() {...});