I am a beginner in javascript, I am learning arrays. I am working on creating a html interface with javascript to use parallel arrays to obtain a users name and numeric value for each user (Score) I am stuck on understanding how I can save users input in each of the new arrays I created for each input. I have a button to save each name and score entry then I want to create a summary output that will check each score input and pass it through a loop to assign it a category such as A, B, C. I haven't gotten that far as I am confused on how to store each input in their array. The examples provided to me and the ones I found use predetermined values vs user input. This is what I have so far.
<h1>Grades</h1>
</header>
<br>
<p><b>Student Name:</b></p>
<input id="inp" type="text">
<br>
<br>
<p><b>Test Score:</b></p>
<input id="inps" type="text">
<br>
<br>
<br>
<button type="button" onclick="enter()">Enter</button>
<br>
<br>
<button type="button" onclick="summ()">Summary</button>
<br>
<p id="iop"></p>
<br>
<script>
var studentArr = new Array();
var scoreArr = new Array();
function enter() {
var studentName = document.getElementById("inp").value;
studentArr.push(inp);
var stuval = "";
for(i=0; i < studentArr.length; i++)
{
stuval = stuval + studentArr[i] + "<br/>";
}
document.getElementById("iop").innerHTML = stuval;
var studentScore = document.getElementById("inps").value;
scoreArr.push(inps);
var scoreval = "";
for(i=0; i < scoreArr.length; i++)
{
scoreval = scoreval + scoreArr[i] + "<br/>";
}
}
</script>
I belive more easier way exists:
var students = new Array();
function enter() {
students.push({
name: document.getElementById("inp").value,
score: document.getElementById("inps").value
});
show();
}
function show() {
document.getElementById("iop").innerHTML = "";
students.forEach(x => {
document.getElementById("iop").innerHTML += x.name + "<br/>";
});
}
You aren't using the right variable when pushing to your array here
studentArr.push(inp);
and here
scoreArr.push(inps);
Those variables do not exist in your code. You've defined 'studentName' and 'studentScore' so use them and you should have some data in your arrays.
Related
I don't know javascript much at all, I just like making lists for myself. I am currently trying to create a html page that I can keep track of characters from my favorite game, but I have run across a couple of problems I don't know how to solve.
<form name="inputNightlife" id="inputNightlife">
<h2>Nightlife</h2>
<label for="traits"><b>Traits:</b></label><br>
<select multiple="true" name="traits" id="traits">
<option value="Cologne">Cologne</option>
<option value="Stink">Stink</option>
<option value="Fatness">Fatness</option>
<option value="Fitness">Fitness</option>
</select>
<label for="turnOns"><b>Turn Ons:</b></label><br>
<select multiple="true" name="turnOns" id="turnOns">
<option value="Blonde Hair">Blonde Hair</option>
<option value="Red Hair">Red Hair</option>
<option value="Brown Hair">Brown Hair</option>
<option value="Black Hair">Black Hair</option>
</select>
<p>Select all that apply.</p>
<nav id="box8" class="hide"><table id="menu3"><tr><td rowspan="2" id="soft">
<textarea name="source8" onclick="this.focus();this.select()" cols="40" rows="3" id="result">
</textarea></td><td>
<input type="button" value="Get Code!" onclick="javascript:generateNightlife();"></td>
<td rowspan="2" id="softA">
<img src="./forSCV/icons/nightlife.png" alt="Nightlife" title="Nightlife" id="arrow" onclick="toggle('box8');">
</td></tr><tr><td>
<input type="button" value="Test Code" onclick="javascript:displayNightlife(this.form);">
</td></tr></table></nav></form>
When I click the button, the document.results.endresults.value appears in the text area. I can then copy the results, and save them as html. This is intended to be a page generator (the best I can come up with).
I am not sure how to make traits and turnOns automatically create an array (with spaces) of the chosen options that will then print in the document.result.endresult.value. I did find several different ways to create an array from the forms, but not how to then get it to go into the document.result.endresult.value.
One way Google. And another way Google
Adding...
Ok, I reworked my html to include names and id's, and I found a little better page generator, so I was trying to get that to work. Now I have tried this.
function byId(idStr){return document.getElementById(idStr);}
function getFormValues() {
var traitsSelectElem = byId('traits');
var turnOnsSelectElem = byId('turnOns');
var chosenTraits = getSelectedOptions(traitsSelectElem);
var chosenTurnOns = getSelectedOptions(turnOnsSelectElem);
var i, n, outputStr;
n = chosenTraits.length;
outputStr = '';
for (i = 0; i < n; i ++)
{
if (outputStr != ".")
outputStr += ", ";
outputStr += chosenTraits[i].value;
}
byId('traitsOutput').innerText = outputStr;
n = chosenTurnOns.length;
outputStr = '';
for (i = 0; i < n; i++)
{
if (outputStr != '.')
outputStr += ', ';
outputStr += chosenTurnOns[i].value;
}
byId('turnOnsOutput').innerText = outputStr;
}
function getSelectedOptions(selectElem) {
var i, nOptions = selectElem.options.length;
var result = [];
for (i = 0; i < nOptions; i++)
{
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.option[i].value
}
);
}
}
return result;
}
function generateNightlife() {
//nightlife
var traits = getFormValues();
var turnOns = getFormValues();
turnOff = document.inputNightlife.turnOff.value;
perfumeDuration = document.inputNightlife.perfumeDuration.value;
lovePotion = document.inputNightlife.lovePotion.value;
outputNightlife = "<a name='nightlife'></a>\n<div id='easy'>\n<h2>Nightlife</h2>\n
<table class='ntlf'><tr><th>Traits:</th><td class='white'>"+traits+"
</td></tr><tr><th>Turn Ons:</th><td class='white'>"+turnOnsOutput+"</td></tr><tr><th>
Turn Offs:</th><td class='white'>"+turnOff+"</td></tr></table>\n<p class='up2'>Perfume
Duration: <span class='colorme'>"+perfumeDuration+"</span></p>\n<p>Love Potion Duration:
<span class='colorme'>"+lovePotion+"</span></p>\n</div>\n"
document.inputNightlife.source8.value = outputNightlife;
return outputNightlife;
}
When I test it with chrome it says it cannot set property of .innerText of null which I think is because I don't want it to go to a div. I would like the value returned back to function generateNightlife so that it can be added to the outputNightlife. I don't know how to do that, and I need some help.
Here's a fully worked example that will pull multiple selections from a select element, before going on to construct an array with them, and finally printing them to screen.
Either of the two tutes you linked to are okay - it's always hard to know what will be obvious, what will need explaining and what will rely on background information that may/may not have already been covered.
I've used a few different tricks here and there are many that are more sophisticated I've elected to eschew. I hope the comments make the operation clear, though would be happy to add clarification as needed. :)
Here's a runnable snippet:
function byId(idStr){return document.getElementById(idStr);}
function getFormValues()
{
// 1. get a reference to each of the select elemenets we wish to process
var mainMealSelectElem = byId('mainSelect');
var dessertSelectElem = byId('dessertSelect');
// 2. get an array of all of the selected options in each of our select elements
var chosenMains = getSelectedOptions(mainMealSelectElem);
var chosenSweets = getSelectedOptions(dessertSelectElem);
var i, n, outputStr;
n = chosenMains.length;
outputStr = '';
for (i=0; i<n; i++)
{
// only add a comma before an element if at least one element already exists
// this is how we do it when writing a list manually.
if (outputStr != '')
outputStr += ", ";
// grab the two values from the array we constructed using the getSelectedOptions function.
// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
// whatever we named them in the below function is what we need to use to access them here.
outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
}
// set the text content of the target span with the array of chosen stuff.
byId('mainsOutput').innerText = outputStr;
n = chosenSweets.length;
outputStr = '';
for (i=0; i<n; i++)
{
if (outputStr != '')
outputStr += ", ";
outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
}
byId('dessertsOutput').innerText = outputStr;
}
// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
// aloop counter and the total number of iterations required
var i, nOptions = selectElem.options.length;
// the empty result array
var result = [];
// loop through all the options this select element has
for (i=0; i<nOptions; i++)
{
// if the current option is selected, we'll need to extract it's info and add it to the output array
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.options[i].value,
textLabel: selectElem.options[i].label
}
);
}
}
return result;
}
div
{
display: inline-block;
}
.centered
{
text-align: center;
}
<div class='centered'>
<form>
<h2>Select the ones you like</h2>
<select id='mainSelect' multiple>
<option value='spag'>Spaghetti</option>
<option value='satay'>Peanut satay</option>
<option value='schnitz'>Chicken Schnitzel</option>
</select>
<select id='dessertSelect' multiple>
<option value='1'>Ice-cream</option>
<option value='2'>Fruit salad</option>
<option value='3'>Custard</option>
</select>
</form>
<br>
<button onclick='getFormValues()'>Get chosen values</button>
<hr>
</div>
<br>
<div>
Selected main-meals: <span id='mainsOutput'></span><br>
Selected desserts: <span id='dessertsOutput'></span><br>
</div>
And here's the full (copy/pastable) source:
<!doctype html>
<html>
<head>
<script>
function byId(idStr){return document.getElementById(idStr);}
function getFormValues()
{
// 1. get a reference to each of the select elemenets we wish to process
var mainMealSelectElem = byId('mainSelect');
var dessertSelectElem = byId('dessertSelect');
// 2. get an array of all of the selected options in each of our select elements
var chosenMains = getSelectedOptions(mainMealSelectElem);
var chosenSweets = getSelectedOptions(dessertSelectElem);
var i, n, outputStr;
n = chosenMains.length;
outputStr = '';
for (i=0; i<n; i++)
{
// only add a comma before an element if at least one element already exists
// this is how we do it when writing a list manually.
if (outputStr != '')
outputStr += ", ";
// grab the two values from the array we constructed using the getSelectedOptions function.
// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
// whatever we named them in the below function is what we need to use to access them here.
outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
}
// set the text content of the target span with the array of chosen stuff.
byId('mainsOutput').innerText = outputStr;
n = chosenSweets.length;
outputStr = '';
for (i=0; i<n; i++)
{
if (outputStr != '')
outputStr += ", ";
outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
}
byId('dessertsOutput').innerText = outputStr;
}
// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
// aloop counter and the total number of iterations required
var i, nOptions = selectElem.options.length;
// the empty result array
var result = [];
// loop through all the options this select element has
for (i=0; i<nOptions; i++)
{
// if the current option is selected, we'll need to extract it's info and add it to the output array
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.options[i].value,
textLabel: selectElem.options[i].label
}
);
}
}
return result;
}
</script>
<style>
div
{
display: inline-block;
}
.centered
{
text-align: center;
}
</style>
</head>
<body>
<div class='centered'>
<form>
<h2>Select the ones you like</h2>
<select id='mainSelect' multiple>
<option value='spag'>Spaghetti</option>
<option value='satay'>Peanut satay</option>
<option value='schnitz'>Chicken Schnitzel</option>
</select>
<select id='dessertSelect' multiple>
<option value='1'>Ice-cream</option>
<option value='2'>Fruit salad</option>
<option value='3'>Custard</option>
</select>
</form>
<br>
<button onclick='getFormValues()'>Get chosen values</button>
<hr>
</div>
<br>
<div>
Selected main-meals: <span id='mainsOutput'></span><br>
Selected desserts: <span id='dessertsOutput'></span><br>
</div>
</body>
</html>
I am trying to create an object and have the name of each object be unique. The objects will have a name, a number and a second number that is null (this I intend to calculate later).
Is it possible to have an object named after a variable of 1 then at the end of the function increase the variable so that the next object is 2?
I am being alerted the value of the id number and it comes out as NaN
In my fiddle, I have a button to append each object in the array to a list so I can inspect them. They come out as [ object Object ].
Should this be an object of objects instead of an array of objects if I later want to use the number field in each object to perform calculations?
The format I have my sample object in is what I believe I want to stick with (unless there is a reason to do it better another way) because it follows the example on w3schools.
What am I doing wrong?
Fiddle here.
HTML:
<input type="text" placeholder="Name" id="name"> <input type="text" placeholder="Number" id="number">
<br>
<button id="makeObject">Make Object</button>
<button id="show">Show Me The Objects</button>
<ul id="list"></ul>
JavaScript:
/*Sample ideal object
1 = {
name: John Doe
number: 52
newNumber: null
}
*/
var arrayOfObjects = [];
var id = 1;
$(document).ready(function(){
$('#makeObject').on('click', function(){
var number = (parseInt($('#Number').val()));
var name = $('#Name').val();
arrayOfObjects.push(id = {
number: number,
name: name,
newNumber: null
});
id++;
alert("The id is now: " + id);
$('#Number').val("");
$('#Name').val("");
});
$('#show').on('click', function(){
$('#list').html("");
for (i = 0; i < arrayOfObjects.length; i++) {
$('#list').append("<li>" + arrayOfObjects[i] + "</li>");
};
});
});
What you are looking for would be an object key, not its name (which cannot start with a number as Quantastical states)
Anyway, your assignment is a little weird. This way shoud be the way you intended it:
arrayOfObjects[id] = {
number: number,
name: name,
newNumber: null
};
have a look at http://jsfiddle.net/ej3z9ncd/3/ to confirm it's working
Object names are strings.
I realized that the unique name doesn't matter for the object itself, I just went with "student." Instead, I put the name of the student, which is unique, as a field within the object.
Fiddle here.
<input type="text" id="name" placeholder="Name">
<input type="text" id="score" placeholder="Score">
<br>
<br>
<button id="push">Push to Array</button>
<button id="show">Show</button>
<button id="doMath">Do Math</button>
<ul id="list"></ul>
<p id="sum"></p>
<p id="mean"></p>
CSS:
input:hover {
border: 1px solid black;
}
JavaScript:
var myArray = [];
var sumOfScores;
var mean;
$(document).ready(function () {
$('#push').on('click', function () {
var name = $('#name').val();
var score = parseInt($('#score').val());
myArray.push((student = {
name: name,
score: score,
newScore: null
}));
console.log(student);
$('#name').val("");
$('#score').val("");
});
$('#show').on('click', function () {
$('#list').html("");
for (i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i].name + " received a score of " + myArray[i].score + "</li>");
};
});
$('#doMath').on('click', function(){
sumOfScores = 0;
for (i = 0; i < myArray.length; i++) {
sumOfScores += myArray[i].score;
};
$('#sum').html("The sum is: " + sumOfScores);
mean = (sumOfScores / myArray.length);
$('#mean').html("The mean score is: " + mean);
});
});
I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/
I want to pass an array from one external .js file to another.
Each of these files works fine by themselves, but I am having a problem passing the array from pickClass.js to displayStudent.js, and getting the names and "remaining" value to display in the html file. I know it has something to do with how the arrays are declared, but I can't seem to get it to work properly.
The first file declares the array choice:
(masterStudentList.js):
var class1 = ['Brown, Abe','Drifter, Charlie','Freed, Eve'];
var class2 = ['Vole, Ug','Xylo, William','Zyzzyx, Yakob'];
The second picks which array to use based on the radio buttons (pickClass.js):
var classPicked = array(1);
function randomize(){
return (Math.round(Math.random())-0.5); }
function radioResult(){
var chooseClass = document.getElementsByName("chooseClass");
for (i = 0; i < chooseClass.length; i++){currentButton = chooseClass[i];
if (currentButton.checked){
var selectedButton = currentButton.value;
} // end if
} // end for
var output = document.getElementById("output");
var response = "You chose ";
response += selectedButton + "\n";
output.innerHTML = response;
chosenClass = new Array();
if (selectedButton == "class1")
{chosenClass = class1;}
else
{chosenClass = class2;}
var text = "";
var nametext = "";
var i;
for (i = 0; i < chosenClass.length; i++) {
text += chosenClass[i]+ ' / ';
}
var showText = "";
l = chosenClass.length;
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
//return = classPicked;
document.getElementById("classList").innerHTML = classPicked;
} // end function
This works properly.
I then want to pass "classPicked" to another .js file (displayStudent.js) which will randomize the student list, loop and display the students for a few seconds, and then end with one student name.
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5); }
function showBasket(){
mixedBasket = basket.sort( randOrd ); //randomize the array
var i = 0; // the index of the current item to show
document.getElementById("remaining").innerHTML = basket.length;
fruitDisplay = setInterval(function() {
document.getElementById('showStud')
.innerHTML = mixedBasket[i++]; // get the item and increment
if (i == mixedBasket.length) i = 0; // reset to first element if you've reached the end
}, 100); //speed to display items
var endFruitDisplay = setTimeout(function()
{ clearInterval(fruitDisplay);
var index = mixedBasket.indexOf(document.getElementById('showStud').innerHTML);
mixedBasket.splice(index,1);
}, 3500); //stop display after x milliseconds
}
Here is the html (master.html). It's just rough -- I'll be working on the layout later:
<html>
<head>
<script src="masterStudentList.js" type="text/javascript"></script>
<script src="pickClass.js" type="text/javascript"></script>
<script src="displayStudent.js" type="text/javascript"></script>
</head>
<body>
<h2>Choose Class</h2>
<form action = "">
<fieldset>
<input type = "radio"
name = "chooseClass"
id = "radSpoon"
value = "class1"
checked = "checked" />
<label for = "radSpoon">Class 1</label>
<input type = "radio"
name = "chooseClass"
id = "radFlower"
value = "class2" />
<label for = "radFlower">Class 2</label>
<button type = "button"
onclick = "radioResult()"> Choose Class
</button>
<div id = "output">
</fieldset>
</form>
</div>
<center>
<h1> <span id="chooseStud"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
Remaining: <span id = "remaining" ></span>
<p>
<button onclick="showFruitwithSound()">Choose Student</button>
</center>
pickedClassList = <p id = classList> </p>
</body>
</html>
You shouldn't use global variable like this (I encourage you to read more on this theme) and I'm not sure I understand what you're trying to do... but the solution of your issue should be to move the basket = classPicked; line into your showBasket method :
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
// whatever
}
should be :
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
basket = classPicked; //This is where the array should be passed
// whatever
}
This way, each time you call showBasket, this method will use the last value of classPicked.
Otherwise, basket will always keep the reference on the first value of classPicked.
Why ? because each time you assign a new Array to the basket variable (classPicked = Array(l);) instead of changing directly it's content by :
emptying it : while (classPicked.length > 0) { classPicked.pop(); }
and then adding new data : classPicked.concat(chosenClass)
You can't pass things to files; you could call a function defined in displayStudent.js, pass it classPicked, and have it assign it to basket.
I noticed this at the end of your second chunk of code ...
} // end function
This could indicate the classPicked is declared inside a function (I don't see one on the code). Because it is inside function scope, your set of code that is trying to use it cannot.
Push the declaraction of classPicked outside of the function.
var classPicked = Array(1);
function thisusesclasspicked() {
...
Also, please start indenting your code properly, it will become much easier to maintain and read.
UPDATE FROM COMMENTS:
I see the declaration now ...
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
... however, you are re-assigning the array with an element of one just before you attempt to make modifications to it ... You are emptying it there: classPicked = Array(l);
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.