0

I have a function that dynamically adds an input and dropdown box when a '+' sign is clicked. However, when the dropdown is changed, the alert returns undefined. Why does it?

jQuery(document).change(".marker-drop-down", function() {       
    alert(jQuery(this).attr("id"));     
});

//functions
function addInputBox() {    
    jQuery("#insert-question-inbox").append('<div id="question-'+i+'-div">
<div id="remove-question-'+i+'" class="ui-icon ui-icon-minus remove-question"></div>
<input class="question-input" type="text" id=question-'+i+' value=question-'+i+' />
<select id="question-'+i+'-drop-down" class="maker-drop-down">
<option>Select</option><option value="multiple-choice">Multiple Choice</option>
<option value="select-all">Select all that apply</option></select><br /></div>');
    i += 1;     
}
Macsupport
  • 5,284
  • 3
  • 27
  • 45
Frank Castle
  • 363
  • 2
  • 21
  • 1
    What is `.marker-drop-down`? Show html code. – Cheery Oct 09 '14 at 05:00
  • scroll to the right... you will see that it is in the append() within the javascript. – Frank Castle Oct 09 '14 at 05:01
  • 2
    In append there is `class="maker-drop-down"`, in select there is `.marker-drop-down`. **maker-drop-down** != **marker-drop-down** – u_mulder Oct 09 '14 at 05:01
  • 1
    I do not see it there. That is why I asking you - what is `.marker-drop-down`?? – Cheery Oct 09 '14 at 05:01
  • 1
    You are referring to `jQuery(document)` for which you do not have defined the id thats why it is displaying undefined – Tushar Oct 09 '14 at 05:02
  • Tushar - what is the solution then? – Frank Castle Oct 09 '14 at 05:02
  • 1
    @massimorai `jQuery(".marker-drop-down").change(function(){ alert(jQuery(this).attr("id")); });` but be sure that you have element with this class as you have a typo – Cheery Oct 09 '14 at 05:03
  • @Cheery - it is the value of the – Frank Castle Oct 09 '14 at 05:04
  • 2
    @massimorai I'm writing for the 3rd time - you do not have such class there. You have `maker-drop-down`, not `marker` – Cheery Oct 09 '14 at 05:05
  • 1
    apart from typo, you need to use event delegation... so marking it as an duplicate – Arun P Johny Oct 09 '14 at 05:05
  • 1
    @massimorai because you appear to be missing it... your selector has **MARKER** and your HTML has **MAKER** – Phil Oct 09 '14 at 05:06
  • @Phil there is big difference between delegated `$(document).on("change", ".maker-drop-down", function() {` and simple `jQuery(document).change(".marker-drop-down", function() {` where `".marker-drop-down"` is just [eventData](http://api.jquery.com/change/), not delegated selector. – Regent Oct 09 '14 at 05:17
  • @Regent Doh! Totally missed that :( – Phil Oct 09 '14 at 05:17
  • @Phil yes, I've reread several times before I understand what is wrong :) – Regent Oct 09 '14 at 05:19

1 Answers1

5

Try to use it as

$(document).on("change",".maker-drop-down", function(){        
        alert($(this).attr("id"));     
    });
Zach
  • 108
  • 8