How to Change a Value of a Variable and Print It - javascript

Sorry, I'm totally new to javascript and need help with something you think is probably really stupid.
I'm trying to make it so that when you start the program, it prints 0, then when you press a button, it changes 0 to 1. This is what I have so far -
<!DOCTYPE html>
<html>
<p id="print"></p>
<script>
var x = 0
document.getElementById('button').onclick = function() {
x++;
};
document.getElementById("print").innerHTML = x;
</script>
<button id = "button">Change Variable x</button>
</body>
</html>
Although, it doesn't print anything when I run the code. Please Help! (By the way, you are probably thinking that this is a stupid question.)
Thanks!

I hope this will work:
var x = 0
document.getElementById('button').onclick = function() {
x++;
document.getElementById("print").innerHTML = x;
};

Not sure if this is what you are looking for, but all I did was make a function name and then whenever you click the button it adds 1 to the
<p id="print">hello</p>
<button id = "button" onclick="myFunction()">Change Variable x</button>
<script>
var x = 0
function myFunction(){
document.getElementById('print').innerHTML = x+=1;
}
</script>

Here is a working snippet of what you are looking for, using javascript. When the user clicks the button, it changes the value to 1, and then when you click the alert button it alerts 1 instead of 0.
var changeMe = 0;
function changeVar() {
changeMe = 1;
}
function alertVar() {
alert(changeMe);
}
<button onclick="changeVar();">Change</button>
<button onclick="alertVar();">Alert</button>

Related

Javascript - 2nd button click clears my div

im fairly new to JS and ive created a formula to do some calculations and put them into a div when its done. My problem is on the first button press it works like a charm. When i press the button a second time it deletes the text in my div and doesnt redo the calculation.
Its probably some silly mistake i cant find but id appreciate any help. The Code looks like this:
function formChanged() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
}
document.getElementById('button').click = function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML = "post-text";
}
<form>
<input value="20" id="x" type="text" onkeyup="formChanged()" onchange="formChanged()">
<input value="1" id="y" type="text" onkeyup="formChanged()" onchange="formChanged()">
<button type="button" id="button">Calc</button>
</form>
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
I tried to slim it down a bit since its a bigger loop with calculation etc. The function itself works fine though.
document.getElementById("test").innerHTML = "post-text";
this part removes your div content, just change it with :
document.getElementById("test").innerHTML += "post-text";
Calc
Full working code:
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
<script>
function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML += "post-text";
}
</script>
And ofcourse you can use element.addEventListener("click", calc)like SimpleJ mentioned.
document.getElementById('button').addEventListener("click", calc);
I copied your code into a file and tried it. Your button doesn't do anything.
Edit: As #SimpleJ stated, calling globally is a bad practice. I updated the answer.
function calc(){
// function body
}
document.getElementById('button').addEventListener("click", calc);
This way the calc() function is actually called when you click the button. It's called adding an EventListener if you need some term to Google for further reference.
I hope this is what you need.

How do I make a button disappear after a certain amount of clicks

I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on!
any response is appreciated!
Use this Code
HTML:
<button type='button' id='button_test_clicks'>
Click me!
</button>
JavaScript:
(function(){
var counter=0; // counter clicks initialization
var button=document.getElementById('button_test_clicks'); //Our button
button.addEventListener("click",function(){ //add a click event to button
counter++; //incement the counter
console.log(a);
if(counter==5){
button.style.display = 'none'; //hide if the clicks reached to 5
}
});
})();
But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage in javascript.
Assign id to your button.
<Button id='myButton' onclick="myFunction()">
On every click of button, keep incrementing the counter (I think you know how to do it)
After the counter is reached,
document.getElementById("Your_button_id_here").style.visibility = "hidden";
<script>
var counter=0;
function myFunction() {
//increment counter
counter+=1;
if(counter>4)
document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>
However, I think disabling would be more proper:
document.getElementById("Your_button_id_here").disabled=true
You could have a simple script like this :
var nbClicks=0;
function btnOnClick(btn){
if(++nbClicks>5){btn.style.display='none';}
}
And use it like that :
<input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">
On every click just increment a variable's value and after got desired number, hide it by css and js.
I made a small example with jQuery
var count = 0;
$("#b1").click(function() {
count++;
if (count >= 5) {
$("#b1").hide();
}
});
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<button id="b1">5 Clicks</button>
</body>
</html>

How to toggle <p> once you click on <button> for second time?

function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<button type= "button" onclick="testFunction()"> Click Here! </button>
I am wondering how I hide the paragraph once a user clicks on the button a second time? When user clicks on button the first time, javascript is enabled and the code is shown, but then paragraph stays on the screen even after user clicks for a second time on button. Is there some way I can hide what is displayed if user clicks on button for a second time?
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<script>
function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
</script>
<button type= "button" onclick="testFunction()"> Click Here! </button>
First of all, I don't think that you should alter the style of elements trough js, that is what css is for (exceptions exist obviously). You could however alter the state of an element, and have your css react to that. I find it keeps your code a lot easier to maintain, and you know automatically where to look for what when you need to change something.
Have a look at the fiddle I prepared: http://jsfiddle.net/7xy39ufz/1/
So I added a state to your markup (I went for a data attribute, but a class or something could do as well)
<p id="test" data-visible="0">...</p>
<button type="button" id="button">...</button>
Then in the css I added a few lines that would react to the state:
p {
font-size: 50px;
color: blue;
}
p[data-visible="0"] {
display: none;
}
p[data-visible="1"] {
display: block;
}
And with all that done the javascript becomes very simple
document
.getElementById('button')
.addEventListener('click', testFunction, false);
function testFunction(){
var x = document.getElementById("test");
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
}
Note that I moved the binding of the click event to js as well, in part because I couldn't get it to work in the fiddle (a scope / sandbox issue i guess), but mainly because I find js belongs with js, not in your markup.
Update
The real 'magic' is indeed being done in this line:
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
This is basically a short hand for
if (x.dataset.visible == 0) {
x.dataset.visible = 1;
} else {
x.dataset.visible = 0;
}
(look up 'ternary' if you want to learn more about the syntax)
This code switches the data-visible attribute of you p between 1 and 0. The css reacts to that by setting the display property of that paragraph (that is what the attribute selector [data-visible="..."] is for).
I hope this clarifies things for you. Feel free to ask if you want me to explain further.
<script>
function testFunction(){
if (x.style.fontSize == "40px"){ //you could use another condition, or a global var here
document.getElementById("test").style.display="none";
}
else{
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
}
</script>

How to change the argument of an onclick function dynamically

I’ve got this button here:
<button onclick="cookieClick(1)">Click Me!</button>
which gives me 1 cookie when I click on it.
function cookieClick(number){
cookies = cookies + number;
document.getElementById("cookies").innerHTML = cookies;
}
This here is the function I use to get it to work.
Now here is my problem: When I want to increase the number of cookie I would get per click I can’t figure out how to do it. This is what I think is the closest to what it should be:
function upgrade(){
if(cookies >= 100){
document.getElementById("cookieClicker(1)").innerHTML * 2 = cookieClicker();
}
}
But I’m guessing that isn’t quite right since it doesn’t work.
Try this:
<button id="cookie-clicker" type="button">Click Me!</button>
var numCookies = 0,
cookiesPerClick = 1,
clicker = document.getElementById("cookie-clicker"),
cookies = document.getElementById("cookies");
clicker.addEventListener('click', cookieClick);
function cookieClick(){
numCookies += cookiesPerClick;
cookies.textContent = numCookies;
}
function upgrade(){
cookiesPerClick *= 2;
}

Trying to change button's contents each hit fails

Given the code :
<html>
<head>
<script src="jquery-2.1.0.min.js"></script>
Something...
</head>
<button id='flip' type='button'>Flip</button>
<script>
$('#flip').bind('click', function() {
var x = document.getElementById("flip").name;
if (x == 'Flip')
{
$(this).text('Flop');
}
else
{
$(this).text('Flip');
}
});
</script>
</body>
</html>
I'm trying to change the button each time it is clicked , but it doesn't work .
Any idea how to fix it ?
Much appreciated
There is no name attribute on your <button>, so you'll always get empty value. No need for document.getElementById because button is in this. Simply call text() without parameters to get current value:
var x = $(this).text();
Update
Here is demo in JsFiddler.
I would do something like this:
HTML:
<button id="flipflop">flip</button>
javascript:
var flip = true;
$("#flipflop").click(function(){
if(flip)
$("#flipflop").text("flop");
else
$("#flipflop").text("flip");
flip = !flip;
})
FIDDLE
edit: if you want to be really savvy, I would use the following line:
var flip = ($("#flipflop").text() === "flip");
Which automatically determines which way you need to flip (or is it flop?).

Categories