1

hello everyone I am trying to create 50 buttons all with unique id. I want it so that whenever the user clicks on the button it will send the name of the button (the name is also the button id) of the tech company. So I know which button was press. The code below is what I have tried so far. Much help would be appreciated.

var tech= ["apple","microsoft","google","netflix","sony"];
for (var i = 0; i < tech.length; i++) {
    console.log(tech[i]);
    document.write('<button class = "tech" value = ' +tech[i]+' id =' +tech[i] + ' onclick = "test('+tech[i]+')"> '+tech[i]+'</h1>');

}

function techid(name){
a = document.getElementById(word);

console.log(a.id);
}
dragonn
  • 311
  • 5
  • 20
  • yes is there a way to do it without eventlistener? – dragonn Nov 06 '20 at 00:55
  • https://stackoverflow.com/questions/64538823/disable-selected-and-other-objects-in-javascript – Konjesh Esbrading Nov 06 '20 at 00:57
  • 1
    Why not use an event listener? I think the issue (although you haven't explained what isn't working exactly) is that `document.write` is going to destroy whatever content exists in the document. Use something like `document.body.innerHTML += ...` which should technically work but it's still pretty poor practice. Also, your func should be `test`, not `techid` or vice versa. Using event listeners is the correct way to do it because you don't need to serialize your data into the DOM--the vars exist purely in closures in JS scope, separating UI from data/logic more cleanly. – ggorlen Nov 06 '20 at 00:58
  • 2
    The problem is your code creates `onclick="test(apple)"` as opposed to `onclick="test('apple')"`, so assuming you fix the current errors by renaming your function to `test` and inserting `name` instead of the non-existant `word`, you have accidentally passed the button element to the function, as opposed to the string: https://jsfiddle.net/sc7znoma/ –  Nov 06 '20 at 00:58
  • 1
    Here's a fixed version: https://jsfiddle.net/sc7znoma/1/ –  Nov 06 '20 at 01:02
  • 2
    Reviewers: the question is not really about closures or let vs var; it's about quotes really. It's not a duplicate of the linked question until the code is rewritten to assign an anonymous function as click handler inside the loop. –  Nov 06 '20 at 01:08
  • @ChrisG thanks that's what I was looking for :) – dragonn Nov 06 '20 at 01:12

0 Answers0