0

I have JQuery onClick function that builds the HTML elements. One of the elements is Add button. I'm trying to use ID for that button to show the form to the user. I used JQuery selector to call this function but that didn't work. Console that log didn't trigger. Here is example:

   $('.settingsHM ul li').on('click', function(){       
        $.ajax({
           type: 'POST',
           url: 'Components.cfc?method=getRecords',
           data: formID,
           dataType: 'json'
        }).done(function(obj){
          var tbl = "<div><input type='button' name='settingButton' id='settingAdd' value='Add' /></div><table><thead><tr><th>Number</th><th>Name</th><th>Type</th><th>Active</th></tr></thead><tbody></tbody></table>";
              $('#containerMaster').empty().append(tbl);
           }

           return true;
        }else{          
           return false;
        }
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    });
});

//Here I call onClick based on Add button ID.
$('#settingAdd').on('click', function(){
    console.log('test');
});

As you can see my table is built when user click on li element. Then If user clicks on Add button I want to run the process. My current onclick function doesn't react after I click on Add button. I tried to test and place onClick="test()" function inside my button input tag and that works. If someone knows what I'm doing wrong and how I can get this to work please let me know. Thanks.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193
  • `$(document).on('click','#settingAdd',function(){});` Your dinamically created element doesn't have any click events, so you have to do a global click for the whole document looking for that specific id, or create the click inside your `.done()` function whichever works – Lixus Aug 14 '17 at 21:19
  • when the jquery onclick is called on #settingAdd, it isn't currently in the dom. you could fix this by putting the onclick call in the function where you append the button to the dom – Punit Aug 14 '17 at 21:22
  • @Punit Isn't declaring the function inside of another function wrong/not recommended? I'm just trying to keep my code clean. Thank you. – espresso_coffee Aug 14 '17 at 21:28

0 Answers0