storing user input in array - javascript

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.

Related

How do I print the a list of arrays from multiple text input using javascript?

Code description:
Clicking the button (id=a1) will add text input brackets (e.g. 3 clicks will give 3 text input). I am trying to get the values from all the text inputs and show it on the page,however, my code only prints out the value from the first text input. How can I get it to print all the values from all the text inputs?
// add textbox function onclick
var a1 = 0;
var x = [];
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' id='a1' value=''/><br />";
a1 += 1;
}
//Adds inout into list var x
function pushData()
{
//get value from input text
var inputText = document.getElementById('a1').value;
//append data to the array
x.push(inputText);
var pval = x;
document.getElementById('pText').innerHTML = pval;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>
I have made a couple of improvements to your code, that you can see in the code snippet below.
The essential changes you need to make would be,
Use a class selector instead of ID selector. When you invoke document.getElementById it returns one element having the provided ID. Instead you want all the textboxes that were dynamically created. So you can add a CSS class to the input at the time of creation (class='magnitude-input') and afterwards use it to get all inputs (document.getElementsByClassName('magnitude-input')).
Once you get a list of inputs, you can iterate over them and collect their values into an array (x in your case). Note that x should be definied within the function pushData, otherwise it will retain values previously added to it.
Also, the variable a1 seems unnecessary after that. So you can remove it.
// add textbox function onclick
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' class='magnitude-input' value=''/><br />";
}
//Adds inout into list var x
function pushData() {
var x = [];
//get value from input text
var inputs = document.getElementsByClassName('magnitude-input');
for(var i = 0; i < inputs.length; i++) {
var inputText = inputs[i].value;
//append data to the array
x.push(inputText);
}
document.getElementById('pText').innerHTML = x;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>

Display JavaScript Array Elements inside Div

There's a textarea in the webpage to enable user to add address. User may enter 'n' number of addresses by clicking on the Add Address button. When user clicks on the Display Address button, all the addresses entered should be displayed inside the "result" div tag as per following format:
Address 1
Address entered by user
Address 2
Address entered by user
.....
Here's the HTML code
<div id="body" align="left">
<h2>Address Details</h2>
Enter the Address : <textarea id="address"></textarea><br>
<button id="add" onclick="addAddress();">Add Address</button>
<button id="display" onclick="displayAddress();">Display Address</button>
</div>
<div id="result" align="right"></div>
Here's the JS function to accept the address and store it in an array:
var address = [];
function addAddress(){
var addr = document.getElementById("address");
if(addr.value.replace(/^\s+|\s+$/gm,'') !=="") {
address.push(addr.value);
addr.value = "";
}
}
And here's the function to display the address inside the result div in the specified format (which does not work)
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
}
result.innerHTML = addrno[i]+"<br>"+display[i]+"<br>";
}
Any help would be greatly appreciated.
Hm, if I understand your question correctly, you could try doing something like this:
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>";
}
}
All I changed was move result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>"; inside your for loop so it can access the variable i uppon each itteration and changed it so it added the string addrno[i]+"<br>"+display[i]+"<br>"; to the DOM by using += on result.innerHTML rather than = (so it doesn't override it, rather it appends to it)

javascript parallel array with user input for name and numeric value

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.

Store values from dynamically generated text boxes into array

I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
{
$('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');
InputtedValue = $('#SemesterSubjectsSelection').val();
SubjectsNames = [];
for (i = 0; i < InputtedValue; i++)
{
TextBoxContainer1 = $('#DynamicTextBoxContainer');
TextBoxContainer2 = $('#DynamicTextBoxContainer2');
$('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
$('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
SubjectsNames['SubjectTextBoxes'+i];
}
$('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
}
$.fn.CreateTimeTable = function()
{
for (x = 0; x < i; x++)
{
localStorage.setItem("Main"+x, +SubjectsNames[i]);
}
}
I am also posting screenshot for better understanding
I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).
$(function() {
$.fn.timeTables = function(config) {
// prepare variables with jQuery objects, based on selectors provided in config object
var numberOfSubjectsTextBox = $(config.numberOfSubjects);
var subjectsDiv = $(config.subjects);
var facultiesDiv = $(config.faculties);
var prepareButton = $(config.prepareButton);
var numberOfSubjects = 0;
prepareButton.click(function() {
// read number of subjects from the textbox - some validation should be added here
numberOfSubjects = +numberOfSubjectsTextBox.val();
// clear subjects and faculties div from any text boxes there
subjectsDiv.empty();
facultiesDiv.empty();
// create new text boxes for each subject and append them to proper div
// TODO: these inputs could be stored in arrays and used later
for (var i = 0; i < numberOfSubjects; i++) {
$('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
$('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
}
});
function generate() {
// prepare result array
var result = [];
// get all text boxes from subjects and faculties divs
var subjectTextBoxes = subjectsDiv.find('input');
var facultiesTextBoxes = facultiesDiv.find('input');
// read subject and faculty for each subject - numberOfSubjects variable stores proper value
for (var i = 0; i < numberOfSubjects; i++) {
result.push({
subject: $(subjectTextBoxes[i]).val(),
faculty: $(facultiesTextBoxes[i]).val()
});
}
return result;
}
// expose generate function outside the plugin
return {
generate: generate
};
};
var tt = $('#container').timeTables({
numberOfSubjects: '#numberOfSubjects',
subjects: '#subjects',
faculties: '#faculties',
prepareButton: '#prepare'
});
$('#generate').click(function() {
// generate result and 'print' it to result div
var times = tt.generate();
var result = $('#result');
result.empty();
for (var i = 0; i < times.length; i++) {
$('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result);
}
});
});
#content div {
float: left;
}
#content div input {
display: block;
}
#footer {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="header">
<input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
<button id="prepare">
Prepare
</button>
</div>
<div id="content">
<div id="subjects">
</div>
<div id="faculties">
</div>
</div>
</div>
<div id="footer">
<button id="generate">Generate</button>
<div id="result">
</div>
</div>

Getting values from list<String> , split them and then slice them by parts, using JavaScript

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/

Categories

Resources