0

I have jquery event in html, this will be triggered when i press the button from the same html(id of the button is used to trigger jquery). Now I have dynamically created button from javascript(another file) code in the same page. When i press button created from js (with the same id) Jquery is not responding. Please help.

The code looks as below.

$(function() {
$( "#dialog" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "blind",
    duration: 1000
  }
});

$( "#opener" ).click(function() {
  $( "#dialog" ).dialog( "open" );
});
});  

HTML button:

<td width="171" ><div>
 <input type="button" id="opener" value="SelDimn"> </div></td>

JS button:

var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "button";
element5.setAttribute('id', 'opener');
element5.name = 'opener';
element5.value = 'SelDimn';
cell6.appendChild(element5);
Praveen
  • 1
  • 2
  • possible duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – Ram Dec 24 '13 at 15:18
  • 1
    Be careful - it's invalid html to have two elements with the same id. jQuery selectors will always only return the first one found in the DOM. (See http://api.jquery.com/id-selector/) – Scott Mermelstein Dec 24 '13 at 15:19

1 Answers1

2

You need to use event delegation

$(document).on('click', "#opener", function () {
    $("#dialog").dialog("open");
});

Also note that ID of an element must be unique, so if there are more than 1 button with the said ID then that is invalid, so you will need to use class attribute to group the similar buttons

In that case change it to element5.setAttribute('id', 'opener'); to element5.className = 'opener';

then

$(document).on('click', ".opener", function () {
    $("#dialog").dialog("open");
});

Also the dom node creation can be simplified as

var cell6 = row.insertCell(5);
$('<input />', {
    type = 'button',
    'class': 'opener',
    name: 'opener',
    value: 'SelDimn'
}).appendTo(cell6)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531