macieira
macieira

Reputation: 359

Event run only once

I have a script that when is clicked, it runs a function with an ajax request.

jQuery('.go').on('click', function(){ 
    id = "";
    id = $(this).parent().parent().find("input").val();             
    request_event("go",id);
    });
jQuery('.noGo').on('click', function(){ 
    id = "";
    id = $(this).parent().parent().find("input").val();             
    request_event("noGo",id);
});

After run the ajax, the value in the div (that div that contain the span value) is changed.

 switch(operation){
    case "go":  
       jQuery('.eventBox input[value="'+id+'"]').parent().find("#confirmBox").html("<span class='noGo cursorIcon'>N&atilde;o Confirmar</span>");
                
break;
case "noGo":
    jQuery('.eventBox input[value="'+id+'"]').parent().find("#confirmBox").html("<span class='go cursorIcon'>Confirmar</span>");

                    
break;
  }

The problem is that in all new "links", the on click event is not triggered.

Can anyone tell me?

Upvotes: 0

Views: 114

Answers (3)

palaѕн
palaѕн

Reputation: 73896

For all the new links, you need to do this:

jQuery(document).one('click', '.go', function () {
    id = "";
    id = $(this).parent().parent().find("input").val();
    request_event("go", id);
});

Upvotes: 1

Anton
Anton

Reputation: 32581

Use .on() on the closest static element or the document like this for newly created elements

jQuery(document).on('click','.go', function(){

Upvotes: 3

Paras
Paras

Reputation: 3067

Seems like to get "on" event register for dynamic elements, the implementation needs to be a bit different like this

$(document).on("click",".go",function(){
    alert("hello");
    $('#divTest').append("<span class='go'>dynamic span</span>");
});

Check this in this fiddle

Upvotes: 0

Related Questions