/    Sign up×
Community /Pin to ProfileBookmark

how to add events dynamically using jquery

in my project i m creating html DOM elements dynamically using JQUERY.
All the data that required for creating are in JSON structure.
eg:

[CODE]
[
{
“node”: “INPUT”,
“id”: “BTN”,
“onclick”: “alert(“hi”)”,
“type”: “button”
}
] [/CODE]

so whatever passing to the function as event name should be add to the element.

I tried to add events to the HTML DOM variable as shown below

[CODE]
jQuery(DOMelem).bind(“onclick”, alert(hi)); [/CODE]

DOMelem is the HTML element that created dynamically using jquery. i need to bind the events to this.

but im getting error while executing this.

[CODE]
<TR id=1x1x1x1x1 jQuery171010988482103845665=”1″></TR>[/CODE]

any idea why it happens?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@GalwayMar 21.2012 — "Hi" needs to be in quotes in your alert for starters.
Copy linkTweet thisAlerts:
@DanInMAMar 21.2012 — please show an example of the DOMelem variable.

Also where are you using the json data in this example?

- and What error are you getting? you have shown an empty row element, but no errors.
Copy linkTweet thisAlerts:
@ammuhereauthorMar 22.2012 — [CODE]var jsonData = [{
"node": "INPUT",
"id": "1x1x1",
"onclick": "alert('hi')",
"type":"button"

}];
function test(tmp)
{
alert(tmp)
}
DOMelem = document.createElement(jsonData[0].node);
jQuery(DOMelem).attr("type",jsonData[0].type);
jQuery(DOMelem).attr("id",jsonData[0].id);
$("body").append(DOMelem );
$("#" + DOMelem.id).bind("click",test(1));
[/CODE]


this is a sample code.

i dont know how to attach event to a dynamically created element.

so in my code in the page load itself the function test will called but not while clicked on the button.
×

Success!

Help @ammuhere spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...