1

I have 2 <buttons> in my html code, and one of them has an onclick function, but the other is just a button I haven't defined yet. The weird thing is that the button that hasn't been defined, has the same onclick property as the other. Could someone please explain why this is happening?

Here is a code snippet:

saveRuleSelections: function() {
  let blackjackRules = [];
  let rules = document.getElementsByClassName("rule");
  for (let i = 0; i < rules.length; i++) {
    blackjackRules.push(rules[i].value);
  }
  let jsonBlackjackRules = JSON.stringify(blackjackRules);
  localStorage.setItem("blackjackRules", jsonBlackjackRules);
  document.getElementById("rules_overlay").style.display = "none";
}
<form>
  <p>Surrender Allowed:
    <select class="rule">
      <option value="early">Early</option>
      <option value="late">Late</option>
      <option value="no" selected>No</option>
    </select>
  </p>
  <button id="select_rules_button" onclick="trueCountApp.saveRuleSelections()">Select Rules</button>
  <button>Restore Default</button>
</form>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • What indicates that both buttons fire `saveRuleSelections()`? – showdev May 03 '18 at 16:58
  • @showdev It's part of a longer html document, and when I run it on my browser, clicking the second button(which should do nothing, since I haven't defined an event on it) does the same thing as clicking the first. I can upload my entire code, if that would be helpful. – Brent Underwood May 03 '18 at 17:02
  • a button without an explicit `type=...` inside a form will always act as a submit button, just add `type='button' to both buttons and everything should be fine. – Calvin Nunes May 03 '18 at 17:09
  • I see. It might be helpful to create a [working example](https://stackoverflow.com/help/mcve) to help demonstrate the issue. – showdev May 03 '18 at 17:09

2 Answers2

1

Both forms have the same value of submit since their inside the form with no different value now both will take the same value of submitting the form and therefore firing the function, it's like a clone. Try

<form>
  <p>Surrender Allowed:
    <select class="rule">
      <option value="early">Early</option>
      <option value="late">Late</option>
      <option value="no" selected>No</option>
    </select>
  </p>
  <button id="select_rules_button" onclick="trueCountApp.saveRuleSelections()">Select Rules</button>
  <button type="reset" value="Reset">Restore Default</button>
</form>
peterpeakk
  • 26
  • 1
  • 6
0

Could it be that your second button is just performing its default action? The default action depends on the button's type, which defaults to submit (except in IE).

what's the standard behavior when < button > tag click? will it submit the form?

Denis Howe
  • 2,092
  • 1
  • 23
  • 25