Matthew Loch
Matthew Loch

Reputation: 59

Javascript code doesn't work when I use onsubmit instead of onclick

var submit = document.getElementById('submit'),
    div = document.getElementById('div');

div.onmouseover = function sum() {
    value1 = document.getElementById('form').value;
    value1 = document.getElementById('form2').value;

    sum = value1 + value2;
}

submit.onsubmit = function print() {
    div.innerHTML = sum;
}

For some reason, the code doesn't work; however, if I replace the last with

submit.onclick = function print() {
    div.innerHTML = sum;
}

onclick instead of onsubmit, it works perfectly fine, even though sum was calculated outside and before I press submit. It's as if every variable becomes null when I enter submit even though the variables aren't even stored in the form fields.

Upvotes: 0

Views: 565

Answers (2)

JaredPar
JaredPar

Reputation: 754735

The onsubmit event fires on the form element, not the button. Try moving the onsubmit handler to the form instead

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

The onsubmit event handler must be attached to the form element, not to input element.

Assuming you have a form, you could do

submit.form.onsubmit = ...

Upvotes: 1

Related Questions