JavaScript- count how many times button is cliked - javascript

I want to count how many times only 1 specified button is clicked.
In my code I have 8 buttons and in p element is shown the number every time I click any other button.
http://prntscr.com/jg26mk
Can you please help me with this?

You can assign an ID to the specified button, then in jQuery use $('#id') instead of $('button')

May be this is what you are looking for.
var count=0;
$(".mySpecialButtons").click(function (){ count++; });
// call this function to show click counts!
function showClicks(){
alert(count);
}

Easiest way:
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = count++;
}
</script>
Example

You can iterate each button, create counter variable that can only be accessible by the button and increment it on click.
$('button').each( function(){
var counter = 0;
$( this ).click( function(){
counter++;
alert( this.innerText + ' has been clicked ' + counter + ' times' );
} );
} )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button A</button>
<button>Button B</button>
<button>Button C</button>

Give your special button an id and use it on click event. Like this:
var count = 0;
$("button#special").on('click', function() {
count ++;
$("p").text(count);
});
$("p").text(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Send</button>
<button id="special">Click Me to count</button>
<br />
<button>Send</button>
<button>Click</button>
<br />
<button>Send</button>
<button>Click</button>
<br />
<button>Send</button>
<button>Click</button>
<br />
<p></p>

try this
<button type="button" id="SomeID">Countable button</button>
<button type="button" >Unountable button</button>
<button type="button" >Unountable button</button>
<script>
var count = 0;
$('body').on('click', '#SomeID', function () {
count++;
$("p").text("Number of Count is " + count)
});
</script>

A closure should do the trick, as described in this article. So, there is no need to define a global variable to count clicks and pollute the global namespace.
element.onclick = (function outer() {
let counter = 0;
return function inner() {
counter++;
console.log('ID:' + element.id + 'Number of clicks: ' + counter);
};
})();
The counter variable will be unique for every button, so you will have information for each button how many times it was clicked.

Related

How do I properly set link variables in javascript?

I have 4 buttons which create a text output, so that a "Go" button goes to the link given in that text output.
I'm still a javascript noob and am thinking in other languages, but is there a way to make .innertext into a variable based on last button pressed? This is the best logic I've come up with, and would like to make it more efficient code.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<h1 id="changedText">Button changes this text</h1>
<button onclick="btn1()">Button1</button>
<button onclick="btn2()">Button2</button>
<button onclick="btn3()">Button3</button>
<button onclick="btn4()">Button4</button>
<br>
<button onclick="Go()">Go to Link Above</button>
<script>
function btn1() {
document.getElementById("changedText").innerText = "http://www.test-
button-1.com";
}
function btn2() {
document.getElementById("changedText").innerText = "http://www.test-
button-2.com";
}
function btn3() {
document.getElementById("changedText").innerText = "http://www.test-
button-3.com";
}
function btn4() {
document.getElementById("changedText").innerText = "http://www.test-
button-4.com";
}
</script>
As you can see my code is really dirty, and doesn't "Go" to the link, what am I missing?
Just single click handle that.No need to define 4 function.
$("button").on("click", function() {
var siteId = $(this).text().slice(-1);
var url = "http://www.test-button-#.com";
if (!isNaN(siteId)) {
url = url.replace(/#/gi, siteId);
$(this).text(url);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button1</button>
<button>Button2</button>
<button>Button3</button>
<button>Button4</button>
I think you can try using input tag and whenever click on a button, you assign the value properties to a global variable.
Then, "Go" function will change your text as:
function Go(){
document.getElementById("changedText").innerText = `http://www.test-${globalVariable}.com`;
}
$("button").on("click", function() {
var url = $(this).data("url");
$("#changedText").text(url);
$("#goButton").data("url", url)
});
$("#goButton").click(function() {
window.location.href = $(this).data("url");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="changedText">Button changes this text</h1>
<button data-url="http://www.test-button-1.com">Button1</button>
<button data-url="http://www.test-button-2.com">Button2</button>
<button data-url="http://www.test-button-3.com">Button3</button>
<button data-url="http://www.test-button-4.com">Button4</button>
<button id="goButton">Go to Link Above</button>
function setLink(link) {
document.getElementById("changedText").innerText = link;
}
function Go() {
document.location.href = document.getElementById("changedText").innerText;
}
<h1 id="changedText">Button changes this text</h1>
<button onclick="setLink('http://www.test-button-1.com')">Button1</button>
<button onclick="setLink('http://www.test-button-2.com')">Button2</button>
<button onclick="setLink('http://www.test-button-3.com')">Button3</button>
<button onclick="setLink('http://www.test-button-4.com')">Button4</button>
<br>
<button onclick="Go()">Go to Link Above</button>

Change HTML Content using jQuery 3, then change it back

Basically, what I want to do:
When you press the button #change, the content in the div #board has to change to nothing but:
<h2>Hi!</h2>
<button type="button" onclick="ChangeAgain();">
Then when you click that button, it has to change back to what it used to be, that is:
<h2>Welcome to this page.</h2>
<p>It's quite boring in here. Why don't you click the button?</p>
<button onClick="Change();">Button for you to Click</button>
Here's my JavaScript (jQuery 3.2.1), which is not working.
$(function () {
var inThere = "";
function Change() {
inThere += $("#board").html();
$("#board").html("<h2>Hi!</h2> \n
<button type=\"button\" onclick=\"ChangeAgain();\">")
}
function ChangeAgain () {
$("#board").html(inThere);
}
})
Don't define the function in the document ready handler scope. You must be getting error like
"Uncaught ReferenceError: Change is not defined",
var inThere = "";
function Change() {
inThere += $("#board").html();
$("#board").html("<h2>Hi!</h2> \n <button type = \"button\" onclick=\"ChangeAgain();\">Button for you to Click</button>")
}
function ChangeAgain() {
$("#board").html(inThere);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
<h2>Welcome to this page.</h2>
<p>It's quite boring in here. Why don't you click the button?</p>
<button onClick="Change();">Button for you to Click</button>
</div>
Your functions are not available in the global namespace, which is considered a good practice. But due to this you should not call a function from your HTML, but listen to the click event of your button in your code:
$(function() {
var inThere = "";
var changed = false;
var $board = $("#board");
$board.on("click", "button", function() {
if (changed) {
$board.html(inThere);
} else {
inThere = $board.html();
$board.html("<h2>Hi!</h2><button>Button for you to Click</button>");
}
changed = !changed;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
<h2>Welcome to this page.</h2>
<p>It's quite boring in here. Why don't you click the button?</p>
<button>Button for you to Click</button>
</div>

Newbee JavaScript advice

I am an absolute newbee to javascript and I have these working on a web page.
HTML
<body>
<p id="decrease">399.99</p>
<button type="button" onclick="decrease();">Start Now!</button>
</body>
SCRIPT
var i=399.99;
function decrease()
{
i--;
document.getElementById('decrease').innerHTML= +i;
}
The script works when the button is clicked but decreases the number by "1" and I need it to decrease by 0.25 and I need a "$" sign in front of the number.
Can someone help?
Thanks everyone who responded it works perfectly no need for any other answers, Happy Holidays
var i = 399.99;
function decrease() {
i -= 0.25;
document.getElementById('decrease').innerHTML = "$" + i;
}
<body>
<p id="decrease">$399.99</p>
<button type="button" onclick="decrease();">Start Now!</button>
</body>
var i = 399.99;
function decrease() {
i -= 0.25;
document.getElementById('decrease').innerHTML = '$'+i;
}
<body>
<p id="decrease">$399.99</p>
<button type="button" onclick="decrease();">Start Now!</button>
</body>
Add a "$" to the innerHTML:
var i=399.99;
function decrease()
{
i-=0.25;
document.getElementById('decrease').innerHTML= '$' + +i;
}
http://jsfiddle.net/jjt5u1dn/2/
Given that the $ character is presentational, I'd suggest using CSS rather than JavaScript:
#decrease::before {
content: "$";
}

Is there a way that you can print this code instead of having an onclick?

I am making a puzzle website where you select a puzzle, I was wondering if there was a way of, instead of it being in pop up boxes it would be printed to the website. I don't mind what code we are using as I am fluent in most,
This is the code I have so far:
<body>
<script type="text/javascript">
function myFunction()
{
function ask() {
var a = (Math.round(Math.random()*1000000))
alert (a)
return prompt("What was the number?") == eval( a );
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction()">Remember the number</button>
</body>
<body>
<script type="text/javascript">
function myFunction2(){
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction2()">Quick math</button>
</body>
</html>
</html>
So I was wondering if there was a way to make it show up as text and have a text box on the page to type into that would still work. And the design is able to be changed, so I can make a larger text box, or a larger font so it's not just an un-editable onclick.
All help greatly appreciated.
Thanks.
I did what I thought that you wanted to the "Remember the number" button click.
Sorry, had no time to do the other one.
HTML:
<body>
<button id="rmbrBtn">Remember the number</button>
</body>
<body>
<button id="quivkBtn">Quick math</button>
<div id="question_area">
</div>
</body>
</html>
</html>
JS & jQuery code:
$("#rmbrBtn").click(function()
{
// Answers collection
var questions = [];
// Check the correctness of the answer
function checkAnswer (){
total = questions.length,
correct = questions.filter(Boolean).length;
if(total < 5)
{
ask();
}else{
var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
$("#question_area").append(answer);
$("#ansOk").click(function(){
$(this).parent().empty();
$(this).parent().remove();
});
}
}
// Get the question
function ask() {
var a = (Math.round(Math.random()*1000000));
// View the generated number
var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';
// Prompt user with a text box
var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input type="button" id="prmtOk" value="Ok"/></div>';
// Append
$("#question_area").append(viewNumber);
$("#ok").click(function(){
$(this).parent().empty();
$(this).parent().remove();
$("#question_area").append(promptVal);
$("#prmtOk").click(function(){
var prmt = $("#ans").val();
var addVal = prmt == a;
questions.push(addVal);
checkAnswer();
$(this).parent().empty();
$(this).parent().remove();
});
});
}
// Run the function.
checkAnswer();
});
Online solution:
JSFiddle
Try to do the other one same as this.
Sorry had no time to comment also.
I think you can figure this out.
Just add a div at the top of your page and use jqueries .html() and you will be done
like
$('.header').html('You are correct.');
here is a fiddle http://jsfiddle.net/AMISingh/8nWKD/3/
This can also be done without JQuery and just JavaScript.
http://jsfiddle.net/8nWKD/4/
<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>
and the JavaScript
function test_click()
{
document.getElementById("header").innerHTML = "CORRECT!";
}

Javascript click count and submit to text area

I am fairly new to coding and am attempting to learn to make a Chrome Plugin to add some functionality to a website. I have been struggling to find an answer to this and have searched and come up with quite a few different options, but nothing I can figure out to create what I am after.
What I and am looking to for is a script that will allow me to count the clicks of 5 different buttons, then send them to a textarea via a "submit" button.
[A] [B] [C] [D] [E] [send]
So if I were to click button A twice, C once and E three times then click "send" it would send it to my textarea and it would read "Counted A2 C1 E3" and would ignore anything that was not clicked. As a bonus, is it possible that when the text is sent to the textarea it would automatically submit?
Hope this makes sense and am looking forward to any help I may be able to get.
Regards,
Pazinga
This code is better, you can have as much buttons as you like!
update: Fix a bug that keys are unsorted (eg: Counted E3 C1 A2)
<html>
<head>
<script>
var list = {};
function increaseCounter(variable) {
if(!list[variable])
list[variable]=1;
else
list[variable]++;
}
function send() {
var keys = [];
for(x in list)
keys.push([x,list[x]]);
keys.sort();
var s = "Counted", i;
for( i = 0; i < keys.length; i++)
s += " " + keys[i][0] + keys[i][1];
document.getElementById('textarea').value = s;
}
</script>
</head>
<body>
<textarea id="textarea"></textarea>
<button onclick="increaseCounter('A')">A</button>
<button onclick="increaseCounter('B')">B</button>
<button onclick="increaseCounter('C')">C</button>
<button onclick="increaseCounter('D')">D</button>
<button onclick="increaseCounter('E')">E</button>
<button onclick="send()">Send</button>
</body>
</html>
You can find a possible solution here : http://jsfiddle.net/jrm2k6/gv8vZ/
You can modify it at your convenience.
Here is the html used:
<button type="button" id="a">A</button>
<button type="button" id="b">B</button>
<button type="button" id="c">C</button>
<button type="button" id="d">D</button>
<button type="button" id="e">E</button>
<textarea rows="5" cols="40" id="results">
</textarea>
And the js part:
var buttonClicked = {"a":0, "b":0, "c":0, "d":0, "e":0};
$("button").click(function() {
$("#results").text('');
var clickedId = $(this).attr('id');
buttonClicked[clickedId] +=1
displayCounter();
});
function displayCounter()
{
for(var elem in buttonClicked)
{
if (buttonClicked[elem] != 0)
{
$("#results").append(elem + " clicked " + buttonClicked[elem] + "\n");
}
}
}
EDIT: This works fine, but TNW gave another approach, more generic, here is the fiddle http://jsfiddle.net/xRMRP/
Try the below code it will help you:
<html>
<head>
<script>
var A = 0;
var B = 0;
var C = 0;
var D = 0;
var E = 0;
function increaseCounter(variable) {
switch (variable) {
case 'A':
A++;
break;
case 'B':
B++;
break;
case 'C':
C++;
break;
case 'D':
D++;
break;
case 'E':
E++;
break;
}
}
function send() {
var text='Counted ';
if(A>0){
text+=' A'+A;
}
if(B>0){
text+=' B'+B;
}
if(C>0){
text+=' C'+C;
}
if(D>0){
text+=' D'+D;
}
if(E>0){
text+=' E'+E;
}
document.getElementById('textarea').value =text;
}
</script>
</head>
<body>
<textarea id="textarea"></textarea>
<button onclick="increaseCounter('A')">A</button>
<button onclick="increaseCounter('B')">B</button>
<button onclick="increaseCounter('C')">C</button>
<button onclick="increaseCounter('D')">D</button>
<button onclick="increaseCounter('E')">E</button>
<button onclick="send()">Send</button>
</body>
</html>

Categories

Resources