Trying to make a Javascript Array Print out using Inputted value - javascript

my first question would be am I correctly getting the value from id "textOne" into my var a? Second, I am supposed to have my while loop run "while the variable that represents the index value that I want to print" is greater than or equal to the minimum array value. Is my While loop condition correct?
I just basically want this to print out the correct number of indexes within my array based on the user input ranging from 1-5.
Thanks in advance.
<input type="button" value="Click" onclick="JobDuties()" />
to see my top
<input type="text" id="textOne" />
job duties here
<p id="answer"></p>
<script type="text/javascript">
function JobDuties()
{
var x = "";
var a = document.getElementById('textOne').value;
var b = a - 1;
myduties = new Array();
myduties[0] = "Saab";
myduties[1] = "Volvo";
myduties[2] = "BMW";
myduties[3] = "Toyota";
myduties[4] = "Ford";
}
while (a>=0)
{
x = x + myduties[b];
document.getElementById("answer").innerHTML=x;
}
</script>

I will assume you want to print out the correct array value, not arrays, as there are not multiple. PS> People do not like homework questions on here if you do not say so because answering completely does not help you learn. I will partially answer.
You do not need to loop through the array to look up a value.
You can initialize the array more easily.
["Saab", "Volvo", ... ]
You can reference a position in the array, like so for Saab as it is zero indexed
myduties[0]
If you are going to loop, which I am still not seeing why you would do that.
Code below:
var i = 1; //The variable you increment up to the use input variable a
while(i =< myduties.length){
if(i == a){ //if i and a are same then that position
//in the array will have the car type the user requested
myduties[i-1] //and set it to the DOM or document element similar to what you already had
}
i = i + 1; //Increment i towards the one less than the length of the array
}
Not perfect or checked but that should provide you with some pointers.

Related

Is there a function for retrieving last array's element value?

I have an array of inputs that accepts a range of 0 and 1. var array = [0,1,0,0,1];//that is not static
Is there a function for retrieving the last element of the array?
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b= 0;
let l = array.length;
for(b=0; b<l; b++)
if(array [l-1]==0)
document.getElementById('print').textContent = 'Last element is 0';
}//end function
P.S: I am editing this old and bad question in order to get give the community time to re-evaluate it.
Please try this
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b=0;
if(array[array.length-1] == 0)
document.getElementById('print').textContent = 'Last element is 0';
}
You could take the length of the array and reduce it by 1 and take the element at this position for checking. You need no loop for the access.
if (array[array.length - 1] === 0) {
Doesn't really need a function, you can even write it inline.
function last_element_is_0(arr){
return !arr[arr.length -1]
}
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user input
if(last_element_is_0(array))
document.getElementById('print').textContent = 'Last element is 0';
}

How to increment a variable after button press

I was wondering how I could increase a variable when a button is clicked. here is my code. Can somebody point me in the right direction? thanks.
I am thinking when the button1 is clicked it will increase team 1's score by like 10, and will decrease if it is clicked again if that is necessary.
var Team2;
var Team2 == 0;
var Team1;
var Team1 == 0;
document.getElementById("calc").innerHTML = Team1;
function clicked(button1)
{
var team1 = team1 + 45
}
</SCRIPT>
<p>
Players for Team 1
First, the variable part: suppose you define a variable var value = 0. To increase it by 10, you can write value = value + 10, but in JavaScript this can be shorten to:
value += 10
The same way, to decrease it, just write value -= 10.
To call the function, you write onClick="someFunction()" (not the best practice), and then you define the function:
function someFunction(){
value += 10
};
This is the working fiddle: https://jsfiddle.net/gerardofurtado/6qh1yhsj/
If you want to see how to do the same thing without the onClick="someFunction()" part, here is a fiddle: https://jsfiddle.net/gerardofurtado/wff8mph3/
PS: I see that in your code you wrote var team2 == 0. In JavaScript, two equal signs make a comparison operator: http://www.w3schools.com/js/js_comparisons.asp
PS2: In JavaScript, you have to mind the scope. Once you defined the var team1, you can change it inside the function just by writing team1. But if you do as you did:
function someFunction(){
var team1 = team1 + 45
};
This team1 is not the same previous variable team1 defined outside the function. It's a different variable. And, as the team1 to the right of the equal sign is not defined, this will return a NaN (Not-A-Number).

Javascript: Arrays and For Loop Basics

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.
I came across this example in the source I'm using for studying and the for loop looks strange to me:
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Would someone mind explaining why there is a [0] and [1] near the end of these statements?
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
A clearer way to write this statement is this:
var parts = cookiearray[i].split('='),
name = parts[0],
value = parts[1];
That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.
String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).
Those are used to access the items in the arrays that you create.
It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:
var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];
The code is splitting each cookie pair key=value into key ([0]) and value ([1]).
A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.
I'll give you a relevant and nonrelevant (simplified) example:
Nonrelevant:
// Increase the value of x and print the new value to the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If you take a close look it's really rather logical. You define an iteration variable i, tell it when to stop (i < 20...so stop if i = 20), how to progress with each iteration (i++ or i + 1).
So the code will enter the loop when i = 0...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1, x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.
Relevant:
// Given array of length 10, print each element to the console
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0, our code prints the element of the array at cookiearray[0]...when i = 1 it prints cookiearray[1]...so on and so forth for the entirety of the array.
What may confuse you in the example is the split function. Split returns an array. So this line:
name = cookiearray[i].split('=')[0];
...actually means assign the first element of the new array created from splitting the cookiearray's element at position i.
Let's assume that cookiearray[0] = "Hello=World". When i = 0, our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

Taking values from one array and to obtain a different value from a separate array. JavaScript

I'm not entirely sure how to word what I am asking here but I have an assignment where two arrays are present. One array contains strings which are the makes of cars. The second array contains the price of that car. The program is to run a for loop through the first array, identify the values that contain that specific make, and then add the prices up in the second array.
This is what I have:
<html>
<script>
make = new Array();
make[0]='honda';
make[1]='toyota';
make[2]='pontiac';
make[3]='honda';
price = new Array();
price[0]=35000;
price[1]=35000;
price[2]=40000;
price[3]=45000;
function totalByColor(parameter1){
total=0;
for(i=0;i<make.length;i++){
if(make[i]=='honda'){
for(b=0;b<price.length;b++){
make[i]=price[b]; //This is where I need help!
total = total + price[b];
};
} else {
};
return total;
};
return total;
};
</script>
<input type='button' value='test' onclick="alert('Return = '+totalByColor('honda'))">
</html>
So I need to set the program up to identify the value in make[0] is relevant to price[0] and make[3] is relevant to price[3], so price[0] and price[3] can be added together in the second for loop, any one have any idea? Thanks in advance for any help or guidance on this issue
If the indices are the same, you don't need another for loop; just use your var i:
var total = 0;
for (var i = 0, len = make.length; i < len; i++) {
if (make[i] === 'honda') {
total += price[i];
}
}
return total;
total should be a local variable, and is defined as 0 first, then you can use += to redefine total as total + price[i]. It's shorthand for total = total + price[i]. I also included var before the i in the for loop, because it should be local, and not global; and, you don't need so many semi-colons: after brackets for example } (so long as it's not an object you are defining). One more thing is that you have a return statement in your for loop, which means it will only loop over one value before ending the function. The return statement should be after the for loop.

JavaScript array.sort() Issue

drafting up a quick listing tool to list local kids baseball teams. Takes a couple of inputs and writes to a text field. There's some validation and whatnot too, but that's out of scope and doesn't seem to be impacting things.
Problem is, I'm having trouble figuring out how to "capture" the existing text, add the new inputs and sort the whole lot, before writing the new result to the paragraph element (effectively replacing it).
So far I have:
var LeagueTeams = [];
var IndividualTeam = '';
LeagueTeams.push(document.forms[0].TeamName.value);
LeagueTeams.push(document.getElementById('TeamList')
LeagueTeams = LeagueTeams.sort();
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
What I end up getting is my input, and then an array of my input PLUS the previous contents, with a couple of line breaks. Setting the operator to = instead of =+ stops it from printing to the array at all.
i.e.
Enter: a
Text area: a
Then enter: b
Text area: a ab
(etc)
OK, now that we have a better idea of what you're trying to do, here's some code that will do that:
HTML:
<label>Enter Team Name: <input id="newTeam" type="text"></label>
<button id="add">Add</button><br>
All Teams:<br>
<textarea id="allTeams" rows="40" cols="40"></textarea>
Javascript (plain javascript, no framework, called after page is loaded):
var teamList = ["Dodgers", "Mets", "Giants"];
document.getElementById("add").onclick = function() {
var input = document.getElementById("newTeam");
if (input.value) {
teamList.push(input.value);
}
updateTeamList();
input.value = "";
}
function updateTeamList() {
teamList.sort();
var o = document.getElementById("allTeams");
o.value = teamList.join("\n");
}
updateTeamList();
And, you can see it working here: http://jsfiddle.net/jfriend00/HkhsL/
Comments on your existing code:
I'm not sure I understand what you're trying to do overall, but do you realize that this loop is going to have problems:
for (j = 0; j < LeagueTeams.length; j++) {
IndividualTeam = LeagueTeams.pop();
IndividualTeam = IndividualTeam + '' + \n;
document.forms[0].TeamName.value += IndividualTeam;
}
Each time you do LeagueTeams.pop() you are reducing the length of the array and you're continually comparing to LeagueTeams.length in the for loop. This will only get half way through the array because each time through the loop, you increment j and decrement LeagueTeams.length which means you'll only get half way through the array.
If you intend to iterate all the way through the array in your for loop, you should use this version that gets the length once initially and simplifies the code in the loop:
for (j = 0, len = LeagueTeams.length; j < len; j++) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
or perhaps even better, this version that doesn't even use j:
while (LeagueTeams.length > 0) {
document.forms[0].TeamName.value += LeagueTeams.pop() + '\n';
}
Then further, I see that you're trying to use LeagueTeams.sort() on an array that has both strings in it and DOM object references. What are you trying to do with that sort because the built-in sort function does a lexigraphical sort (e.g. alpha) which will do something odd with a DOM reference (probably sort by whatever toString() returns which may be object type)?
If you want to sort the input by team name, then you would need to put both team name and the DOM reference into an object, insert that object into the array as one unit and then use a custom sort function that would sort by the name in the object. As your code is written above, you see to be using document.getElementById('TeamList') which is the same for all teams so I'm not sure why you're putting it into the array at all.
If you can show your HTML and a more complete version of your code, we could help further. What you have above is just a non-working piece of code and we don't know what your HTML looks like that it's trying to operate on.
FYI, there are several syntax errors in the code you posted, so this can't be running code:
Missing paren at the end of this: LeagueTeams.push(document.getElementById('TeamList'))
Missing quotes around \n: IndividualTeam = IndividualTeam + '' + '\n';
If you are just trying to make a list of the teams, try something like:
<script type="text/javascript">
function addTeam(form) {
var para = document.getElementById('teamList');
var teams = para.innerHTML.split(/<br\s*[\\]?>/);
teams.push(form.teamName.value);
para.innerHTML = teams.sort().join('<br>');
}
</script>
<form action="">
<input type="text" name="teamName">
<input type="button" value="Add team" onclick="addTeam(this.form)">
</form>
<p id="teamList"></p>
You may be using different elements or layout, but the strategy should be about the same. If you are making a set of options for a select, things are a little easier.

Categories