Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}
Related
I am trying to loop through and increment the following:
var result_types = document.querySelectorAll('[data-title]')[0].attributes[2].nodeValue
specifically to grab and increment this value:
[0].attributes
Currently, I have the following:
var card = document.querySelectorAll('[data-title]')[0].attributes[2].nodeValue;
for (var i = 0; i < card.length; i++) {
console.log(card[i]);
}
I am trying to get this [0].attributes to increment to [1].attributes etc. when it is clicked
I am not sure what you are asking here, but if the issue is looping through the elements, this is happening because you get a NodeList back from querySelectorAll and not an array. Below will let you loop through node elements.
const nodes = document.querySelectorAll('.nodes');
[].forEach.call(nodes, (singleNode) => {
//Whatever you want.
})
I have a question about this code. It is supposed to keep score of a quiz.
function point() {
var questions = document.getElementsByTagName("input");
var value_list = [];
var point = 0;
for (var i = 0; i < questions.length; i++) {
value_list.push(questions[i].value);
if (questions[i].checked) {
point += Number(value_list[i])
}
}
var questions = document.getElementsByTagName("input");
Get all elements that have the tag <input>.questions is an array of all those elements.
var value_list = [];
var point = 0;
Initialize an array and a variable.
for (var i = 0; i < questions.length; i++) {
For all the input elements in the questions array do the following.
value_list.push(questions[i].value);
1) Push the value of the input element into the value_list array.
if (questions[i].checked) {
point += Number(value_list[i])
}
2) If the input is checked then add the point.The function Number will convert the value in value_list[i] to a number and then add it the points.we pass the value of the checked input tag as argument to the function.
The input in this case is a checkbox which has attributes checked and value.
<input type="checkbox" name="vehicle" value="Bike">
// We define a new function, named point. In this case, it doesn't receive any parameters.
function point() {
// We get all the input elements, and we store it in the variable 'questions'
var questions = document.getElementsByTagName("input");
// We are creating a new empty list
var value_list = [];
// We declare a variable initialized at 0
var point = 0;
// we are going to loop over the items inside questions (all the input elements)
for (var i = 0; i < questions.length; i++) {
// We get the value of the questions of the current iteration (questions[i].value) and we store it inside the empty list
value_list.push(questions[i].value);
// If the input is checked...
if (questions[i].checked) {
// we increment the value of point with the value in value_list[i], in this case it should be the same as questions[i],
// because previously we store questions[i] inside value_list
point += Number(value_list[i])
}
}
You are simply looping over all the input, and if the input it's checked, you increment the point variable with it's value. It could be simplified in this code
// We define a new function, named point. In this case, it doesn't receive any parameters.
function point() {
// We get all the input elements, and we store it in the variable 'questions'
var questions = document.getElementsByTagName("input");
// We declare a variable initialized at 0
var point = 0;
// we are going to loop over the items inside questions (all the input elements)
for (var i = 0; i < questions.length; i++) {
if (questions[i].checked) {
point += Number(questions[i].value)
}
}
Line1:
var questions = document.getElementsByTagName("input");
There are be elements with tag input in your HTML file.So you are taking those elements array using document.getElementsByTagName("input") and assigning in to variable questions.
So outcome of this line is you will get a variable questions which will hold all input elements of your HTML document.
Line2:
var value_list = [];
This line is being used to define an array variable value_list and assigning empty array to it.
Line3:
var point = 0;
Initializing variable point with value 0.
Line4 till end:
// for (var i = 0; i < questions.length; i++) =>for loop syntax will iterate till the length of questions(Which is array of input elements")
Suppose you have two input tag elements it will iterate 2 times.
// value_list.push(questions[i].value);=>taking value of ith input element and pushing to "**value_list**" array variable
// if (questions[i].checked) { =>
// { checking if ith element is checked}
point += Number(value_list[i])=>
//{ converting to munber and adding to point variable.
// }
//}
The result of this code will be the sum of all the values input tags have.
suppose you have an html file like below:
<html><input type="checkbox" value="10">
<input type="checkbox" value="20">
</html>
Note that only input type of checkbox has the attribute checked.After this code will successfully executed the point will be 0 + 10 + 20.
point will hold value = 30.
Best Regards,
Priyanka
function point() {
var questions = document.getElementsByTagName("input");
//This line gets all the input tags on your page. Instead you can give all your questions a common class and do this to get count
document.getElementsByClass("className");
var value_list = []; //creates an empty array value_list.
var point = 0; //intializes a variable called point = 0 for keeping the count.
for (var i = 0; i < questions.length; i++) {
//Runs a for loop starting from 0 to number of questions on your screen less 1. So if you have 5 input tags this loop will run from 0 to 4.
value_list.push(questions[i].value); //pushes the values of the questions into the array value_list.
if (questions[i].checked) { //If questions have checked property then the point variable is trying to store a number.
point += Number(value_list[i])
}
}
function point() {
var questions = document.getElementsByTagName("input");
The getElementsByTagName() method accesses all elements with the specified tagname.
var value_list = [];
Above line creates the empty list having name value_list.
var point = 0;
Set the variable point=0; Purpose of this variable is storing final result.
for (var i = 0; i < questions.length; i++) {
#var i = 0 => sets a variable before the loop starts (var i = 0).
#i < questions.length => defines the condition for the loop to run (i must be less than question.length). questions.length calculate total number of question.
#i++ => increases a value (i++) each time the code block in the loop has been executed.
value_list.push(questions[i].value);
The push() method adds new items to the end of an array.
if (questions[i].checked) {
point += Number(value_list[i])
#Here point = point+ Number(value_list[i]), it means adds the new score
}
}
state.on('change', function(){
city.empty();
$.getJSON("pincodes.JSON", function(pincodes){
var key = state.val();
for (var j= 0; j < pincodes['address'].length; j++) {
if (pincodes['address'][j]['circlename'] == key) {
temp.push(pincodes['address'][j]['regionname']);
}
}
cities = $.unique(temp);
for (var k = 0; k < cities.length; k++) {
city.append('<option>' + cities[k] + '</option>');
}
});
});
In the above state = $('#state') , the above works fine fills the cities on select "state" . But the issue is when a new state is selected the previously filled cities are also there . Even though I tried .empty on every change() .
You don't empty your temp array. So, every time this function is called, you keep appending items to your temp array.
You simply need to add the following line in your code:
state.on('change', function() {
city.empty();
temp = []; // <---
$.getJSON("pincodes.JSON", function(pincodes) {
What about cities = $.unique(temp);, it won't work.
According to jQuery.unique() documentation, this function
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
So, it is not a correct usage. If you get non-unique values from your JSON, you will need to use another way to get distinct values. There is a good SO article on this topic.
I have this segment of code that allows you set CSS changes on a timed delay. It works perfect except that it only allows you to have one instance, while I need for it to allow many. It currently just takes the last element from the loop and keeps the timeout function. Is there a way to let ALL the timeout functions from this loop to be saved and ran? I'm thinking that it is just that the setTimeout function is being overridden each time rather than being a unique function.
Note: I am getting NO console errors
Javascript (inside an onload function)
elems = _('[data-timecss]'); //function to return elems via querySelectorAll()
for (var i=0; i<elems.length; i++) {
var tempelem = elems[i];
var c_info = elems[i].dataset.timecss.split(","); //split to get time
setTimeout(function() {
var css_e = c_info[1].split(";"); //split to get css properties
for (var c=0; c<css_e.length; c++) {
var css_elem = css_e[c].split(":"); //split property and value
tempelem.style.setProperty(css_elem[0], css_elem[1]); //set value
}
}, c_info[0]); //set time
}
The HTML
<div class="block">
<p data-timecss="2000,color:green;font-weight:bold;">Change to green after 2000ms</p>
<p data-timecss="5000,display:none;">Hide this block after 5000ms</p>
</div>
Whichever data-timecss is last, will run correctly. So I can tell that the timeout function is just being overriden each time. Does anyone have any ideas on how to make these unique, but also keep it as dynamic as I have it?
you need closure - How do JavaScript closures work?
elems = _('[data-timecss]'); //function to return elems via querySelectorAll()
for (var i=0; i<elems.length; i++) {
(function(i) { // added this
var tempelem = elems[i];
var c_info = elems[i].dataset.timecss.split(","); //split to get time
setTimeout(function() {
var css_e = c_info[1].split(";"); //split to get css properties
for (var c=0; c<css_e.length; c++) {
var css_elem = css_e[c].split(":"); //split property and value
tempelem.style.setProperty(css_elem[0], css_elem[1]); //set value
}
}, c_info[0]); //set time
}(i)); // added this
}
I have this problem, where I can't seem to put the number of the "xq" into being the id for the buttons while using innerHTML.
Here's the code:
for (var xq = 0; xq < 3; xq++) {
var pass = xq;
tabletextvar = '<button id="buttontexto"; onclick="cancelObject(this.id);">Button</button>'
document.getElementById("buttontexto").innerHTML = pass;
}
document.getElementById("tabletext").innerHTML = tabletextvar;
Button ID ends up being "buttontexto" when I really want it to be what innerHTML. It could be that you can't have another innerHTML inside an innerHTML.
Any tips or fixes would be appreciated
If you want to have 3 buttons with id 1,2 and 3 then you need to append them, just using a variable inside the loop will override it and when the loop is over it will have the last value. You need to have a concatenated string.
var buttons = [];
for (var xq = 0; xq < 3; xq++) {
buttons.push('<button id="',xq,'" onclick="cancelObject(this.id);">',xq,"</button>")
}
document.getElementById("tabletext").innerHTML = buttons.join('');
Demo: Fiddle