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.
Related
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.
I dynamically create a form. There is an add line button that adds a new line that includes a delete line button.
I originally wrote this in angular, and I was able to pass "$index" into the function to remove the specific line.
I am now rewriting my code in pure js, and my question is: How can I go about implementing this same functionality?
The example for deleting elements by index as per your requirement can be found in this jsfiddle : https://jsfiddle.net/ChaitanyaMunipalle/9z73rfjx/2/. I assume you will take care of adding lines & delete buttons dynamically. It contains only deletion.
As you have not given any code, I assumed the html would look like the below one:
<div id="lines">
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
</div>
You have to add event listeners to delete buttons. And you have to use closure to save the index of the button clicked.
var deleteItem = function(index) {
var divElements = document.getElementsByClassName("line-item");
for (var i = 0; i < divElements.length; i++) {
if (i == index) {
divElements[i].parentNode.removeChild(divElements[i]);
break;
}
}
};
var deleteButtons = document.getElementsByClassName("delete-line");
for (var i = 0; i < deleteButtons.length; i++) {
(function(index){
deleteButtons[i].addEventListener('click', function() {
deleteItem(index);
}, false);
})(i);
}
I don't quite understand your setup, but removing a div is just
parentNode.removeChild(yourDiv)
If you only have the parentNode but know the index of the div you want to delete, then
parentNode.removeChild(parentNode.children[i])
`<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>`
This a example in jsfiddle:
https://jsfiddle.net/AlfonsoRamirez9/ttj1sLo5/
I hope help you :)
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");
I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:
<div id="person">
<br><br>
<div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
<div role="form">
...
<button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
</div>
</div>
<div id="person-success" class="hide">
...
<p>
<span l10nID='M_AC_UT_TXT_19'></span>
You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
</p>
</div>
The JavaScript:
$('#addPerson').click(function() {
var counter = 0;
var limit = 10;
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?
I hope I could explain my problem. Would be grateful for any help!!
Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.
var counter = 0;
var limit = 10;
$('#addPerson').click(function() {
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
The variable you declare is local scope.
Declare variable globally outside the click event called.
On each click it resets counter to 0.
Hope it helps !!!
I searched everywhere on here on an alternative on printing to HTML from a JavaScript function to HTML without using document.write() but document.getElementById() doesn't seem to work and I'm really not sure how to go about doing this.
I have this so far
JavaScript
function trials() {
while (num_trials > 0) {
for (var i = 0; i < random.length; i++) {
document.write(random[i]);
}
}
}
Where "random" is an array of letters
HTML
<div id ="container">
<center>
<i>**TRIALS HERE**</i><br><br>
<font size="8">
<script>trials();</script><br><br>
</font>
</center>
</div>
I'm also looking for a way to hide each letter after each iteration of the for-loop so that it doesn't just print as a long string of letters.
Basic idea is to use an interval to loop through the array so there is a delay. You want to set the text with innerHTML or textContent.
(function() {
var outputElem = document.getElementById("outputSpot"), //where to output the letter on the screen
current = 0, //start index in the array
randomChars = ["W","E","L","C","O","M","E","!"], //characters to show
timer = window.setInterval( //this is how we will loop with an interval
function () {
var letter = randomChars[current]; //get next letter
if (letter) { //if there is no letter, it will be undefined and we will be done
outputElem.innerHTML = letter; //show the letter to the user
current++; //update the index
} else {
window.clearInterval(timer); //cancel the timer since we ran out of things to display
}
}
,1000); //number of seconds to wait between iterations
}());
<span id="outputSpot">Hello!</span>
Javascript
I would try setting the div to a variable:
var div = $('#container');
function trials() {
while (num_trials > 0) {
for (var i = 0; i < random.length; i++) {
div.appendTo(random[i]);
}
}
HTML
Then maybe hiding the container div (style='display:none;') would prevent the numbers printing out, but still accessible:
<div>
<center>
<i>**TRIALS HERE**</i><br><br>
<font size="8">
<script>trials();</script>
<div id="container" style="display:none;"></div><br><br>
</font>
</center>
</div>
It may be very useful for you to use JQuery.
function trials() {
while (num_trials > 0) {
for (var i = 0; i < random.length; i++) {
$('#iToWrite').html( $('#iToWrite').html() + random[i]);
}
}
}
<div id ="container">
<center>
<i id='iToWrite'>**TRIALS HERE**</i><br><br>
<font size="8">
<script>trials();</script><br><br>
</font>
</center>
</div>