0

I can't figure out why am I getting undefined when trying to console.outthe iUsedId variable from the code below.

Here I attatch the user id to data-iUserId.

var aUsers = [];            
            for( var i = 0; i < aUsers.length; i++ ){
                $("#lblUsers").append('<tr><th scope="row">'+aUsers[i].id+'</th><td>'+aUsers[i].username+'</td><td>'+aUsers[i].firstName+'</td><td>'+aUsers[i].lastName+'</td><td>'+aUsers[i].email+'</td><td>'+"<span data-iUserId='"+aUsers[i].id+"'</span><input type='checkbox' id='chk_"+i+"'"+'</td></tr>');
            }

And here I am trying to use the data from the data attribute, but in the console all I get is undefined.

$(document).ready(function() {
    $("#remove").on("click", function() {
        $('input:checked').each(function() {
            $(this).closest('tr').remove();
            var iUserId = $(this).attr('data-iUserId');
            console.log(iUserId);
            for (var i = 0; i < aUsers.length; i++) {
                if (iUserId == aUsers[i].iUsersId) {
                    aUsers.splice(i, 1);
                }
            }
        });
    });

});

Any gueses? Please help!

user1866925
  • 338
  • 2
  • 9
  • 3
    In line $(this).attr('data-iUserId') $(this) refers to $('input:checked') and not to the span you added the data-iUserId attribute to. – pBuch Aug 31 '16 at 16:49
  • Possible duplicate of [jquery get HTML 5 Data Attributes with hyphens and Case Sensitivity](http://stackoverflow.com/questions/22753629/jquery-get-html-5-data-attributes-with-hyphens-and-case-sensitivity) – Endless Aug 31 '16 at 16:50
  • Multiple issues at play here... – Mark Schultheiss Aug 31 '16 at 17:11
  • Well, yes. I am very new to all this. Are there more then the ones mentioned below? – user1866925 Aug 31 '16 at 17:14

3 Answers3

1

The reason is you are looping over the checkboxes and not the span's which have the attribute you are trying to access.

$(this) refers to the checkbox and not the span in the each method you are using:

 $('input:checked').each(function() { 
     // Inside this each statement $(this) refers 
     // to the the current 'input:checked' element being accessed
 });

You should put the data-iUserId attribute on the checkbox since you are accessing that element.

Also! You are missing the closing '>' on the opening span tag:

<span data-iUserId='"+aUsers[i].id+"'</span>
meditari
  • 131
  • 2
  • 7
  • Thanks for the input! Sorry if i ask for too much, but can you suggest how to loop on both of them, so I can get the ids as well? I am kind of new to JS and jquery. – user1866925 Aug 31 '16 at 17:12
  • I am not sure why you need the span tag at all. You are only adding the data-iUserId to the tag but the tag itself is not encapsulating anything. I would think you would want to put the attribute on the input tag and that way you can access the data-iUserId attribute and the id when you iterate using the `$('input:checked').each(function() { console.log($(this).data('iuserid')); console.log($(this).attr('id')); });` – meditari Aug 31 '16 at 17:18
1

You are deleting the parent with the containers, then trying to access the element.

removing the parent should be in the last step:

$(document).ready(function() {
    $("#remove").on("click", function() {
        $('input:checked').each(function() {
            var iUserId = $(this).closest('span').attr('data-iUserId');
            console.log(iUserId);
            for (var i = 0; i < aUsers.length; i++) {
                if (iUserId == aUsers[i].iUsersId) {
                    aUsers.splice(i, 1);
                }
            }
            $(this).closest('tr').remove();
        });
    });

});

Also, consider the comment of @pBuch

Mojtaba
  • 4,852
  • 5
  • 21
  • 38
1
var aUsers = [];
//...somehow populate array...
// We have to assume here that the array got populated 
for (var i = 0; i < aUsers.length; i++) {
  $("#lblUsers").append('<tr><th scope="row">' + aUsers[i].id + '</th><td>' + aUsers[i].username + '</td><td>' + aUsers[i].firstName + '</td><td>' + aUsers[i].lastName + '</td><td>' + aUsers[i].email + '</td><td>' + "<span data-iUserId='" + aUsers[i].id + "'></span><input type='checkbox' id='chk_" + i + "'" + '</td></tr>');
}

$(document).ready(function() {
  $("#remove").on("click", function() {
    $("#lblUsers").find('input[type="checkbox"]:checked').each(function() {
      // fixed to get the element with the data
      var iUserId = $(this).siblings('[data-iUserId]').data('iuserid');
      console.log(iUserId);
      for (var i = 0; i < aUsers.length; i++) {
        // bad practice to use a global aUsers
        if (iUserId == aUsers[i].iUsersId) {
          aUsers.splice(i, 1);
        }
      }
      $(this).closest('tr').remove();
    });
  });
});
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • NOTE: This will fail if there are multiple siblings with the attribute - so do not change that part of the append. – Mark Schultheiss Aug 31 '16 at 17:36
  • NOTE if you use ` – Mark Schultheiss Aug 31 '16 at 17:49
  • There is also the `aUsers[i].id` in the top but `aUsers[i].iUsersId` later...which is inconsistent perhaps? – Mark Schultheiss Aug 31 '16 at 17:54
  • Thanks for your help, really. Unfortunately i still get undefined...I think this might be me is some way. I forgot to paste part of the code here, which might be impotrant for the case :if( localStorage.sUsers ){ var sUsersFromLocalStorage = localStorage.sUsers; aUsers = JSON.parse( sUsersFromLocalStorage ); } – user1866925 Aug 31 '16 at 18:00
  • `localStorage.getItem('sUsers');` perhaps? with assumption you set it with `localStorage.setItem("sUsers", "somestringthing");` Either way, check that for existence prior to use... even if you used `localStorage.sUsers="somestringthing";` which is also valid...https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API – Mark Schultheiss Aug 31 '16 at 18:12