Pawan
Pawan

Reputation: 32321

Combobox event is not geting invoked

On click of a button a Combo Box gets displayed and on select of a Combo Box . The change event is not getting called .

Please let me know where i am making the mistake .

<html>
<head>
<script src="jquery17.js" type="text/javascript"></script>
<script>
  $("select").change(function(){
        alert(this.id);
    });

$(document).ready(function(){
  $("button").click(function(){
   var s = $('<select />');
   var data = {
    'foo': 'bar',
    'foo2': 'baz'
}
for(var val in data) {
   $('<option />', {value: val, text: data[val]}).appendTo(s);
}
s.appendTo('body');
 });
});
</script>
</head>
<body>
<div id="div1"></div>
<button>Get External Content</button>
</body>
</html>

Upvotes: 0

Views: 186

Answers (3)

Jai
Jai

Reputation: 74738

You have to place that in the doc ready but after appending those to body and yes that is dynamic so delegate the event to closest parent element or document itself which is the parent of all.

<script>
  $(document).ready(function(){
      $("button").click(function(){
           var s = $('<select />');
           var data = {
                 'foo': 'bar',
                 'foo2': 'baz'
            }
           for(var val in data) {
               $('<option />', {value: val, text: data[val]}).appendTo(s);
            }
          s.appendTo('body');
       });

       // you need to place that here.
             $(document).on('change', 'select', function(){
                 alert(this.id);
             });

    });

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

$("select").change(function(){
    alert(this.id);
});

The problem is that you don't do this inside your $(document).ready(function(){ block.

Move it into there, otherwise you are setting an event handler on DOM elements that do not yet exist.

Upvotes: 1

Talha Akbar
Talha Akbar

Reputation: 10030

$(document).on("change", "select", function(){
        alert($(this).attr("id"));
});

As <select> tag is appended dynamically so, you have to delegate event on it.

Upvotes: 3

Related Questions