Jawad Sleiman
Jawad Sleiman

Reputation: 55

Dynamic button Ids - Javascript

I have a number of buttons generated from a for loop as follows and the id = like:

<button type="submit" id = "like" class="btn btn-custom btn-sm like"><span id="tx-like">Like</span></button>

I have a script that changes the "like" to "unlike" and "unlike" to "like", it gets element by Id:

$( function() {
        $('#like').click( function() {
            var t = $("#tx-like").html();
            if(t == 'Like'){
                $("#tx-like").html("Unlike");
            }else{
                $("#tx-like").html("Like");
            }
        } );
    } );

This is only functional on the first button since it taking the id. How I can get it functional on all buttons that are generated dynamically?

Upvotes: 0

Views: 235

Answers (1)

Quentin
Quentin

Reputation: 3289

As said in comments above, you should not have multiple IDs in the same page. You could use classes instead, but even if it would work, there is a better approach which is to use data-attributes.

// Retrieves all your elements using the `data-like` attribute.
const likes = document.querySelectorAll('[data-like]');

// For each element as `el`
likes.forEach(el => {
  el.addEventListener('click', () => {

    // Get its `data-like` value.
    const { like } = el.dataset;

    // If the value is 'false':
    if (like === 'false') {
      el.innerText = 'Dislike';
      el.dataset.like = 'true';
      return;
    }

    // Else...
    el.innerText = 'Like';
    el.dataset.like = 'false';
  });
});
/* You can easily customize your elements according to their current state. */

.like[data-like="true"] {
  border: solid 1px green;
}

.like[data-like="false"] {
  border: solid 1px red;
}
<!-- Remove duplicate IDs and use `data-like` instead. -->
<button type="submit" class="btn btn-custom btn-sm like" data-like="false">Like</button>
<button type="submit" class="btn btn-custom btn-sm like" data-like="false">Like</button>

Upvotes: 1

Related Questions