-1

I have looked though all the historic answers to this question but nothing seems to be working for me

When a button is clicked on my page , A div box becomes visible and a table is added

$('#NewParentItem').click(function() { 

InnerTable =  "<table width='90%' bgcolor='#CCCCCC' align='center'  >"
InnerTable += "<tr height='12px'> "
InnerTable += "<td width='2%'></td> "   
InnerTable += "<td width='68%' style='text-align:center' > <input type='text' name='Item' placeholder='Main Item Name' size='12'> </td> "   
InnerTable += "<td width='30%'> <button type='button' id='NewParentSubmit' value='generate new element' >Enter </button>  </td> "
InnerTable += "</tr> </table>" 
DisplayUniDiv(160,200,50,200) // display div box
$('#UniDivHead').html("Add New Main Group Item (Parent)")           
$('#UniDivBody').html( InnerTable )         
}) ; // End of Function `  

This table now includes a button with the id NewParentSubmit

Further within my script I have the following

$(document).on('click', '#NewParentSubmit' , function() {
    alert(" Submit ")  
    }) ;     // End of Function

I would now expect this to trigger( after the button has been dynamically created ) when the user clicks the button , But nothing is happening ?

All these functions are contained within

$(document).ready(function() { 

});

Can anyone offer a solution or some suggestion please ?

Thanks

Mick
  • 2,840
  • 10
  • 45
  • 61
  • 2
    You should have only one element with same id, use class instead. – jcubic Jan 27 '16 at 13:15
  • They are unique ids ? #NewParentItem / #NewParentSubmit – Mick Jan 27 '16 at 13:18
  • 2
    He is going to have only one element with `NewParentSubmit` Id as he is replacing whole content with that table on click. – Pardeep Dhingra Jan 27 '16 at 13:18
  • 2
    Your code is working check this https://jsfiddle.net/4p5udrb1/ – Pardeep Dhingra Jan 27 '16 at 13:18
  • 1
    You have to provide MCVE because your posted code doesn't explain your issue. Now i'm wondering what's doing `DisplayUniDiv()` method?! Maybe this add element overlaying the button, making it unclickable. Or maybe click event propagation is stopped in some way... – A. Wolff Jan 27 '16 at 13:20
  • 1
    Given that the code provided does not have the error described, could you recreate your problem in jsfiddle.net (or similar)? The question should pass the [MCVE](http://stackoverflow.com/help/mcve) test, at the moment it's not verifiable. – freedomn-m Jan 27 '16 at 13:24
  • Ok, i really think the click event propagation is stopped... Test it by capturing it instead: `document.addEventListener('click', function(e){if(e.target.id === "NewParentSubmit") alert('Submit');}, true);` – A. Wolff Jan 27 '16 at 13:26
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Liam Aug 02 '21 at 14:13

2 Answers2

1

Have a look https://jsfiddle.net/1waumb6d/

$(document).ready(function()
{
$('#NewParentItem').click(function() { 

InnerTable =  "<table width='90%' bgcolor='#CCCCCC' align='center'  >"
InnerTable += "<tr height='12px'> "
InnerTable += "<td width='2%'></td> "   
InnerTable += "<td width='68%' style='text-align:center' > <input type='text' name='Item' placeholder='Main Item Name' size='12'> </td> "   
InnerTable += "<td width='30%'> <button type='button' id='NewParentSubmit' value='generate new element' >Enter </button>  </td> "
InnerTable += "</tr> </table>" 
//DisplayUniDiv(160,200,50,200) // display div box
$('#UniDivHead').html("Add New Main Group Item (Parent)")           
$('#UniDivBody').html( InnerTable )         
}) ; 
});

$(document).on('click', '#NewParentSubmit' , function() {
    alert(" Submit ")  
    }) ; 

The Enter button is working as expected.

adeel41
  • 3,123
  • 1
  • 29
  • 25
  • 2
    So what could be OP's issue??? This had already been commented, it shouldn't be an anwser – A. Wolff Jan 27 '16 at 13:33
  • I didn't read all answers first but I guess if this code worked then he should just copy paste this code. – adeel41 Jan 27 '16 at 16:22
-1

JQuery attaches event handlers as the code is called. So if the button is created AFTER $(Document).ready() is fired, it will NOT have the event handler attached to it, even though it matches the element.

Keep in mind, when you call $('#Id').click(function(){}); You are running a script against the DOM as it exists at the moment its called. All you're really saying is. "Give me all elements that match the selector, Apply a click handler to it that fires function() when you click it"

So if the button is created AFTER that fires, you'll need to re-run that bit of code again. I'd also recommend seperating some of your code so you can do this without writing code in multiple places

so try this:

function generateHTML() {
    var InnerTable =  "<table width='90%' bgcolor='#CCCCCC' align='center'  >";
    InnerTable += "<tr height='12px'> "
    InnerTable += "<td width='2%'></td> " ;  
    InnerTable += "<td width='68%' style='text-align:center' > <input type='text' name='Item' placeholder='Main Item Name' size='12'> </td> "  ; 
    InnerTable += "<td width='30%'> <button type='button' class='NewParentSubmit' value='generate new element' >Enter </button>  </td> ";
    InnerTable += "</tr> </table>";
    return InnerTable;
}

function setButtonEvent() {
    $('.NewParentItem').click(function() { //notice change to class from ID here
         generateTable();
    });
}

function generateTable() {
    DisplayUniDiv(160,200,50,200); // display div box
    $('#UniDivHead').html("Add New Main Group Item (Parent)");          
    $('#UniDivBody').html( generateHTML());
    setButtonEvent();       
}

$(document).ready(function() {
    generateTable();
});
Bcbury
  • 117
  • 1
  • 9
  • But OP is delegating event to `document` level – A. Wolff Jan 27 '16 at 13:36
  • the event handler will be attached at the document level. same as if you called $('.selector').click(function() { }); from your console. any html added to the dom after the original event handler declaration is called will need to have the event handler attached to it.. Or maybe i'm misunderstanding. – Bcbury Jan 27 '16 at 13:42
  • You can just delegate event to any static container to handle any dynamic elements (the event just has to bubble through this delegated level), see: https://learn.jquery.com/events/event-delegation/ – A. Wolff Jan 27 '16 at 13:45
  • Ah, ok, I understand what you mean now. in that case, his issue is with the ID selector. as Jquery will only grab the first element with that ID in the dom. So the first button (the original) would work, but any further buttons wouldn't because it only sees the first. – Bcbury Jan 28 '16 at 16:45