0

I am trying to check for activity on any of some specific ID attributes on my webpage with JavaScript, and if they are activated, I want to execute some code. The code is working for a single attribute with document.querySelector but not for document.querySelectorAll.

I have tried the solutions posted here but without success, as I run into the following error:

Uncaught ReferenceError: Invalid left-hand side in assignment

My code is simple:

document.addEventListener('DOMContentLoaded', function(){
    Array.from(document.querySelectorAll("#id_types, #id_cons_1")).forEach(button=>button.click()) = function() { 
        document.querySelector("#id_new_name").value= some_value_to_be_assigned
    }})

What am I doing wrong?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Rivered
  • 741
  • 7
  • 27

1 Answers1

0

There's no need for the DOMContentLoaded event handler, just put a script with the following at the end of the body (just before the closing body tag).

There is also no need for Array.from since forEach is supported on the node list returned from querySelectorAll().

Then, you need to set up a click event for each button as shown below (button.click() = function...., doesn't set up an event handler, it invokes a click event).

document.querySelectorAll("#id_types, #id_cons_1").forEach(function(button) { 
  button.addEventListener("click", function(event){
    document.querySelector("#id_new_name").textContent = "some_value_to_be_assigned";
  });
});
<button type="button" id="id_types">button</button>
<button type="button" id="id_cons_1">button</button>
<div id="id_new_name">some value</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Thank you for your assistance. I get prompted: ```(parameter) event: Event 'event' is declared but its value is never read.ts(6133)``` with your code. In addition I cannot use for example type="button". ID attributes of interest do not have common classes or types and are generated automatically in Django by ModelForms – Rivered Oct 28 '22 at 18:21
  • @Rivered Your question is not tagged and doesn't mention anything about Django. As you can see, the code works just fine here and is correct. You must have other problems. – Scott Marcus Oct 29 '22 at 02:07