Gagan93
Gagan93

Reputation: 1876

Element not reacting to JQuery Click

I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under

    echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";

Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code

$('.b_ui').click(function()
{
    cls = $(this).attr('class');
    alert('no. '+cls);
}

It shows only first class (GUI) and not the other which I want to use for handling click. Any help ?

Upvotes: 1

Views: 68

Answers (3)

j08691
j08691

Reputation: 208002

Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>

Upvotes: 1

Developer
Developer

Reputation: 610

You should use "on" method:

$(document).on('click', '.b_ui', function() { 
   cls = $(this).attr('class');
   alert('no. '+cls);
});

Upvotes: 1

When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:

<div id="div"></div>

and you add some content with jQuery so it now looks like this:

<div id="div"><span id="span"></span></div>

you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:

$('#id').on('click','span',function(){});

Upvotes: 0

Related Questions