I have a list of buttons in the sidebar and two input fields (number one and number two) in the main container. I need to make sure that when I click on the first (or second, third, etc.) button, the name of this button goes to the main container in the number one input field. Then, when you clicked on the second (or first, or third, etc.) button, the name of this button went to the main container in the input field number two. I think I should do this with an onclick event, but for me the method of implementation doesn't matter much. Below is the code that sends the name of the pressed button only in the first input field (field number one).

Js

function projectClick(index, name) { const nameA = document.getElementById('prjA'); const nameB = document.getElementById('prjB'); nameA.value = name; } 

pug

 mixin projectButton(objectName index) lable input.prjBtn(type="button" value=`${objectKey}` onclick="projectClick('" + index + "','" + objectKey + "')") block append main form.formMod input.form-control#prjA(type="text" name="prjA") input.form-control#prjB(type="text" name="prjB") block append sidebar form.formMod each val, index in projectlist +projectButton(val.objectKey, index) 
  • And if two fields are already filled in, and then click on the 3rd button. What will happen? - Lukas
  • And what's the point in the case of a single handler on several buttons, for example, why not catch an event on the container in which these buttons are located? - Bald
  • bring the codepen link in question with the markup that you have, I will try to help ... - Bald

1 answer 1

This can be done if you loop through the elements and hang the onClick event on them. Like so

 const buttons = document.querySelectorAll('input[type="button"]'); for(let i = 0 ; i < buttons.length ; i++) { const btn = buttons[i]; btn.addEventListener('click' , (e) => projectClick(i , e.target.value)) } 
  • why not use forEach instead of for iteration? - Bald
  • @AlisaBondarchuk working example - Bald