Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second element in each loop returns undefined

Tags:

jquery

From fields with the class .edit-links i´m able to retrieve the values but $(this).next(".edit-url").val(); only returns the first found element then only returns undefined. In the console i can see that "this" is targeting the first element as expected but the second .edit-url is not found and returning prevObject.

$('#edit').click(function() {
  edit.revertLink();
});

var edit = {};
edit.revertLink = function() {

  $('.edit-link').each(function(index) {

    var currentName = $(this).val();
    var url = $(this).attr('data-tempurl');
    var meta = $(this).attr('data-meta');
    //edit.changeLiOrgname(this, currentName);

    if (meta === "external") {
      //url = $(this).next(".edit-url").val();
      currentName = $(this).next(".edit-url").val();
      //edit.changeLiOrgURL(this, url);
      $(".edit-url").remove();
    }

    var linkStr = [
      '<a href="' + url + '" class="aktiv">',
      '' + currentName + '',
      '<span class="type float-r">',
      '' + meta + '',
      '</span>',
      '</a>'
    ];

    $(".removeBtn").remove();
    $(this).replaceWith(linkStr.join(''));

  });
}
<button id="edit">Edit</button>
<li data-identifier="4.3e43f44714869abce3fabc5">
  <input class="edit-link" data-meta="internal" data-tempurl="/internal-page.html" type="text" value="Stöd">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="Link">
  <input class="edit-url" type="text" data-tempurl="www.link.se" value="www.link.se">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="link2">
  <input class="edit-url" type="text" data-tempurl="www.link2.se" value="www.link2.se">
</li>
<li>
  <input class="edit-link" data-meta="external" type="text" value="link3">
  <input class="edit-url" type="text" data-tempurl="www.lin3k.se" value="www.link3.se">
</li>
like image 820
maho Avatar asked Sep 28 '26 02:09

maho


1 Answers

Error here

$(".edit-url").remove();

in this line you remove all element with class edit-url but need remove just one, for current element.

You can change it to

$(this).next(".edit-url").remove();

or, just call it after loop

edit.revertLink = function() {

    $('.edit-link').each(function(index) {
      ...
    });
    $(".edit-url").remove();
}
like image 127
Grundy Avatar answered Sep 29 '26 23:09

Grundy