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>
Related
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function wordRand(){
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random()*words.length)];
}
function replaceAt(str,index,chr){
if(index > str.length-1)
return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
function wordSet(){
var i, word=wordRand();
document.getElementById("text").innerHTML += word.charAt(0); //places the first letter.
for(i=1;i<word.length;i++)
document.getElementById("text").innerHTML += '-';
document.getElementById("checkword").innerHTML = word; //my current solution.
}
function check(letter){
//variable "word" receives the string from the paragraph with ID "checkword".
var exists=false, i, word=document.getElementById("checkword").innerHTML, correct;
for(i=1;i<word.length;i++){
if(word.charAt(i)==letter){
exists=true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if(exists==false)
document.getElementById("verify").innerHTML += "No ";
}
</script>
</head>
<body onload="wordSet();">
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button onclick="check('Q');">Q</button>
<button onclick="check('W');">W</button>
<button onclick="check('E');">E</button>
<button onclick="check('R');">R</button>
<button onclick="check('T');">T</button>
<button onclick="check('Y');">Y</button>
<button onclick="check('U');">U</button>
<button onclick="check('I');">I</button>
<button onclick="check('O');">O</button>
<button onclick="check('P');">P</button>
<button onclick="check('A');">A</button>
<button onclick="check('S');">S</button>
<button onclick="check('D');">D</button>
<button onclick="check('F');">F</button>
<button onclick="check('G');">G</button>
<button onclick="check('H');">H</button>
<button onclick="check('J');">J</button>
<button onclick="check('K');">K</button>
<button onclick="check('L');">L</button>
<button onclick="check('Z');">Z</button>
<button onclick="check('X');">X</button>
<button onclick="check('C');">C</button>
<button onclick="check('V');">V</button>
<button onclick="check('B');">B</button>
<button onclick="check('N');">N</button>
<button onclick="check('M');">M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
I'll start off by saying that I apologize if this question is extremely basic and probably has been already answered, but I can't seem to find a proper response to it:
I am in the process of creating the code for an HTML page, with a bit of JavaScript included. However, I have a problem with a variable: my only way to pass it is by first inserting its content in an element inside the body, and then copying it in the other function's variable, as follows:
function parolaSet(){
var i;
var parola=parolaRand();
document.getElementById("testo").innerHTML += parola.charAt(0);
for(i=1;i<parola.length;i++)
document.getElementById("testo").innerHTML += '-';
document.getElementById("verifica").innerHTML = parola;
}
function check(lettera){
var present=false, i, parola=document.getElementById("verifica").innerHTML, giusto;}
Where "verifica" is a "p" element. I did think about using the simple "return parola;" command in the parolaSet function, however, this function sets a word in the HTML page that can't be changed by any means, as it's a requirement for my project to work. Making the call everytime I need a returned value from it would reset the word and mess everything up. So, is there another way to share this value without having to use up space in the page, repeating the parolaSet function's code and just by using common JavaScript functions and commands? If JavaScript on its own is not enough for this, I would like to acknowledge other options anyway.
P.S. Creating a global variable doesn't seem to work, as the value is returned as an "Object object" when used in the page or inside of functions.
EDIT: Due to absolutely reasonable suggestions, I added a snippet of my page. It's all just a basic hangman game, the words in the original code are much more, but this is the most minimal I could make it.
Try a hidden input field to pass the value along with every web request.
Somthing like:
<input hidden id="MyValueToPass" value="parola">
Have a look at this
I delegate the click and have word as a global
let word;
function wordRand() {
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random() * words.length)];
}
function replaceAt(str, index, chr) {
if (index > str.length - 1)
return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
function wordSet() {
word = wordRand(); // set the global word
document.getElementById("text").innerHTML = word.charAt(0) + word.slice(1).replace(/./g,"-")
}
function check(letter) {
//variable "word" receives the string from the paragraph with ID "checkword".
var exists = false, i, correct;
for (i = 1; i < word.length; i++) {
if (word.charAt(i) == letter) {
exists = true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if (exists == false)
document.getElementById("verify").innerHTML += "No ";
}
window.addEventListener("load", function() {
document.getElementById("keyboard").addEventListener("click", function(e) {
const tgt = e.target.closest("button");
if (tgt)
check(tgt.textContent)
})
wordSet();
});
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button>Q</button>
<button>W</button>
<button>E</button>
<button>R</button>
<button>T</button>
<button>Y</button>
<button>U</button>
<button>I</button>
<button>O</button>
<button>P</button>
<button>A</button>
<button>S</button>
<button>D</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>Z</button>
<button>X</button>
<button>C</button>
<button>V</button>
<button>B</button>
<button>N</button>
<button>M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
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.
When I click on of these button I want an item in sessionStorage to be assigned to true which is indicative of the button which was pressed. When the fourth button is clicked I was it to show what information was selected to know more about.
Right now my button aren't returning anything and I can't figure out how to loop through this and assign a function to every button
//simple html to print four buttons.
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
document.getElementById(y[count].id).onclick = function(count) {
//Assigning a variable to be the id name of button passed into this function
z = y[arguments[i]].id;
//If the button is the fourth button
if ( z == "infoChosen" ){
//Add in the things which were selected
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
If the first button and then the fourth button is clicked the output should be
Green Molluscs
If the first and third button are clicked and then the fourth the output should be
Green Molluscs Green Sweaters
I need to do it in a loop
Try this
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript">
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
var aa = y[count].id;
document.getElementById(y[count].id).onclick = function(aa) {
var z = aa.currentTarget["id"];
if ( z == "infoChosen" ){
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
}
</script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
I would do it differently in this situation.
In my eyes the best option is to make a function for each button like this <button onclick="myFunction()">Click me</button>and that function changes a variable too true or false. And when you click the 4th button it might be the best too use the switch statement for each possibility for the right output.
I am not that experienced in coding yet so this might not be the most efficient way but I hope this helped you.
Well, firstly, you're not accessing your sessionStorage correctly. See this. And what you're doing looks a bit like a mess. I've tidied up the code in my answer below so I'll just make some explanations here.
I decided to grab all your buttons using document.getElementsByTagName("button"); it may not always be applicable, but it feels suitable in your case.
I've changed using a for loop using length, to just using the of operator. It basically iterates through an array without needing to length it.
I think the other parts concerning putting stuff into the sessionStorage is pretty straight forward, but if you are unsure, just ask me and I'll rewrite it.
jsfiddle: https://jsfiddle.net/ryvcvp42/
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!";
}
I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}