Getting the value from an HTML button using JavaScript - javascript

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();

You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;

You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!

Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}

Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");

Related

How to make dynamic changes in HTML?

So I want to add to a variable every time someone clicks a button on my website. I am very new to HMTL so I don't know how to do this. All the examples I've googled just change text into other text and not adding to a variable.
If someone would like to enlighten me on how to do this I would greatly apricate it.
function changeIt() {
document.getElementById('test').innerHTML = "<h2>Congrats</h2>";
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
var sum = 0;
function changeIt() {
sum++;
document.getElementById('test').innerHTML = `<h2> ${sum} </h2>`;
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
The code you've written in document.innerHTML is correct. For making it dynamic and to add a new Congrats onto the screen instead of just modifying the old one, you need to keep a global counter and loop over it.
let count = 0;
function changeIt() {
count++;
for (let i=0;i<count;i++) {
document.getElementById('test').innerHTML = '';
let h2 = document.getElementById('test').createElement;
h2.innerHTML = "Congrats";
document.getElementById('test').appendChild(h2);
}
}
Since you are calling the changeIt function on every button click it will let you update the count and will loop over the count to add the Congrats 'count' number of times to your div.

How to add +1 to a text value every click i do?

I want to add +1 to a text value but when I click it doesn't add anything...
I think is a updating time but i am not sure...
<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
punticlick = 1;
punti = document.getElementById("cliccare").value ;
function clicca() {
punti += punticlick;
}
I don't really know if it is correct the onclick on the img...
You cannot add punticlick to punti, it makes no sense: in javascript, punti += punticlick equals to punti = punti + punticlick. Instead, you have to do this:
punticlick = 0;
punti = document.getElementById("cliccare");
function clicca(){
punticlick++;
punti.value = punticlick;
}
Check the fiddle: https://jsfiddle.net/jn9dqfp4/1/
punti = document.getElementById("cliccare").value is outside the function clicca. So on every click it wont get new value
Secondly since you will add one you can directly add with punti. I dont see any use of second variable
Thirdly once you have updated the value of punti you need to update value of the DOM
function clicca(){
punti = parseInt(document.getElementById("cliccare").value,10) ; // Convert to integer
punti += 1;
document.getElementById("cliccare").value=punti
}
JSFIDDLE
A very shortcut (mostly discouraged) way is like this
cliccare.onclick = e => ++e.target.value
<input type="text" id="cliccare" value="0">
you can just set onclick attribute:
onclick="document.getElementById('cliccare').value++"
<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
<script>
var pun = 1;
punti = document.getElementById("cliccare").value ;
function clicca(){
punti=pun;
document.getElementById("cliccare").value=punti;
pun++;
}
</script>
Try This
You can use onclick attribute for almost any html tag, but the code snippet you've wrote won't work, because after the increment of the value you need to set that value back into input tag, so your java script part would look like this:
<script>
punticlick = 1;
function clicca() {
punti = document.getElementById("cliccare").value;
punti += punticlick;
document.getElementById("cliccare").value = punti;
}
</script>

How do I change the text displayed on a website?

What I want to do is change one word of text on my webpage to run through a list of words.
ie:
<p>My favorite hobby is <u>fishing</u>!</p>
Where "fishing" would change after about 2 secs to the next word of a list of hobbies.
The closest example I've found is this
<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3>Hang around a bit (for a surprise).</h3>
</div>
function ChangeIt() {
var newcontent = '
<h1>Click here ' +
'for a web page with more of the same.</h1>';
WriteContentIntoID("welcome",newcontent);
}
setTimeout("ChangeIt()",20000);
But I can't get it to work either.
Here's something simple using setInterval():
<p>My favorite hobby is <span id="ch">fishing</span>!</p>
<script>
var activities = ['eating', 'burping','coding'];
var i=0;
setInterval(function(){
document.getElementById("ch").innerHTML = activities[i];
if (i < activities.length-1) {
i++;
} else {
i=0;
}
}, 1000);
</script>
FIDDLE Demo
EDIT: changed to make it loop forever.
Use this:
<p>My favorite hobby is <u>fishing</u>!</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function getnewword(){
return "me";// fix this section with getting new word!
}
function ChangeIt() {
$("p u").html(getnewword());
setTimeout("ChangeIt()",2000);
}
setTimeout("ChangeIt()",2000);
<script>
Programming is cool. You should try with some beginner JavaScript tutorials like http://www.w3schools.com/js/.
You must encapsulate your script with script tag and you must use selectors (like document.getElementById).
This is the full code:
<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3 id="hobby">Hang around a bit (for a surprise).</h3>
</div>
<script>
// we start with 0
var currentHobby = 0;
function ChangeIt() {
// hobbies array
var hobbies = ["fishing", "eating", "drinking", "programming"];
// we save the current hobby in hobbyString and increment the currentHobby number
var hobbyString = hobbies[currentHobby];
currentHobby++;
// if the currentHobby number is too big, we start with 0 again
if(currentHobby >= hobbies.length) {
currentHobby = 0;
}
document.getElementById("hobby").innerHTML = "My favourite hobby is " + hobbyString;
}
setInterval("ChangeIt()",2000);
</script>
HTML PART
I am going to <span id="changingtext">InitialWord</span>
Javascript Part - You Need JQuery and call the following on onLoad
var texts = ["France", "Italy", "Ireland", "Wales"];
var count = 0;
function updateval() {
$("#changingtext").text(texts[count]);
count < 4 ? count++ : count = 0;
}
setInterval(updateval, 2000);
Working JS Fiddle Link Click Here
Click on the Javascript setting button on JsFiddle to check the settings put in use.

Javascript function not defined in jQuery

I have problems with a simple bit of code. I'm trying to take a value from an input field and then do a simple calculation. The calculation is supposed to take place with an onSubmit command and then append it to a p tag.
HTML:
<h1 class="titleHead">Calculator</h1>
<form method="POST" action="#" onSubmit="depositCal()">
<input type="text" name="money" id="money">
<input type="submit" value="How much" onSubmit="">
</form>
<div>
<p class="answer"></p>
</div>
Javascript:
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
function depositCal() {
$('.answer').append(finalNumber);
}
})
I get back function not defined when it runs.
I know this is probably very simple but any help would be greatly appreciate.
Try this:
Give your form a name and ID e.g. 'myForm'
JS
$('#myForm').submit(function(e){
e.preventDefault();
var numberOne = $('#money').val();
var numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
});
e.preventDefault() - stops the form from submitting (thus refreshing the page) and the function is only fired when submit is clicked.
Addition
numberOne is getting it's value from a form field so it sees it as a string.
To prevent this use this line instead:
var numberOne = parseFloat($('#money').val());
Which forces the value to be a (float) number.
You need to declare the function in global scope if you want to use it in inline js
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
})
function depositCal() {
$('.answer').append($('#money').val() + 4);
}
You could also make it a global function by attaching the function to window object.
I think you don't need $(document).ready here and do calculation of finalNumber inside function so that it will give you the correct value of money input, otherwise you will get NaN or empty value-
function depositCal() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
}
You have to keep the depositCal function definition out of $(document).ready(),because first the whole document is loaded,then $(document).ready() is called.So while loading the form,browser finds depositCal as undefined as it is defined after document is fully loaded......So keep the depositCal definition in global scope

Noob at javascript trying to add +1 to a var with a button

Hey I'm really new to javascript and i just don't understand why it won't print on my document a number increasing every time i click on my button
<script type="text/javascript">
var x = 0;
function clicker(
y = x+1
)
document.write(y)
return clicker();
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
must be :
var x = 0;
function clicker(){
y = x+1;
document.write(y)
}
but, using document.write(y) will erase your button, to remedy this, you can create another element like <div id='status'></div> and use
//use this instead of document.write(y)
var stat = document.getElementById("status");
stat.innerHTML = y;
There are some problems with the script:
The syntax for the function is wrong, so the code won't run at all.
You can't use document.write once the page is loaded, then it will replace the entire page with what you write.
You are calculating a value that is one higher than a value that never changes, so it will only increase the first time, after that it just returns the same result.
Create an element where you can put the result, and increase the variable in the function so that the value changes each time.
<script type="text/javascript">
var x = 0;
function clicker() {
x = x + 1; // or simply x++;
document.getElementById('value').innerHTML = x;
}
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
<div id="value"></div>

Categories

Resources