Brent Underwood
Brent Underwood

Reputation: 103

Html button with no defined click event still calls a function

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>

Upvotes: 1

Views: 69

Answers (2)

peterpeakk
peterpeakk

Reputation: 26

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>

Upvotes: 1

Denis Howe
Denis Howe

Reputation: 2411

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?

Upvotes: 0

Related Questions