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.
I'm trying to mimic the while loop of plain Javascript in AngularJS. I simply want to call the createPlant() method x number of times according to the value of the quantity input, when the "add" button is clicked, as follows (it adds to an array 'plants'):
$("#add").on("click", function() {
var i = 0;
while (i < $("#pQuantity").val()) {
createPlant();
i += 1;
};
In Angular I have:
HTML
<button ng-click="addPlant()" type="button">Add</button>
And I'm not sure how the script would look but this is what I wrongly put:
JS
var i = 0;
while (i < $("#pQuantity").val()) {
$scope.addPlant = function() {
var plant = {name: $("#pVariety").val()};
$scope.plants.unshift(plant);
};
i += 1;
};
I support what #dfsq told you in the comment. Do not use jQuery if you are using angular... unleash the angular power! :P
For your solution, you should do something like this:
Your JS:
$scope.result="";
$scope.addPlant = function(){
for (i=0; i<$scope.someValue;i++){
//do something
$scope.result=$scope.result+i.toString()+",";
}
};
HTML:
<body ng-controller="MainCtrl">
<input type=number ng-model="someValue" />
<button ng-click="addPlant()">CLICK ME</button>
<div>{{result}}</div>
</body>
Plunker sample
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 want to check if the value of my textarea is almost the same as requires , for example :
I have a HTML code :
<textarea class="ab" placeholder="Type here"></textarea>
<div class="result">
</div>
and a Jquery code :
$(document).ready(function(){
$(".btn").click(function(){
var a = $(".ab").val();
var b = $(".result").html();
/* */
if(a.indexOf('Which of the following is generally true about Open Source software?') >= 0){$('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');} /* */
else{
$(".result").html("error");
}
});
});
this code doesn't work as what i want actually , this is just what i tried to make . But the thing i want is for example when the value of the $('.ab') is almost the same as the text Which of the following is generally true about Open Source software? like the following is generally true or true about the Open Source , the $(".result") still have the html as Its usually developed on a volunteer basis and anyone is free to change it (correct).
So how do i do that , thanks for your help
Try splitting input text into array , using $.each() to iterate input words , if input words match at least five words in selected phrase , return true , else return false at if ; e.g.; try typing or pasting at textarea
the following is generally true or true about the Open Source
$(document).ready(function() {
$(".btn").click(function() {
var a = $(".ab");
var b = $(".result");
var arr = a.val().split(/\s+/);
var n = 0;
var phrase = "Which of the following is generally true about Open Source software?";
$.each(arr, function(key, val) {
if(phrase.indexOf(val) >= 0) ++n;
})
if (n >= 5) {
b.html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
}
else {
b.html("error");
};
a.val(""); n = 0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea class="ab" placeholder="Type here"></textarea>
<div class="result"></div>
<button class="btn">click</button>
Actually it should be:
$(document).ready(function(){
$(".btn").click(function(){
var a = $(".ab").val();
var b = $(".result").html();
var c = 'Which of the following is generally true about Open Source software?';
console.log(c.indexOf(a));
if(c.indexOf(a) >= 0){
$('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
} else {
$(".result").html("error");
}
});
});
<textarea class="ab" placeholder="Type here">following is generally true about Open Source</textarea>
<div class="result"></div>
<button class="btn">test</button>
Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/