htmljqueryjquery-load

jquery cannot get button using id selector when use load method


I have a page named loop.php and have two radio buttons A & B, when A is checked then I load a.html and when B is checked load b.html.

loop.php (most important part)

<div>
    <input id="radio_one" type="radio" value="radio_one" />&nbsp;tpl_one&nbsp;
    <input id="radio_two" type="radio" value="radio_two" />&nbsp;tpl_two

    <!--template1-->
    <div id="tpl_one"></div>
    <!-- template 1 end-->

    <!-- template2 -->
    <div id="tpl_two"></div>
    <!--template 2 end-->
</div>

a.html

<div>
    <input type="button" id="tpl_one_btn" name="" value="in tpl one"/>
</div>

b.html

<div>
    <input type="button" id="tpl_two_btn" name="" value="in tpl two"/>
</div>

I am using jquery-1.9, and I can easily implements my requirements. All of the jquery code are in a file whose name is op.js

 $(function(){
   $("#radio_one").click(function(){
       $("#tpl_two").hide();
       $("#tpl_one").show();
       $("#tpl_one").load('a.html');
   });

   $("#radio_two").click(function(){
      $("#tpl_one").hide();
      $("#tpl_two").show();
      $("#tpl_two").load('b.html');
   });
 });

Everything is ok now, I can do almost everything, but things chang bad when I want to work with buttons on a.html & b.html.

In op.js I want to fire an event when I click the button in a.html

$("#tpl_one_btn").click(function(){
    console.log('button in a.html');
});

Nothing happend, that it's to say I don't get the button via button's id $("#tpl_one_btn")

I realized that maybe the problem is because of load method, so I have an experiment, I move the button to loop.php that it is to say, I don't load a button via a jQuery Ajax function. And this time the above code go well.

Why has this happened when I use load method? Why I cannot get the button via jQuery id selector?

If I want to use load method, how can I got the button using jQuery id selector?


Solution

  • You need to use event delegation (as you are adding your button dynamically)

    $(document.body).on('click',"#tpl_one_btn",function(){
        console.log('button in a.html');
    });