user2896120
user2896120

Reputation: 3282

Organizing multiple onChange events

I have 8 forms on the page. Each form changes the values of its corresponding graph without refreshing the page. However, I'd like to make it so that I don't have to hit the submit button in order to change the graphs. I have 3 form elements for each form. This means that I need 3 onChange events for every form. I would need 24 onChange events for the whole page. Each onChange event calls a unique function only to that graph. So inside each onChange event is a unique function with the parameters supplied by the onChange event.

What i'd like to know is that is there a way to reduce the number of onChange events? Writing out 24 events makes me wonder if there is a simpler way of doing it. Is there?

Upvotes: 0

Views: 1749

Answers (2)

Lars-Kristian Johansen
Lars-Kristian Johansen

Reputation: 160

Just for fun here is another way to improve the solution.

First every form gets an Id. Then inside the event handler you could get that id by doing this.parentNode.id. Now the input element do not need to know what form it should update.

And at last you could add the event handler to the input elements by query them and use addEventListener

var q = document.querySelectorAll.bind(document);

function updateForm(id) {
  console.log(id);
  document.getElementById('output').textContent = "Change detected in Form: " + id;
}

function onChangeEvent(event) {
  updateForm(this.parentNode.id);
}

var allInputs = q('form input');
allInputs.forEach(function(element) {
  element.addEventListener('change', onChangeEvent);
});
<form id="1">
  <label>Form 1</label><br>
  <input type="text">
  <input type="text">
</form>
<br>
<form id="2">
  <label>Form 2</label><br>
  <input type="text">
  <input type="text">
</form>
<br>
<form id="3">
  <label>Form 3</label><br>
  <input type="text">
  <input type="text">
</form>
<br>
<div id="output"></div>

Upvotes: 0

Lars-Kristian Johansen
Lars-Kristian Johansen

Reputation: 160

You only need 1 eventHandler, and you can send in different ids that you check for. Something like this.

function onChangeInput(id) {
  switch (id) {
    case 1:
      console.log('Update form 1');
      break;

    case 2:
      console.log('Update form 2');
      break;
  }
}
<form>
  <label>Form 1</label><br>
  <input type="text" onchange="onChangeInput(1)">
  <input type="text" onchange="onChangeInput(1)">
</form>

<form>
  <label>Form 2</label><br>
  <input type="text" onchange="onChangeInput(2)">
  <input type="text" onchange="onChangeInput(2)">
</form>

Upvotes: 2

Related Questions