(Edit : up)
First I'm a JS beginner. I need to make a calcul using both input type number and plus/minus buttons linked to it (to replace spinners on smartphone screens). I precise I can't use JQuery or any other external library.
I face 3 problems :
I've spent hours and hours to try to solve... thanks in advance.
Here is the code :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<style>
.result {
width: 5rem;
height: 2.5rem;
background-color: grey;
}
</style>
</head>
<body>
<form name="myForm">
<div class="result">
<output id="output"></output>
</div>
<div>
<input type="button" value="-" id="decreaseMe">
<input type="number" id="saisie">
<input type="button" value="+" id="increaseMe">
</div>
</form>
<script>
var valeur = 10;
var varSaisie = document.querySelector('#saisie');
var varOutput = document.querySelector('#output');
myForm.addEventListener('input', function () {
decreaseMe.addEventListener('click', function(){
varSaisie.value = --varSaisie.value;
});
increaseMe.addEventListener('click', function(){
if(varSaisie.value === "")
{
varSaisie.value = 0;
}
varSaisie.value = ++varSaisie.value;
});
varOutput.value = parseFloat(varSaisie.value) + parseFloat(valeur);
}, false);
</script>
</body>
</html>
It sounds like something is blocking the click from reaching the plus button. You shouldn't need to focus on it for it to work. it might be behind something. try to move it to be the top element on the page by adding this style to the page:
<style>
#increaseMe {
z-index:99;
}
</style>
Please comment if this fixed this issue.
Finally I've found the solution. I share it in case it's useful for community. Not sure it's best practice but it does the job.
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formulaire avec boutons plus moins</title>
<style>
.result {
width: 5rem;
height: 2.5rem;
background-color: grey;
}
</style>
</head>
<body>
<form name="myForm">
<div class="result">
<output id="output"></output>
</div>
<div>
<input type="button" value="-" id="decreaseMe">
<input class=boxnumber type="number" id="saisie" min="0" max="95" step="1" placeholder="0-95">
<input type="button" value="+" id="increaseMe">
</div>
</form>
<script>
var valeur = 10;
var varSaisie = document.querySelector('#saisie');
var varOutput = document.querySelector('#output');
myForm.addEventListener('input', function(){
myResult();
});
decreaseMe.addEventListener('click', function(){
varSaisie.value = --varSaisie.value;
myResult();
});
increaseMe.addEventListener('click', function(){
varSaisie.value = ++varSaisie.value;
myResult();
});
function myResult() {
varOutput.innerHTML = parseFloat(varSaisie.value) + parseFloat(valeur);
}
</script>
</body>
</html>