root
root

Reputation: 1583

jquery1.7.2 click event not firing

i'm trying to bind a click event to some div that has a id="unit". Theses div are generate in run-time and my javascript doesn't seems to work.

my javascript click event.

$("#unit").click(function(){
  alert('1');
});

before ajax call.

<div id="content">
    <div id="building">

    </div>

    <div id="units">

    </div>
</div>

after ajax call.

<div id="content">
        <div id="building">
            <div value="1" class="buildingBlock"><h3 style="text-align: center;">Level - 1</h3></div>
            <div value="2" class="buildingBlock"><h3 style="text-align: center;">Level - 2</h3></div>
            <div value="3" class="buildingBlock"><h3 style="text-align: center;">Level - 3</h3></div>
            <div value="4" class="buildingBlock"><h3 style="text-align: center;">Level - 4</h3></div>
        </div>


        <div id="units">
            <div value="1" id="unit">#02-01<br>3 room(s)</div>
            <div value="2" id="unit">#02-02<br>2 room(s)</div>
            <div value="3" id="unit">#02-03<br>5 room(s)</div>
        </div>
    </div>

Upvotes: 2

Views: 253

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

Change id to class of unit

<div id="units">
   <div value="1" class="unit">#02-01<br>3 room(s)</div>
   <div value="2" class="unit">#02-02<br>2 room(s)</div>
   <div value="3" class="unit">#02-03<br>5 room(s)</div>
 </div>

Try with delegate event handler.

$("#units").on('click', '.unit', function(){
  alert('1');
});

Upvotes: 0

jancha
jancha

Reputation: 4967

you cannot have more than one element with same id.

use class instead. e.g. class="unit"

and when you bind on event use $(".unit")..


Also, if we are considering Ajax requests, either in the success method, or in the backend you should prepare extra js code to properly init the new elements. Having event listening on parent is a hack actually.

so, if you have:

$.get("someurl", {}, function(data){
    $("#units").append(data);
    $("#units .unit").unbind("click").bind("click", function(){ 
// your click handler here
    });
});

at least I would go that way unless you have specific need to control event from parent.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Because you are dynamically appending the #unit elements, you need to delegate the event to the nearest parent element. Try this:

$("#units").on('click', '.unit', function(){
    alert('1');
});

Also, multiple id attrbutes are invalid. You should change the code to use classes, like this:

<div id="units">
    <div value="1" class="unit">#02-01<br>3 room(s)</div>
    <div value="2" class="unit">#02-02<br>2 room(s)</div>
    <div value="3" class="unit">#02-03<br>5 room(s)</div>
</div>

Upvotes: 6

Related Questions