I have been "writing" a game which involves you collecting a resource, you then spend those resources on something which then creates more of that resource (it will be more interesting when i have finished).
Anyway, my question is that i cannot find a way to stop the number of resources from going into a negative value after buying too much of the thing that creates more resources. I need some way of disabling the button.
I would also like to know how to show the number that is a percentage of the total trees:)
To make it easier, here is the code...
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<script>
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}
function plantTree() {
document.getElementById("Seeds").stepDown(10);
document.getElementById("Trees").stepUp(1);
}
function plantTrees10() {
document.getElementById("Seeds").stepDown(100);
document.getElementById("Trees").stepUp(10);
}
</script>
</head>
<body>
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" id="plantTree"
onClick="myTimer = setInterval(collectSeeds, 1000); plantTree();">Plant Tree</button>
<button
onClick="plantTrees10(); myTimer = setInterval(collectSeeds,100);">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" id="Seeds" disabled></input>
<p>Trees
<br/>
<input type="number" id="Trees" disabled></input>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
</body>
</html>
add min and max to the field as explained in the documentation
You likely want to give a message somewhere too.
Lastly clear the interval before using it again - I rewrote the script to be unobtrusive and generic.
var myTimer; // make global in scope
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}
function plantTree(but) {
var nofSeeds = parseInt(but.getAttribute("data-nofseeds"), 10),
availableSeeds = parseInt(document.getElementById("Seeds").value, 10);
if (availableSeeds < nofSeeds) {
console.log(availableSeeds + " not enough, " + nofSeeds + " needed"); // give some message somewhere
return;
}
console.log(nofSeeds)
document.getElementById("Seeds").stepDown(10 * nofSeeds);
document.getElementById("Trees").stepUp(nofSeeds);
}
window.onload = function() {
var plantButtons = document.querySelectorAll(".plantTree");
for (var i = 0; i < plantButtons.length; i++) {
plantButtons[i].onclick = function() {
clearInterval(myTimer); // only have one timer running
myTimer = setInterval(collectSeeds, 1000);
plantTree(this);
}
}
}
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" class="plantTree" data-nofseeds="1">Plant Tree</button>
<button type="button" class="plantTree" data-nofseeds="10">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" min="0" max="1000" id="Seeds" disabled />
</p>
<p>Trees
<br/>
<input type="number" id="Trees" disabled />
</p>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
Just add if it should work just fine...
function plantTree() {
if (document.getElementById("Seeds").value < 10) {
alert("you don't have enough resources")
} else {
document.getElementById("Seeds").stepDown(10);
document.getElementById("Trees").stepUp(1);
}
}
function plantTrees10() {
if (document.getElementById("Seeds").value < 100) {
alert("you don't have enough resources")
} else {
document.getElementById("Seeds").stepDown(100);
document.getElementById("Trees").stepUp(10);
}
}
Related
I am trying to create a loop. so far I can get it to say Hello Tom and just the number. I want to add on a function named addOrderListItems that receives the name and numOfTimes as parameters. Then call the addOrderListItems function from the displayHello function and if the number is even add an !
so if I type name Braden and numOfTimes 8
the output will display a list
1.Hello Braden
2.Hello Braden!
3.Hello Braden
4.Hello Braden!
5.Hello Braden
6.Hello Braden!
7.Hello Braden
8.Hello Braden!
9.Hello Braden
function displayHello() {
let name = document.getElementById("helloNameInput").value,
numOfTimes = document.getElementById("numOfTimesInput").value;
}
function addOrderListItems() {
let numOfTimes = 0;
while (numOfTimes > 0 ) {
document.getElementById("helloNameOutput").innerHTML = "Hello " + name + numOfTimes;
numOfTimes++;
}
}
function clearName() {
document.getElementById("helloNameInput").value = "";
document.getElementById("numOfTimesInput").value = "";
document.getElementById("helloNameOutput").innerText = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript: Looping Structures Assignment</title>
<link href="/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-3">
<h1>JavaScript: Looping Structures Assignment</h1>
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input
type="text"
class="form-control"
name="helloNameInput"
id="helloNameInput"
placeholder="Enter a name"
/>
</div>
<!--Number of Times input-->
<div class="mb-3">
<label for="numOfTimesInput" class="form-label">Number of Times:</label>
<input
type="text"
class="form-control"
name="numOfTimesInput"
id="numOfTimesInput"
placeholder="Enter number"
/>
</div>
<!--Name output-->
<ol id="helloNameOutput"></ol>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();" >
Display Hello!
</button>
<button class="btn btn-danger" id="clearButton" onclick=" clearName();">Clear</button>
</div>
<script src="/script.js"></script>
</body>
</html>
```
You'll probably need a few functions to help you accomplish your goal and keep your code organized. Below I've created an example in a code snippet to demonstrate how the functionality you described can be implemented. I've included lots of comments to explain and help you understand the steps involved.
You can search on MDN and read the JavaScript documentation if there are parts you've never seen or don't yet understand — for example, here are a few links to some of the DOM APIs used:
Document.createElement()
Element.remove()
Node.firstChild
Node.appendChild()
Keep learning, and good luck in your programming!
const nameInput = document.getElementById('helloNameInput');
const qtyInput = document.getElementById('numOfTimesInput');
const btn = document.getElementById('writeGreeting');
const output = document.getElementById('helloNameOutput');
function createGreetingText (name, withExclamationPoint) {
return `Hello ${name}${withExclamationPoint ? '!' : ''}`;
}
function createGreetingListItem (name, withExclamationPoint) {
const listItem = document.createElement('li');
listItem.textContent = createGreetingText(name, withExclamationPoint);
return listItem;
}
function clearOutput () {
// Delete every child element from the output element:
while (output.firstChild) {
output.firstChild.remove();
}
}
function writeGreeting () {
// Get the trimmed input value (or use "world" if it's empty):
const name = nameInput.value.trim() || 'world';
// Get the number of times (quantity) from the other input:
let qty = parseInt(qtyInput.value);
// If the number input value couldn't be parsed as a valid integer,
// use 1 as the default valid value and update the input:
if (!Number.isInteger(qty)) {
qty = 1;
qtyInput.value = 1;
}
clearOutput();
// Loop the number of times:
for (let i = 1; i <= qty; i += 1) {
// Create and append a list item element each time:
const isEven = i % 2 === 0;
const listItem = createGreetingListItem(name, isEven);
output.appendChild(listItem);
}
}
// Bind the "writeGreeting" function to the button's "click" event,
// so that it runs each time the button is clicked:
btn.addEventListener('click', writeGreeting);
#container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1rem;
font-family: sans-serif;
}
button, input {
font-size: 1rem;
padding: 0.5rem;
}
<div id="container">
<input
type="text"
id="helloNameInput"
placeholder="name"
value="Braden"
/>
<input
type="number"
step="1"
min="1"
id="numOfTimesInput"
placeholder="# of times"
value="8"
/>
<button id="writeGreeting">Write greeting</button>
<ol id="helloNameOutput"></ol>
</div>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what the problem is, I am trying to save variables, please help. I am trying to save and load but keep getting the error messages involving my save() function and the button calling it. Please help me with this issue, I have been trying to fix it for about 30 minutes and haven't had any luck.
var money = 50;
var printpower = 0;
var autoclickprice = 50;
var autoclick = 0;
var printpowerprice = 50;
var gems = 0;
var fakegems = 0;
var gemcost = 1000;
var gemgrowercost = 5;
var gemgrower = 0;
var gemsellprice = 1250;
function update() {
document.getElementById('TotalMoney').value = money;
document.getElementById('MoneyPerSecond').value = autoclick;
document.getElementById('MoneyPerClick').value = printpower;
document.getElementById('AutoClickCost').value = autoclickprice;
document.getElementById('PrintPowerCost').value = printpowerprice;
document.getElementById('GemAmount').value = gems;
document.getElementById('GemCost').value = gemcost;
document.getElementById('GemGrowerCost').value = gemgrowercost;
document.getElementById('GemsPerMinute').value = gemgrower;
document.getElementById('GemSellPrice').value = gemsellprice;
document.getElementById('FakeGemAmount').value = fakegems;
}
function add() {
money = money + printpower;
update();
}
function timer() {
money = money + autoclick;
update();
}
function buyautoclick() {
if (money >= autoclickprice) {
money = money - autoclickprice;
autoclickprice = autoclickprice * 2;
autoclick = autoclick + 1;
update();
}
}
function addprintpower() {
if (money >= printpowerprice) {
money = money - printpowerprice;
printpowerprice = printpowerprice * 3;
printpower = printpower + 1;
update();
}
}
function buygems() {
if (money >= 1000) {
money = money - 1000;
gems = gems + 1;
update();
}
}
function buygemgrower() {
if (gems >= gemgrowercost) {
gems = gems - gemgrowercost;
gemgrowercost = gemgrowercost * 2;
gemgrower = gemgrower + 1;
update();
}
}
function gemsperminute() {
fakegems = fakegems + gemgrower;
update();
}
function sellgems() {
if (fakegems >= 1) {
money = money + gemsellprice;
fakegems = fakegems - 1;
}
}
function save() {
localStoarge.setItem("money", "money");
}
function load() {
const data = localStorage.getItem("money");
}
setInterval(timer, 1000);
setInterval(gemsperminute, 60000);
#moneydiv {
width: 225px;
height: 925px;
padding: 10px;
float: left;
background-color: lime;
}
#gemdiv {
width: 225px;
height: 925px;
padding: 10px;
float: right;
background-color: aqua;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css" />
<title>
Money Printer!
</title>
</head>
<body>
<script src="index.js">
//nice try little kid, try agian -_-//
</script>
<div id="container">
<div id="moneydiv" style="text-align: center">
<button onclick="add()">
Print Money
</button>
<button onclick="addprintpower()">
Improve MPC
</button>
<br> Improve Money Per Click Cost:
<br>
<input type="text" id="PrintPowerCost" style disabled>
<br> Money Per Click:
<br>
<input type="text" id="MoneyPerClick" style disabled>
<br>
<br>
<button onclick="buyautoclick()">
Buy Auto Clicker
</button>
<br> Auto Clicker Cost:
<br>
<input type="text" id="AutoClickCost" style disabled>
<br> Money Per Second:
<br>
<input type='text' id="MoneyPerSecond" style disabled>
<br>
<br> Total Cash:
<br>
<input type="text" id="TotalMoney" style disabled>
<br>
<br>
</div>
<div id="gemdiv" style="text-align: center">
<button onclick="buygems()">
Buy Gems!
</button>
<br> Gem Cost:
<br>
<input type="text" id="GemCost" style disabled>
<br>
<br>
<button onclick="buygemgrower()">
Buy Gem Grower
</button>
<br> Gem Grower Cost(In Gems):
<br>
<input type="text" id="GemGrowerCost" style disabled>
<br> Gems Per Minute:
<br>
<input type="text" id="GemsPerMinute" style disabled>
<br> Total Gems:
<br>
<input type="text" id="GemAmount" style disabled>
<br> Total Fake Gems:
<br>
<input type="text" id="FakeGemAmount" style disabled>
<br>
<br>
<button onclick="sellgems()">
Sell Fake Gems!
</button>
<br> Sell Price:
<br>
<input type="text" id="GemSellPrice" style disabled>
</div>
<div id="saveloaddiv" style="text-align: center;">
<button onclick="save()">
Save
</button>
<button onclick="load()">
Load
</button>
</div>
</div>
</body>
</html>
It's a typographical error, you wrote "stoarge" instead of "storage" while defining the save function
I have a form. Here in the submit button which is disabled, I have made the following function that when balance value will be greater than 10, it will remove its disabled function. My script is not working. Is there any way to remove the disabled function of submit button, when balance value will be greater than 10?
<script >
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.add_form.obalance.value;
two = document.add_form.debit.value;
document.add_form.balance.value = (one * 1) - (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script>
My html form:
<html>
<form name="add_form" action="ebill.php" method="post" >
<input type="text" name="obalance" id="obal" value="" onFocus="startCalc();"
onBlur="stopCalc();" >
<input type="text" name="debit" id="totl" value="" onFocus="startCalc();"
onBlur="stopCalc();" />
<input type="text" name="balance" id="totl" value="" />
<input type="submit" id="submit" name="submit" disabled="disabled" />
</html>
Script to remove disabled attribute of Submit button:
<script >
setInterval(function () {
if ($('#balance').val() >= 10){
$(":submit").removeAttr("disabled");
}
else{
$(":submit").attr("disabled", "disabled");
alert('Your Balance is less than 10');
}
}, 1);
</script>
(comments in the code itself — you'll also find below your code some "best practice advices" to avoid a lot of headhaches ;))
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.add_form.obalance.value;
two = document.add_form.debit.value;
document.add_form.balance.value = (one * 1) - (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
setInterval(function () {
/*************************************
v----------- ID error (fixed) */
if ($('#tot2').val() >= 10){
$(":submit").removeAttr("disabled");
}
else{
$(":submit").attr("disabled", "disabled");
// alert('Your Balance is less than 10');
}
}, 10); // 1 is too much?
input#submit[disabled] {
background-color: red; color: white; opacity:.2;
}
input#submit:not(disabled) {
background-color: green; color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="add_form" action="ebill.php" method="post" >
<input type="text" name="obalance" id="obal" value="" onFocus="startCalc();"
onBlur="stopCalc();" >
<input type="text" name="debit" id="tot1" value="" onFocus="startCalc();" onBlur="stopCalc();" />
<!-- ID error (fixed) -------------^ -->
<input type="text" name="balance" id="tot2" value="" /> <!--
<!-- ID error (fixed) -------------^ -->
<input type="submit" id="submit" name="submit" disabled="disabled" />
By the way, you should use jQuery or not. The use of jQuery for a bunch of code and pure DOM for another is REALLY errors prone.
In your code above for instance, document.add_form.balance and $('#tot2') address the same DOM Element, but their names are fully different, with no reason.
Hard to read, hard to debug, errors prone.
If your code works after document is ready, you should for example put your fields in variables with self-explanatory names:
let balanceField /* or whatever name you want */ = $('#balance') ;
let debitField = $('#debit') ;
let totalField = $('#total') ;
Then, in your code, you use these variables instead of hard value:
let one = balanceField.val() || 0 ;
let two = debitField.val() || 0 ;
totalField.val( one + two ) ;
Or, shorter, still readable and expressive (but only if you don't need the one and two values further):
totalField.val( (balanceField.val()||0) + (debitField.val()||0) ) ;
and further:
if ( debitField.val() > 9 ) { ... }
What this program its supposed to do is first with a range input you put how many elements you want to guess then it will show a random element form a json list and you have to guess the valnce and then it will load annother one and you continue. OK when i run this code everything is normal until you click submit button two times. When i click the submit botton the first time its goes well but the second time the program runs the if in the line 41 but it also runs the code in the else and if you submit more times it will run the alerts more and more times.
I have tried doing it other ways like just putting all into a for but it still runing code i dont want to.
const $ = require('jquery');
let elementoActual;
let valorPositivoCorrecto;
let valorNegativoCorrecto;
let valorCuadroNegativo;
let valorCuadroPositivo;
// Button on click add the element
$(document).ready(function() {
$("#startButton").click(function() {
$(".hide").hide();
let questionHTML = '<div class="elementoQuimico"><img id="imgElemnt" src="" alt=""></div>' +
'<div class="valenciasElemento">' +
'<input type="text" class="valorPositivo" placeholder="Valencias positivas">' +
'<input type="text" class="valorNegativo" placeholder="Valencias negativas">' +
'</div>' +
'<button class="submitButtonElement">SUBMIT</button>';
$(".questions").append(questionHTML);
putAnElement();
}); //onclick ends
}) //ready ends
function putAnElement() {
let numb = $("#textInput").val();
let counter = 0;
$.getJSON("../../json/valencias.json", function(data) {
let numeroDeElemento = Math.floor(Math.random() * 3);
elementoActual = data[numeroDeElemento];
valorNegativoCorrecto = data[numeroDeElemento].valenciasNegativas;
valorPositivoCorrecto = data[numeroDeElemento].valenciasPositivas;
//$("#imgElemnt").attr( "src" , elementoActual.img);
$("#imgElemnt").attr("alt", elementoActual.name);
$("#imgElemnt").attr("width", "200px");
$("#imgElemnt").attr("height", "200px");
alert(numb);
$(".submitButtonElement").click(function() {
valorCuadroNegativo = $(".valorNegativo").val();
valorCuadroPositivo = $(".valorPositivo").val();
$(".valorNegativo").val("");
$(".valorPositivo").val("");
if (valorCuadroNegativo === valorNegativoCorrecto &&
valorCuadroPositivo === valorPositivoCorrecto) {
alert("correcto");
counter++;
alert(counter);
if (counter != numb){
putAnElement();
} else {
alert("ya");
}
} else {
alert("incorrecto");
counter++;
alert(counter);
if (counter != numb) {
putAnElement();
} else {
alert("ya");
}
}
});
}); //getJSON ends
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tabla periodica</title>
<link rel="stylesheet" href="../../css/periodic-table.css">
</head>
<body>
<div class="wrapper">
<div class="hide">
<h1>TABLA PERIODICA</h1>
<img src="../../img/tabla-valencias.png">
<div class="buttons">
<button id="startButton">EMPEZAR</button>
<form id="submit-tabla">
<label for="rangeInput"></label><input type="range" name="amountRange" id="rangeInput" min="10" max="30" value="20" oninput="this.form.amountInput.value=this.value" />
<label for="textInput"></label><input type="number" name="amountInput" id="textInput" min="10" max="30" value="20" oninput="this.form.amountRange.value=this.value" />
</form>
</div>
</div>
<div class="questions">
</div>
</div>
<footer>
2017 © Nestor and Diego
</footer>
<script src="chemistry.js"></script>
</body>
</html>
And here is the json
[
{
"name":"hidrogeno",
"valenciasNegativas":"-1",
"valenciasPositivas":"1",
"img":"img/Hidrogeno.svg"
},
{
"name":"litio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Litio.svg"
},
{
"name":"sodio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Sodio.svg"
}
]
I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<script type="text/javascript">
var x = 0
document.write(x)
function button1() {
document.write(x++)
}
function button2(){
document.write(x--)
}
</script>
</body>
The problem is that you put ++ and -- after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.
Also, as mentioned, you have some trouble with document.write(). Consider the following documentation from the W3Schools page:
The write() method writes HTML expressions or JavaScript code to a
document.
The write() method is mostly used for testing. If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Thus, document.write() will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML like this:
var x = 0;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
Why don't you change your code a bit? Instead of document.write(x++) and document.write(x--) use document.write(++x) and document.write(--x).
The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.
Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.
Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.
document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.
Moreover, use addEventListener instead of inline event listeners:
var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function () {
// this function is executed whenever the user clicks the increment button
span.textContent = x++;
});
decrement.addEventListener('click', function () {
// this function is executed whenever the user clicks the decrement button
span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.
document write will delete full html:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
As in w3schools
try this instead
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<div id="value"></div>
<script type="text/javascript">
var x=0
var element = document.getElementById("value");
element.innerHTML = x;
function button1(){
element.innerHTML = ++x;
}
function button2(){
element.innerHTML = --x;
}
</script>
I changed the x-- and x++ to ++x and --x so the changes are immediatly. With this change your code would have worked aswell. showing 1 or -1.
HTML code for UI
<div class="card">
<div class="card-body">
<h5 class="card-title">How many guests can stay?</h5>
<div class="row">
<ul class="guestCounter">
<li data-btn-type="increment"><span class="romoveBtn"><i class="fa fa-plus"></i></span> </li>
<li class="counterText"><input type="text" name="guestCount" id="btnGuestCount" value="1" disabled /> </li>
<li data-btn-type="decrement"><span class="romoveBtn"><i class="fa fa-minus"></i></span></li>
</ul>
</div>
Java Script:
// set event for guest counter
$(".guestCounter li").on("click", function (element) {
var operationType = $(this).attr("data-btn-type");
//console.log(operationType);
var oldValue = $(this).parent().find("input").val();
//console.log(oldValue);
let newVal;
if (operationType == "increment") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$(this).parent().find("input").val(newVal);
});
var x = 1;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
if(x <= 0 ){
alert(' minimum value 0 // By Khaydarov Marufjon marvell_it academy uzb ')
return false ;
}
document.getElementById('output-area').innerHTML = --x;
}
input{
width: 70px;
background-color: transparent;
padding: 20px;
text-align: center;
}
button{
padding: 20px;
}
<input type='button' value="plus" onclick="button1()" />
<span id="output-area"></span>
<input type='button' value="minus" onclick="button2()" />
This question is very common. I have developed a solution with Bootstrap and pure JavaScript in another very similar thread here.
There is autoincrement input on keeping button pressed down.
Use ontouchstart and ontouchend instead than onmousedown and onmouseup method for mobile. To make it work for both mobile and desktop browser without headache use onpointerdown, onpointerup, onpointerleave
https://stackoverflow.com/a/70957862/13795525
function imposeMinMax(el) {
if (el.value != '') {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
var index = 0;
var interval;
var timeout;
var stopFlag=false;
function clearAll(){
clearTimeout(timeout);
clearInterval(interval);
}
function modIn(el) {
var inId = el.id;
if (inId.charAt(0) == 'p') {
var targetId = inId.charAt(2);
var maxValue = Number(document.getElementById(targetId).max);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue < maxValue){
stopFlag=false;
document.getElementById(targetId).value++;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index+1 >= maxValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value++;
}
index++;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
if (inId.charAt(0) == 'm') {
var targetId = inId.charAt(2);
var minValue = Number(document.getElementById(targetId).min);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue > minValue){
stopFlag=false;
document.getElementById(targetId).value--;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index-1 <= minValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value--;
}
index--;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Button example</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<button type='button' class='btn btn-danger btn-sm ' id='mbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='A' onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='B' onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='C' onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
</body>
</html>