0

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.

here is my script:

$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
            if (data.indexOf("noDiary") > -1) {
                document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
            } else {
                var appendedText = '';
                $.each(data, function(){
                    var diaryID = this.diary_id;
                    var dateAdded = this.date;
                    appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
                })
                document.getElementById("diaryList").innerHTML = appendedText;
            }
        })

this is what i use to select:

$(':button.diaries').click(function(){});

but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?

Kelvin
  • 873
  • 2
  • 9
  • 20
  • 1
    You probably want to check out **[Event Delegation](http://learn.jquery.com/events/event-delegation/)** – brbcoding Jan 02 '15 at 16:04
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – alex Jan 02 '15 at 16:06
  • FYI, `data` would be an object as it's automatically parsed by jQuery, and it wouldn't have a `indexOf` method ? – adeneo Jan 02 '15 at 16:06
  • @brbcoding from what I have read, the conclusion is to use on() method right? – Kelvin Jan 02 '15 at 16:24
  • 1
    @alex sorry if the question has been asked already, I tried to searching others, but I cannot find which is relevant. maybe because I didn't really understand the term correctly. – Kelvin Jan 02 '15 at 16:25
  • @adeneo I echoed the "noDiary" instead of the array of objects if the array size is 0. that's why it works. – Kelvin Jan 02 '15 at 16:27
  • @KelvinAliyanto No sweat, I have also been flagged before for not knowing that event delegation exists! :) But yeah, if the `diaries` elements are being *dynamically* generated, click handlers won't work and you're going to have to use event delegation instead. – alex Jan 02 '15 at 16:32
  • @alex but however, it still cannot work :( – Kelvin Jan 02 '15 at 16:43
  • Well, what did you try? Can you post your code? Also, what version of jQuery are you running, and what's the function of ":" in `$(':button.diaries')`? – alex Jan 02 '15 at 16:45
  • I am using 2.1.1.min.js. I have followed the TECHNOMAN's answer and it works, but it alerts 'hi' 3 times. I dunno why. – Kelvin Jan 02 '15 at 17:25
  • I use the same jquery as u said but my alert is coming only once. i m using ur jquery version http://code.jquery.com/jquery-2.1.1.js – TECHNOMAN Jan 03 '15 at 05:57

2 Answers2

0

check your code is after document ready

 $(document).ready(function(){ //your code here });  

and use

$('button.diaries').on(click , function(){}) 

instead of .click

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • yeah, I am using the ready function, but i decided to omit it here. and I have tried using the on click and it also did not work. – Kelvin Jan 02 '15 at 16:10
  • 1
    Previously in older jqueries, this can be done using live function but now because the live function is deprecaated, so "on" will work correctly – TECHNOMAN Jan 02 '15 at 16:11
  • @TECHNOMAN @Mohamed-Yousef i have tried using `$(document).ready(function(){ $(':button.diaries').on("click" , function(){ var x = $(this).attr("value"); localStorage.setItem("diaryID", x); alert("a");; }) })` but they respond only to the dummy button, not the appended button – Kelvin Jan 02 '15 at 16:17
  • @KelvinAliyanto why : before button in selector?? just use $('button.diaries') – Mohamed-Yousef Jan 02 '15 at 16:18
  • @Mohamed-Yousef I tried deleting the :, and still not working – Kelvin Jan 02 '15 at 16:21
  • @KelvinAliyanto Is your code append a paragraph already? your question means that everything is Ok in your code and you just want click event to work.. you need to provide your php code as well – Mohamed-Yousef Jan 02 '15 at 16:33
  • @Mohamed-Yousef yeah It is appended successfully. Everything appears on the page, but nothing is alerted when it is clicked. I don't think there is a problem with the PHP file. – Kelvin Jan 02 '15 at 16:40
  • $('div').on('click', '.diaries', function(event){ Please use this one and let me know – TECHNOMAN Jan 02 '15 at 16:58
0

@Kelvin Aliyanto ....So the solution will be like this

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
        $.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
            if (data.indexOf("noDiary") > -1) {
                document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
            } else {
                var appendedText = '';
                $.each(data, function(){
                    var diaryID = this.diary_id;
                    var dateAdded = this.date;
                    appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
                })
                document.getElementById("diaryList").innerHTML = appendedText;
            }
        });


        $('div').on('click', '.diaries', function(event){
        alert("Hi");
        }) ;

});
</script>   

<div id="diaryList"></div>  
TECHNOMAN
  • 361
  • 1
  • 9