1

I am writing an application using jQuery, where when a button is clicked, a select box is generated and appended to a row. Whenever the select changes, it should trigger the change event, but using .on("change", function() {}); isn't working:

Code:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML5-Template</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <style type="text/css">
            html, body
            {
            }

            input,select {
                border: 1px solid #404048;
                padding: 4px;
            }
        </style>
        <script type="text/javascript" src="../JavaScript/JQuery/jquery-1.9.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#cmdCreateRow").click(function() {
                    var row = $("<div />")
                    .css("font", "normal 12px Verdana")
                    .css("padding", "8px")
                    .css("display", "inline-block")
                    .css("background", "#F0F0F8")
                    .css("border", "1px solid #A0A0A8")
                    .css("margin", "2px");

                    var types = [
                        "Local", 
                        "Remote",
                        "(Custom)"
                    ];

                    var type = $("<select />").attr("class", "member-type");
                    for(var i in types) {
                        type.append($("<option />").val(types[i]).text(types[i]));
                    };

                    row.append(type);

                    $("#Container").append(row).append($("<br />"));
                });

                $(".member-type").on("change", function() {
                    alert("changed");
                });
            });
        </script>
    </head>
    <body>
        <input type="button" id="cmdCreateRow" value="Create Row" />
        <div id="Container">
        </div>
    </body>
</html>

Any idea's what I'm doing wrong?

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313

2 Answers2

9

As $(".member-type") is empty when you do the binding, you're not doing anything.

Change

$(".member-type").on("change", function() {
       alert("changed");
});

to

$(document).on("change", ".member-type", function() {
         alert("changed");
});

or this because the #Container element is static:

$("#Container").on("change", ".member-type", function() {
         alert("changed");
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Try this:

$(document).on("change", ".member-type", function() {
    //Code
});

This is the replacement for: "live" in jQuery, see: http://api.jquery.com/live/

--

The regular "on" method will only work for elements which are already available in the DOM.

Dillen Meijboom
  • 963
  • 7
  • 13