How do I dynamically change a key in a for loop - javascript

I want to be able to change the key in a for loop, it's hard to explain what I need so I made a demo based on the https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for play ground.
I need to be able to swap the keys depending on logic because the array data keys will alter depending on the json feed therefore it won't be possible to hard code the keys.
Thanks in advance
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
var keyToChoose = "name"; /// or I could choose "colour"
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

You use it like this.
text += cars[i][keyToChoose] + "<br>";
now it depends on the value of the variable keyToChoose.

You can use a global variable to decide your key.
<script>
// 1 = name , 2 = colour
var currentKey = 1;
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
// the key is chosen based on the currentKey which can be made a global variable and changed dynamically.
var keyToChoose = currentKey === 1 ? "name" : "colour";
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>

Related

Javascript Higher Order Functions and DOM

I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/

Why does this for loop not display in my div using JavaScript?

I want to display the content in my div but the code won't work. Please show me how to do it.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for (i = 0; i < 11; i++) {
var disp = "the number is " + i;
console.log(disp);
}
disp = document.getElementById("display").innerHTML;
</script>
</body>
</html>
How can I get the loop to display my variable in my selected div? Which part of my code is wrong? please help.
Tehre are multiple problems
<p id="display"></p>
<script>
var i;
//initialize the value
var disp = '';
for (i = 0; i < 11; i++) {
//concatenate the value of disp so that new value will be added to the previous content other wise the values will be overwritten
disp += "the number is " + i;
console.log(disp);
}
//assign value of disp to the elemet innerHTML
document.getElementById("display").innerHTML = disp;
</script>
Set the innerHTML inside the for loop.
for (var i = 0; i < 11; i++) {
var disp = "the number is " + i;
document.getElementById("display").innerHTML = disp;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
IF you want to display all the content at once
var disp = ''; // Assign empty string
for (var i = 0; i < 11; i++) {
disp += " the number is " + i; // Concat message
}
document.getElementById("display").innerHTML = disp; // Add into html
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because you never write anything to your HTML page. You just display it in your console. And later you assign the HTML content of the #display element to the variable disp, which doesn't make any sense:
disp = document.getElementById("display").innerHTML;
This is how it will work
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
// This just writes to the javascript console
console.log(disp);
// This writes in the #display element on your page
document.getElementById("display").innerHTML += disp + '<br>';
}
</script>
</body>
</html>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
console.log(disp);
}
document.getElementById("display").innerHTML = disp;
Something like this should be fine
function createDivs(){
var pContainer = document.getElementById("display");
var i;
for(i = 0; i < 11; i++){
var message = "the number is " + i;
console.log(message);
var element = document.createElement("div");
element.innerHTML = message;
pContainer.appendChild(element);
}
disp = document.getElementById("display").innerHTML;
};
createDivs();

SyntaxError: invalid flag after regular expression and white screen

I can't figure out why my page will not work. It just gives me a white screen when I try to load it. Is there a code I am missing? I don't know if my spaces matter either. Here is my code:
<!DOCTYPE html>
<html>
<head><body>
<title>Initializing an Array</title>
<style type="text/css">
table {width:10em}
th {text-align:left}
</style>
<script language="JavaScript">
<!--
{//create (declare) two new arrays
var n1=new Array(5); //allocate five-element Array
var n2=new Array (); //allocate empty Array
//assign values to each element of Array n1
for ( var i = 0; i <n1.length; ++i )
n1[ i ] = i;
//create and initialize five elements in Array n2
for ( i=0; i <5; ++i )
n2[ i ] = i;
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
//output the heading followed by a two-column table
//containing subscripts and elements of "theArray"
function outputArray (heading,theArray)}
{
document.writeln("<h2>"+heading+"</h2>");
document.writeln("table border=\"1\"");
document.writeln("<thead><th>Subscripts</th>"+"<th>Value</th></thead> <tbody>");
//output the subscript and value of each array element
for ( var i = 0; i <theArray.length; i++ )
document.writeln("<tr><td>+i+"</td><td>"+theArray[i]+"</td></tr>");
document.writeln("/tbody></table>");
} //end function outputArray
//-->
</script>
</head></body>
</html>
Please help! Thanks.
You have broken HTML and invalid Javascript.
<script language="JavaScript">
For your DOCTYPE of html, there is no need to specify any attributes to a <script> tag except src, and that is only needed if you are loading an external script file. And there is no attribute language. You likely meant type="text/javascript" but that is the default and therefore redundant.
<!--
You can't have HTML comments inside a <script> block. You are telling the browser that what is inside the <script> block is Javascript, then you putting invalid javascript. There will likely be errors displayed in the console.
Your example, tidied up, would look something like this:
<script>
// create (declare) two new arrays
var n1 = new Array(5); //allocate five-element Array
var n2 = new Array(); //allocate empty Array
// assign values to each element of Array n1
for (var i = 0; i < n1.length; ++i) {
n1[ i ] = i;
}
// create and initialize five elements in Array n2
for (i=0; i < 5; ++i) {
n2[ i ] = i;
}
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
// output the heading followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray (heading, theArray) {
var html = '<h2>' + heading + '</h2>';
html += '<table border="1">';
html += '<thead><th>Subscripts</th><th>Value</th></thead>';
html += '<tbody>';
// output the subscript and value of each array element
for (var i = 0; i < theArray.length; i++) {
html += '<tr><td>' + i + '</td><td>' + theArray[i] + '</td></tr>';
}
html += '</tbody></table>';
var div = document.createElement('div');
div.innerHTML = html;
document.body.appendChild(div);
}
</script>
You forgot quote " and on the next line < in </tbody> in last for loop.
document.writeln("<tr><td>"+i+"</td><td>"+theArray[i]+"</td></tr>");
^
document.writeln("</tbody></table>");
^
Of course nothing gets displayed, the base HTML layout is completely wrong.
You wrote :
<head>
<body>
(all the stuff)
</head>
</body>
It should be :
<head>
(scripts.....)
</head>
<body>
(HTML....)
</body>

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Any ideas on what is wrong with this javascript code?

I have the code below. The purpose of the code is to grab all the values stored in the local storage and display them in two HTML elements with ids of 'title' and 'textLoc'. 'title' is an <input type="text"> and 'textLoc' is a <textarea>. I want the values to be stored in the <textarea> and the keys to be stored in the <input type="text">. The values are being stored correctly but the keys are not. Any ideas on why this would be?
var tests = [];
var titles = [];
var finalTests = "";
var key, value;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
tests.push(value);
titles.push(key);
finalTests += "<tr><td><a class=\"dashlinks\" href=\"javascript:void\" onclick=\"rememberTest("+i+")\">" + key + "</a></td></tr>";
}
for (i=0; i<tests.length; i++) {
document.getElementById('title').innerHTML = titles[i];
document.getElementById('textLoc').innerHTML = tests[i];
}
You should use document.getElementById('title').value and document.getElementById('textLoc').value. Also it seems like you are doing nothing with finalTests after you store it.
You should be appending the string to the text area:
document.getElementById('title').innerHTML = document.getElementById('title').innerHTML + titles[i] + '\n';

Categories

Resources