lundi 27 juin 2016

Single form button incorrectly triggering two event listeners and alert boxes

Originally I had multiple buttons set up as follows:

<button id="plus" type="button" onclick=assignVarAddition()>+</button>
<button id="minus"  type="button" onclick=assignVarSubtraction()>-</button>

These buttons linked to individual javascript functions where the variables firstNumb and secondNumb are generated from form inputs. With each button linked to it's own function the alert() would only be called once with the result of the sum. Functions as below

function assignVarAddition() {
var firstNumb = +document.getElementById("Numb1").value;
var secondNumb = +document.getElementById("Numb2").value;
var total = firstNumb + secondNumb;
alert("You added " + firstNumb + " and " + secondNumb +  ". The total of these two numbers is " + total);
}

function assignVarSubtraction() {
var firstNumb = +document.getElementById("Numb1").value;
var secondNumb = +document.getElementById("Numb2").value;
var total = firstNumb - secondNumb;
alert("You subtracted " + secondNumb + " from " +  firstNumb + " and got " + total);
}

I'm trying to clean and shorten the js into one functio so now I am trying to use event listeners within one function where a separate event event listener with a separate alert() is set up for the click of each button. But when I click one, both alerts are triggered, addition then subtraction, with the totals displaying in separate alert boxes, one after the other. Now the buttons and functions are set up as:

<button id="plus" type="button" onclick=assignVarAddition()>+</button>
<button id="minus"  type="button" onclick=assignVarSubtraction()>-</button>

function assignVarCalc() {
var firstNumb = +document.getElementById("Numb1").value;
var secondNumb = +document.getElementById("Numb2").value;
document.getElementById("plus").addEventListener("click", alert(firstNumb+secondNumb));
document.getElementById("minus").addEventListener("click", alert(firstNumb-secondNumb));
}

What do I need to do to stop both alerts being called simultaneously - so that when the '+' button is pressed, only the addition of Numb1 and Numb2 are displayed in the alert box? Not the addition value, then the subtraction in it's own alert.

Please note I have separate files for set for the html and javascript and have tags set up in the html file.

Aucun commentaire:

Enregistrer un commentaire