Reputation: 23
I wanted to make a checkbox input and when we select it, it gets the number of the first input and reduces it by 10 and when we unselect it the original number of first input prints. for example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()">
<p id="par">hrllo</p>
<script>
function one () {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
if(!event.target.checked){
document.getElementById("par").innerHTML = input;
}
}
</script>
</body>
</html>
Upvotes: 0
Views: 69
Reputation: 187
You can define the id of checkbox element and on the bases of id can check that checkbox is checked or not.
Here is your updated code.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<p id="par">hrllo</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
alert("CheckBox checked.");
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
alert("CheckBox not checked."+document.getElementById("input").value);
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>
Upvotes: 1
Reputation: 8301
You can check the event object to find the value of checkbox. Based on the checkbox value you can add or subtract the value of input element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onChange="one(event)">
<p id="par">hrllo</p>
<script>
function one(event) {
let input = document.getElementById("input").value;
y = event.target.checked ? input - 10 : input;
document.getElementById("par").innerHTML = y;
}
</script>
</body>
</html>
Upvotes: 1