0

I wanted to append a new entry after an ajax request. This works perfectly. Unfortunately the design is messed up, and as I inspected my document the html has been loaded perfectly, but e.g. trying to access the data-status attribute of the recently inserted always fails.

What did I do wrong?

$('.newRoomSubmit').click(function(){

                    if($.trim($('.roomName').val()) != "" && $.trim($('.roomDescription').val()) != "" && $.trim($('.building_id').val()) != ""   ){
                        $('#myRoomModal').modal('hide');

                    $.ajax({
                        type : 'POST',
                        url : '@routes.Admin.saveNewRoom()',
                        data : {
                            roomName: $('.roomName').val(), roomDescription: $('.roomDescription').val(), building_id : $('.building_id').val()
                        },
                        success : function(data) {

                         var newReference =  reference.parent().parent().parent().children().eq(1).append(   
                   '<div class="row">'+
      '<div class="col-sm-3 col-xs-6"><b>'+$('.roomName').val()+'</b></div>'+
      '<div class="col-sm-2 col-xs-7 col-sm-offset-7 text-right"> '+
'<button class="btn  btn-sm btn-default editableRoom" data-status="'+parseInt(data,10)+';'+$(".roomName").val()+';'+$(".roomDescription").val()+';" data-toggle="modal" data-target="#roomEditModal"><span class="glyphicon glyphicon-pencil"></span></button>'+
'<button class="btn btn-sm btn-danger removableRoom" data-status="'+parseInt(data,10)+';'+$(".roomName").val()+'" data-toggle="modal" data-target="#confirmRoomDelete"><span class="glyphicon glyphicon-remove"></span></button>'+
      '</div>'+ 
      '</div>');

                        },
                         error : function(err) {

                            alert(err.responseText); 
                            }
                        });
                    } else {
                        alert("Das Formular wurde nicht vollständig ausgefüllt!");
                    }

                });

The design after my insertion looks like this, I added a red box and 2 red lines by way of illustration, just so that you can distinguish the difference: You can clearly see the messed up design

The real problem is, that after my insertion I click on the button with the pencil-glyphicon in the inserted row. As my modal shows up, it doesnt get the data-status of the html as input. But as I inspected that row in my browser, I could clearly see that the data-status has been added correctly to the new row.

This is how it should look (example of one row above). enter image description here

Why does my jquery has problems with it?

The click method of the pencil-icon on the newly inserted row should put the values into my input tags and it looks like this:

$('.editableRoom').click(function(w) {
                   w.preventDefault();
                   var statusCode = $(this).data('status'); 

                   var felder = statusCode.split(';', 3);

                   $('#roomEdit_id').val(felder[0]);
                   $('#roomEditName').val(felder[1]);
                   $('#roomEditDescription').html(felder[2]);


                 $('#editRoomSubmit').click(function(){
                        /** on click wird das modal versteckt und
                        der User bekommt wieder die neugeladene lab Seite zu sehen*/
                        $('#roomEditModal').modal('hide');
                    });
                });

I researched here jQuery can't access append element and here Refresh DOM with jquery after AJAX call but it doesn't seem to relate to my problem.

Thanks in advance :), I would really appreciate your help :)!

Community
  • 1
  • 1
BigPenguin
  • 264
  • 2
  • 17
  • Please explain a bit more when you actually are trying to access the data-status? – Dejan.S Aug 24 '14 at 19:53
  • When I'm clicking on the button with the pencil-icon in the newly inserted row (appended in ajax succes function) of "keine ahnung mehr", a modal comes up which should split the data I placed in 'data-status' and put it into the input fields just like shown in the second picture. – BigPenguin Aug 24 '14 at 19:57
  • 1
    Just to be certain about this: the click should happen on an appended element? Just thinking of possible problem with event-delegation. – matthias_h Aug 24 '14 at 20:02
  • So the "newroomsubmit" adds that row? How does the click method for the penic icon look? – Dejan.S Aug 24 '14 at 20:05
  • I will edit my post so that you can see the click method :) – BigPenguin Aug 24 '14 at 20:08
  • You already tried to add some console-messages in the part of your script that doesn't work? – matthias_h Aug 24 '14 at 20:19
  • Yes I tried that and the funny thing was: It didn't show me any alert on the newly inserted row, but as I clicked on the other rows it always alerted. I think Radu Andreis answer fits my problem, but unfortunately it didnt work, maybe you are right matthias_h and there is a problem with the event delegation. – BigPenguin Aug 24 '14 at 20:31
  • just to be sure: console.log(status); added after the status-declaration really returns the data value..? – matthias_h Aug 24 '14 at 20:35
  • Radu Andreis solution was the right one, I was just unable to amke use of it as i tested it on the wrong click event. Sorry ! Anyway, thank you matthias_h, as you pointed me to the right right direction :)! – BigPenguin Aug 24 '14 at 20:43

1 Answers1

2

Someone said something about event delegation. I suspect that you're doing something along this line:

$('.class').click(function(e){//something here});

Try this:

$(document).on('click','.className',function(e){//do something here});

Explanation (in the rough) - the page you were looking at, btw, had a very good explanation:

What you were doing was directly binding the to the elements present on the page at the time the function was executing - meaning that when the function that bound elements was executing, it was looking at all the elements that you had on the page and binding (associating an event with an action) an event to them. At that point your future element was not in the page hence it had nothing bound to it - it still triggered the event, but it did not have the associacion in place. The other approach was to bind to the root document (though you could bind to any parent element, present in the page, at the time the binding function is executing) and tell it: look, when an event comes along that was triggered by this type of element, do this.

Radu Andrei
  • 1,075
  • 10
  • 19
  • this is exactly what I do, thanks for your answer :) I ve tried your solution, but unfortunately it didn't work for me – BigPenguin Aug 24 '14 at 20:14
  • Don't know why it's not working, but about the delegation, you're binding events in static way, if you will, meaning that when a new element of the same type comes along after the initial bound, you don't have an event bound to it. That's why the answer was about catching events on a higher level. Anyway, i hope it at least pointed you in the right direction. – Radu Andrei Aug 24 '14 at 20:20
  • Sorry man, I rewrote my code but used your answer on a wrong element. Everything works properly now :). I found something that explains the delegation a little, but would it be possible that you explain it one more to me, so I can understand what, the problem was :). Thank you very much again, and all the others that tried to help me :)! http://learn.jquery.com/events/event-delegation/ – BigPenguin Aug 24 '14 at 20:39
  • Edited my answer since there was not enough space here. Hope it helps. – Radu Andrei Aug 24 '14 at 20:53
  • Thank you man, you were really helping me out :)! Have a nice day :)! – BigPenguin Aug 24 '14 at 21:17
  • Thank you very much i googled about it too much. Its working fine – Mohammad H. Jul 11 '18 at 09:00