Home > Software engineering >  .append keeps appending even though if statement is false
.append keeps appending even though if statement is false

Time:03-30

Not sure why, but when clicking my button, my code keeps appending even though it appears the if statement is false after the first append?

In line 9, I am checking to see if any .tab class has an attr that does not equal my variable sysId. No matter what I do, it keeps appending. I want it to only append once IF a .tab doesn't have an attribute of data-sysid= sysid already in place.

var recordHtml = '<div  data-sysid="">This is a record opened 
from the list.</div>';

// Open Record Tab
$(".tab-content-list-button").click(function () {
  var sysId = $(this).data('sysid');
  var title = $(this).data('title');
  var tabHtml = '<div  data-sysid="'   sysId   '"><div >'   title   '</div><div >X</div></div>';

  if ($('.tab').attr('data-sysid') != sysId) {
    $(".tab-list").append(tabHtml);
  }

  //$(".tab-list").append(tabHtml);

})

Here is my fiddle that shows it working with the HTML & CSS: https://jsfiddle.net/fju60bca/1/

CodePudding user response:

You have many tab elements on the page, so the following statement won't return the attribute you are looking for:

$('.tab').attr('data-sysid')

You need to check each tab element to see if the one you are looking for exists:

let buttonExists = false; 

$("div.tab").each(function(index, tabElem) 
{
    if ($(tabElem).data('sysid') === sysId)
        buttonExists = true; 
});
  

if (!buttonExists) {
    $(".tab-list").append(tabHtml);
}
  • Related