Issue
I am new to JS. I am learning to apply event listeners, node lists but struggling with the JavaScript syntax for this query. I want to extract the innerHTML of each button to their corresponding textbox within the parent div. So if a user clicks button 3 for example, only textbox 3 value should read the innerHTML of button 3. As you can see, the event listener to trigger each button is working but struggling with the textboxes.
let buttoninput = document.querySelectorAll(".buttoninput");
let textbox = document.querySelectorAll(".textbox");
buttoninput.forEach(btnclickevent => {
btnclickevent.addEventListener('click', () => {
textbox.forEach(content => {
content.value = btnclickevent.innerHTML;
});
});
});
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 1</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 2</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 3</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 4</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 5</button>
</div>
I am aware you can create an id for each textbox input and button and create individual rules but I want to avoid that route as this would be a long line of code. Right now the list is 5 but if I duplicated say 10 or 20 times, I would want the syntax to only trigger each parent div content regardless of the number of duplicates.
Any help would be greatly appreciated.
Thank you
Solution
You can find sibling of button by parentNode.children[0] as
btnclickevent.parentNode.children[0].value = btnclickevent.innerHTML;
let buttoninput = document.querySelectorAll(".buttoninput");
let textbox = document.querySelectorAll(".textbox");
buttoninput.forEach(btnclickevent => {
btnclickevent.addEventListener('click', () => {
btnclickevent.parentNode.children[0].value = btnclickevent.innerHTML;
//textbox.forEach(content => {
// content.value = btnclickevent.innerHTML;
//});
});
});
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 1</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 2</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 3</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 4</button>
</div>
<div>
<input type="text" name="" class="textbox" value="">
<button class="buttoninput">Button 5</button>
</div>
Answered By - Hien Nguyen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.