0

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?

6
  • 1
    id's are unique. you can not share an id between elements. Commented Mar 11, 2019 at 20:45
  • Is there a way those ids to be incremental with a number like: button 1 id is like1, button2 id is like2, and so on. Then, the JavaScript function can take those ids and do the job? Commented Mar 11, 2019 at 20:48
  • 1
    of course there is. add your number to the id. But I suggest using class' instead. Commented Mar 11, 2019 at 20:50
  • I used a class. it is unliking/liking everything at once. it's not efficient. How it can be done with dynamic ids? Commented Mar 11, 2019 at 21:05
  • select all with your custom class and use that select list perform your actions against. Commented Mar 11, 2019 at 21:08

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

Didnt work. I know the snippet did and this exactly what I want. Is there any libraries I need to include?
I don't. I tried to use in my application, it didn't work. I tried a test separately as the snippet but didnt do the function. Any suggestions?
I can't really help without seeing the application. Try to find the problem step by step: is your javascript loaded ? Then, does the likes constante returns results? Then, is the click event triggered? etc.
I tried it on jsfiddle and it worked. Any suggestions?
Once I remove it, it works but I want it to work with ajax. Any suggestions?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.