I've been searching for a while, and I found that I can send a value from doGet to html created.
But I want to do smth different, I want to have a button and label where where every time I press on that button it increments the label.
something like a counter for pressing that button.
I already has the HTML that renders button and label it's pretty simple
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('stylesheet'); ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LDP Test</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
function incrementCounter() {}
</script>
</head>
<body>
<label> Counter 0 </label>
<button onClick="incrementCounter"> Increment counter</button>
</body>
</html>
I want to link the incrementCounter function to this label, or whatever html element that can be done that whenever the button is pressed it gets incremented and rendered on the screen can someone guide me to go through this ?
CodePudding user response:
You have some errors in your code. Firstly it should be onclick
not onClick
and the function should be called as onclick="incrementCounter()"
.
Secondly, a label should be used with a input, textarea or select element.
Now coming to the code
HTML
<p>Count: <span id="counter">0<span></p>
<button onclick="incrementCounter()">Increment Counter</button>
JS
function incrementCounter() {
const counterElem = document.querySelector('#counter'),
count = counterElem.innerHTML;
counterElem.innerHTML = count 1;
}
What is happening inside the code is I'm selecting the target element where the count would display. Then I'm getting the value of its innerHTML and parsing it as an integer using
before the counterElem.innerHTML
. Then I'm adding 1 to the value and setting it as the innerHTML
CodePudding user response:
Try like following snippet
function incrementCounter() {
document.querySelector('#counter').innerHTML ;
}
<label>Count: <span id="counter">0</span></label>
<button onclick="incrementCounter()">Increment Counter</button>