0

i've a modal. On Click i load some elements into a ul-list to the content of the modal.

This function is called over the class "modaldata", for my later generated elements, this function do nothing and i dont know why?

Thats the function inside the mainpage

    $(".modaldata").on("click",function(){ 
alert("klick"); 
   var modalid = $(this)[0].getAttribute("data-modalid"); 
   var ds = $(this)[0].getAttribute("data-ds"); 
   var step = $(this)[0].getAttribute("data-step");  
   $.ajax({
         type: "POST",
         url: "'.$global['serverurl'].'/system/modalcontent.php",
         data: { modalid : modalid, ds : ds, step: step },
         success: function(result){
             var res = $.parseJSON(result);
             eval(res.js)},
         error: function(){
               alert("failure:"+res.msg);
         }
    });
});

That the part from the modal modalcontent.php It will display correctly but the function wont work again if i click at the <span class="modaldata" part

 ... $cont.='<li class="list-group-item li_'.$e['DS'].'"> <span class="modaldata" data-id="'.$e['DS'].'" data-step="edit" data-modalid="rollenverw"><i class="fa fa-wrench"></i> '.$e['ROLE_BEZ'].'</span><span class="badge badge-success"> '.$tmp['count'].' </span>'.$tmp['del'].'</li>';
    } 
    $res['js'].='$("#ex_roles_div ul").append("'. preg_replace( '/\r|\n/', '', addslashes($cont) ).'");';

echo json_encode($res);

Call up the modal and first call of the function

<a href="#" class="modaldata" data-ds="'.$e2['DS'].'" data-modalid="changerole" data-target="#modal_changerole" data-toggle="modal">'.GloFu_get_rolename($e2['USER_HOME'],$e2['ROLE']).'</a>
newbieRB
  • 137
  • 1
  • 14

1 Answers1

1

You need to bind the click a bit different for dinamically added elements(event delegation):

$(document).on("click", ".modaldata", function() {
  alert("klick");
  var modalid = $(this)[0].getAttribute("data-modalid");
  var ds = $(this)[0].getAttribute("data-ds");
  var step = $(this)[0].getAttribute("data-step");
  $.ajax({
    type: "POST",
    url: "'.$global['serverurl'].'/system/modalcontent.php",
    data: {
      modalid: modalid,
      ds: ds,
      step: step
    },
    success: function(result) {
      var res = $.parseJSON(result);
      eval(res.js)
    },
    error: function() {
      alert("failure:" + res.msg);
    }
  });
});

You can read more about this here.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
  • oh, it seems that "$(document).on("click", ".modaldata"," this was the important differece, but i dont really understand the difference between my first code... – newbieRB Mar 02 '17 at 10:05
  • @newbieRB, the change is from `$(".modaldata").on("click",function(){ ` to `$(document).on("click", ".modaldata", function() {`. I've also posted a link in my answer where you can read more about event delegation. I hope it helps you. – Ionut Necula Mar 02 '17 at 10:06