0

I have some HTML as follows:

<td>
    <tr>
        <input type="button" name="confirm" id="confirm1" tabindex="12" size="25"
               value="Confirm" class="inputbox autowidth" title="confirm address" />
    </tr>
</td>

I have a script with the following code:

$("#confirm1").click(function(){…}
$("#confirm2").click(function(){…}

These are very similar except with 1, 2...10 etc... at the end which determines what to do.

How do I write it like:

$("#confirm" + id).click(function(){…}

I want to be able to use the id as a variable and have one function rather than 10 smaller ones.

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Tim
  • 1
  • 1
  • While *possible* using the linked question, it would be better to avoid numeric-indexed IDs entirely - use a CSS selector for the inputs instead instead. Add classes if required. If you need the index, either calculate it inside the function, or use a data attribute – CertainPerformance Mar 10 '20 at 08:40
  • you can have a single function that will be called on 'onclick' for each button. where you can retrieve information e.g. value, id etc about calling button using `event.target` then do stuff. – Muhammad Murad Haider Mar 10 '20 at 08:42

1 Answers1

0

In vanilla Javascript you could do something similar to this:

Array.from(document.querySelectorAll('[type="button"]')).forEach(bttn=>{
    bttn.addEventListener('click',function(e){
        alert(e)
    })
});

This would bind a generic event handler to all buttons matched in the querySelectorAll

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • why convert the result to an actual array using `Array.from` when `NodeList` already implements a `forEach` method according to the documentation? – M0nst3R Mar 10 '20 at 08:46
  • 1
    older browsers, and IE, do not natively offer that so converting to an array mitigates errors.. – Professor Abronsius Mar 10 '20 at 09:01
  • I saw that in the documentation, but it also mentions that these old browsers do not support `Array.from` either, that's why I'm a bit confused. It mentions using `Array.prototype.forEarch` instead. Thoughts? – M0nst3R Mar 10 '20 at 11:01