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: "$";
}
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.
im trying to change a line of text if a link is clicked, however it doesnt seem to be calling my script to change it.
<script >
var paragraphToChange = document.getElementById("q1");
paragraphToChange.innerHTML ="Quotation is by:" + Antole France
</script>
<div id="body">
<p>javascript.html - JavaScript page</p>
<a href id="q1">Quotaion is by:</a>
</div>
What you're trying to accomplish is probably something like this:
HTML
<div id="q1">
<a onClick="javascript:clickFunction()">Quotation is by</a>
</div>
JavaScript
clickFunction = function() {
document.getElementById("q1").innerHTML = "<a href='http://www.quotationspage.com/quote/1463.html'>Antole France</a>";
}
JSFiddle
Sir you have to set the value of "newValue" to the quotation.
var newValue = '"Quotation is by:" + Antole France'
paragraphToChange.innerHTML = newValue;
You are missing the click event on the Html tag. Hence, this paragraphToChange.innerHTML ="Quotation is by:" + Antole France"
never gets call.
Why don't you start with this example first:
<p id="display"></p>
<button onclick="displayBob">Bob</button>
<button onclick="displayTom">Tom</button>
<script>
displayBob = function ()
{
document.getElementById("display").innerHTML = "Hello Bob";
}
displayTom = function ()
{
document.getElementById("display").innerHTML = "Hello Tom";
}
</script>
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 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>