Home > Software engineering >  Change attribute of element when another element is clicked, when there are multiple elements
Change attribute of element when another element is clicked, when there are multiple elements

Time:04-12

I'm trying to disable a textbox when a submit button is clicked - however there are multiple textboxes with submit buttons. The order of the textbox is the same as the order of the button (for example, the 1st button must disable the 1st button).

As such, I've been using the following code:

 window.onload = function() {
    document.querySelectorAll('button')[i].onclick = function fun(i) {
        document.querySelectorAll('input')[i].disabled = true
    }
}

Where i would be the order of the button/textbox.

Thanks in advance for your help.

CodePudding user response:

Try using closest which should work in this case. Also I am not sure about how you iterate through the querySelectAll, but I may just not be aware of the shorthand. Change to:

window.onload = function() {
    const allButtons = document.querySelectorAll('button');
    allButtons.forEach(function(button) {
      button.addEventListener('click', function(e) {
          e.target.closest('input').disabled = true;
      });
});  
  • Related