user3614760
user3614760

Reputation: 9

How to call id of an tag inside the query

I have generated some rows in jquery. I want to call myid from another jquery function. Is this possible. my code is below

<html>
<head><title></title>
<body>
<div id="body"></div>

</body>
</html>
<script>
$(document).ready(function()
{
$("#body").append("<table><tr><td id="myid">Value1</td><tr/></table>");


$("#body").find("#myid").click(function(){
alert("value is clicked");
});
});
</script>

But it is not working. pease anyone help to to solve my issue.

Upvotes: 0

Views: 462

Answers (4)

Atul
Atul

Reputation: 894

You have wrong assignment -

$("#body").append("<table><tr><td id="myid">Value1</td><tr/></table>");

You cannot use " inside another " without using escape character (\) So you write -

$("#body").append("<table><tr><td id='myid'>Value1</td><tr/></table>");

or

$("#body").append("<table><tr><td id=\"myid\">Value1</td><tr/></table>");

Upvotes: 0

Mutahhir
Mutahhir

Reputation: 3832

I think your code looks ok, but you're probably getting an error because you're using double quotes (") within a table html string (which is a double quoted string), so basically:

"this is a "simple" string"
|----------|xxxxxx|-------|

In the above example, simple is not part of the string and is invalid JavaScript syntax. You have two options:

  1. Alternate using " with ', e.g. "this 'is' a valid string" or 'this "is" a valid string' are both valid strings
  2. Escape the double quote character, e.g. "this \"is\" a valid string"

Hope this helps.

Upvotes: 0

nrsharma
nrsharma

Reputation: 2572

Try this

$(document).ready(function()
{
  $("#body").append("<table><tr><td id='myid'>Value1</td><tr/></table>");
});
$("#body").on('click','#myid',function(){
  alert("value is clicked");
});

DEMO

Upvotes: 0

Kiran
Kiran

Reputation: 20303

You should use .on() to attach events to dynamically created elements. Try this:

$("#body").on('click','#myid',function(){
alert("value is clicked");
});

DEMO

Upvotes: 1

Related Questions