User input stored in array using JavaScript - javascript

Hi guys i'm kinda new to javascript and for a while now, i've been struggeling with something that shouldnt be that hard. The thing that i'm trying to execute is to get user input stored in an array, and then get it to print the collected info into a specific div (later on i'm gonna try to create a table using the DOM and store the input there). But i cant get it to work, below is my code :) any suggestions?
JavaScript
function submitInfo(){
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.lenght; i++){
document.getElementById("theResult").innerHTML=myArray[i];
}
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="inl2a.css" />
<script type="text/javascript" src="inl2a.js"></script>
<title>Inlämning 2a</title>
</head>
<body>
<div id="inputFields">
<h3>Submit your fighters information:</h3>
Name:<br><br>
<input id="name" type="text" /><br><br>
Age:<br><br>
<input id="age" type="text" /><br><br>
Fighting style:<br><br>
<input id="fightingStyle" type="text" /><br><br>
Weight:<br><br>
<input id="weight" type="text" /><br><br>
<input id="button" value="Submit" type="button" onclick="submitInfo();" /><br><br>
</div>
<div id="theResult">
</div>
</body>
</html>

function submitInfo(){
var myArray = []; // problem 1
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.length; i++){ // problem 3
document.getElementById("theResult").innerHTML+=myArray[i]; // problem 2
}
}
you haven't initialized the array anywhere
you overwrite the innerHTML property so only the last value remains
you have a typo: lenght instead of length
You can also set the values directly in the array and no longer use the intermediary variables. Also, you can get theResult element once, outside of the loop:
function submitInfo(){
var myArray = []; // problem 1
myArray.push(document.getElementById("name").value);
myArray.push(document.getElementById("age").value);
myArray.push(document.getElementById("fightingStyle").value);
myArray.push(document.getElementById("weight").value);
var element = document.getElementById("theResult");
for(var i = 0; i<myArray.length; i++){
element.innerHTML += myArray[i]; // problem 2
}
}

suppose user inputs are title and name, then
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
You could put all of these in one array:
var m = [ title, name ];
then for title use,
document.getElementById(your_divID).innerText=m[0];
you can use textContent instead of innerText for mozilla support.

Related

Why isn't this JavaScript code executing?

Sorry, I'm a student and I can't figure out what is wrong with my code! When I click the buttons absolutely nothing happens. I've tried isolating each function and still nothing happens. I've been looking it over for ages trying to find a missing tag or a missing bracket or parentheses or something but I'm not finding it. It's meant to create a mini-blog simulation. You should be able to add an entry to the top of the list with the first function, and you should be able to delete an entry of your choice with the second function. Thank you for any help!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5 Activity</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Awesome NBA Blog! Each day, a sentence about the feats of a different legend!</h1>
<ol id="playerEntries">
<li>Michael Jordan: 6 Championship rings in 6 NBA Finals appearances.</li>
<li>Bill Russell: 11 time champion in a 13 year career, including one as a player/head coach.</li>
<li>Kobe Bryant: 5 Championships, 18-time All-Star.</li>
<li>Lebron James: Won a Championship and was the Finals MVP with 3 different teams.</li>
</ol>
<form action="">
Add a new entry:
<input type="text" name="newEntry" id="newEntrySpot" size="80">
<input type="submit" value="Submit" onclick="addEntry()"><br>
Delete an entry(which entry would you like to delete?)
<input type="number" name="entryNum" id="numToDelete">
<input type="button" value="Delete" onclick="deleteEntry()"><br>
</form>
<script type="text/javascript">
function addEntry() {
var newEntry = document.getElementById("newEntrySpot").value;
var newestEntry = document.createElement("li");
newestEntry.innerHTML = newEntry;
var blogList = document.getElementsByTagName("ol")[0];
var topEntry = document.querySelectorAll("#playerEntries li")[0];
blogList.insertBefore(newestEntry, topEntry);
}
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.getElementsByTagName("ol")[0];
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
var deletedPost = blogList.removeChild(postToDelete);
}
}
</script>
</body>
</html>
You have to replace
<input type="submit" value="Submit" onclick="addEntry()"><br>
with
<input type="button" value="Submit" onclick="addEntry()"><br>
otherwise the form will be submitted and the page will reload. You can also use the submit function of the form but will you have to use preventDefault.
Also to make the deleteEntry function works, you can't use document.getElementsByTagName("ol")[0]; since you can't use .length on an element. Here's another way to do it :
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.querySelectorAll("ol > li");
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
postToDelete.remove();
}
}

JS: change "var y = UNDEFINED" for "var y= blank space" with if

I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).
The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.
Here's a snippet to show the problem:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
if (y === undefined) {
y = " ";
}
document.getElementById('displayCell').innerHTML = x +" "+ y;
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:
index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined.
So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).
Any ideas?
Try
var x = document.getElementById('excel_table1').rows[0].cells[0].innerHTML;
var y = document.getElementById('excel_table1').rows[0].cells[1].innerHTML;
using rows instead of getElementsByTagName is cleaner.
Also note that the indexes for cells start from zero not 1, you probably only have 2 cells in your first row, but .cells[2].innerHTML tries to get the innerHTML of the 3rd cell which does not exist.
As others have pointed out, you're already using jQuery, so the easiest way to get the cell contents is to use a css selector to find the cells using the $ function, then call .html() to get the contents. A direct conversion of your current code to this approach could be:
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
This works in a way so that the $ function returns a jQuery object, which is essentially a set of elements, which can potentially be empty. Most jQuery functions are then designed to fail gracefully when called on an empty set. For instance, html will return undefined when invoked on an empty set, but it will not fail.
Note that it is not very robust to use the selector above, as it is obviously sensitive to the placement of the cells. It would be more maintainable to assign a class attribute to the cells that describes their content, and then select on that, e.g. something like
var name = $("#excel_table1 tr:nth-child(1) td.name").html()
So here's the answer that worked for me:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
if (y ===undefined)
{document.getElementById('displayCell').innerHTML = x ;}
else
{document.getElementById('displayCell').innerHTML = x +" "+ y;}
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>

Receive input numbers until the user enters a zero. Then output the highest. javascript

As the title suggests, i have to write a program where the user enters numbers and when the number entered is 0, it outputs the highest number which was entered. i've done most of it and i know there is only a little missing but i cant figure it out.
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8" />
<title></title>
<script style="text/javascript">
function numbers(){
var numbers = 0;
var outMessage = "";
var numbersArray = new Array(numbers);
do{
numbers = prompt('enter 0 to cancel', 0);
}while(isNaN(numbers));
var maxNum = Math.max.apply(null, arr);
alert(maxNum);
document.getElementById('result').innerHTML = maxNum;
}
</script>
<body>
<p>Numbers Exercise</p>
<p id="numbers"></p>
<input type="button" value="Start" onClick = "numbers();">
<label id='result' />
</body>
</html>
One of your issues is that you write var maxNum = Math.max.apply(null, arr); but you mean var maxNum = Math.max.apply(null, numbersArray);. I think that was just forgetting to change that array name.
Then in your do while you are checking NaN(numbers) which will always return false if they type in valid input. You want to check `!(NaN(numbers)) so the loop quits when the number is invalid
I then check if(numbers != 0) inside your do while, determining if you want to push it into an array using numbersArray.push(numbers) and if not then break the loop.
I created a JSFiddle of this: https://jsfiddle.net/4otwrnzL/
I think this does the job, do sure if this is what you want.
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8" />
<title></title>
<script style="text/javascript">
function numbers(){
var numbers = 0;
var outMessage = "";
var numbersArray = new Array(numbers);
do{
var number = prompt('enter 0 to cancel', 0);
numbersArray.push(number);
}while(isNaN(number)||number != 0);
var maxNum = Math.max.apply(null, numbersArray);
alert(maxNum);
document.getElementById('result').innerHTML = maxNum;
}
</script>
<body>
<p>Numbers Exercise</p>
<p id="numbers"></p>
<input type="button" value="Start" onClick = "numbers();">
<label id='result' />
</body>
</html>

dropdown menu in javascript with adding new elements

I am new in javascript and in this moment I am trying to use "Basic DOM and JS". I am doing a dropdown menu, what gets his elements from an array. There is an input field, where you can add new items into the array.I also made a button to push and save the item into array and make the dropdown automatically with DOM.
My problem if you push the button, it makes always a new dropdown menu. Otherwise the array works good, but I need just one dropdown menu with the items of array. I think this problem comes out at listing with ul li too. Here is my whole code and thanks for helping
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
var menu = document.createElement("select");
document.body.appendChild(menu);
for(var i = 0; i<select.length; i++){
var option = document.createElement("option");
var text = document.createTextNode(select[i]);
option.appendChild(text);
menu.appendChild(option);
}
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
You are creating the select tag every time array() is invoked. So create select tag once and rest of the time create option tag when array() is invoked. Here is your solution.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
var selectIsCreated = false;
var menu;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
if(!selectIsCreated){
menu = document.createElement("select");
document.body.appendChild(menu);
selectIsCreated = true;
}
var option = document.createElement("option");
var text = document.createTextNode(select[select.length-1]);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
So Suman already answered your question, but in terms of simplifying the code or the approach, I think you could take a different approach by removing the use of the "select" array entirely. The array isn't necessary to add in the value to the select list, as you can get everything you need from the input element, so you just need to work on adding the option to the actual select DOM element.
Here is the desired functionality re-factored a bit with this in mind.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
function createSelect() {
select = document.createElement('select');
select.id = 'select';
document.body.appendChild(select);
return document.getElementById('select');
}
function addOption(){
var input = document.getElementById("input");
var value = input.value;
// This will attempt to grab the 'select' element, but if it finds
// that it doesn't exist (i.e. getElementById returns a "falsy" value)
// then it will return the value of the createSelect function.
// This could also be done with more explicit "if" statements
var menu = document.getElementById('select') || createSelect();
// The same effect could be achieved by running this code:
/*
var menu = document.getElementById('select');
// If the select element hasn't been created/added to the page yet,
// then the above call to getElementById will return a "falsy" value,
// i.e. a value that isn't a strict boolean type but JS will treat it
// as "false".
if (!menu) {
menu = createSelect();
}
*/
var option = document.createElement("option");
var text = document.createTextNode(value);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<!--
I've renamed the array() function since we don't even
have an array anymore
-->
<input onclick="addOption()" type="button" value="Add">
</body>
</html>
You can see this in action on this jsFiddle

Dynamic input length for all input fields

I have been looking for a way to dynamically change the length of the input field in a HTML form.
I have come across the following:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
<script type="text/javascript">
window.onload = function() {
thelink = document.getElementById('MyLink');
linksize = thelink.value.length;
if (linksize < 10) thelink.size = 10;
if (linksize > 50) thelink.size = 50;
}
</script>
</head>
<body>
<input id="MyLink" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
</body>
</html>
How would i adapt this to work for every input field on my very large form?
Thanks
For your case, I would give the required minimum and maximum as data-*= attributes,
For example:
<input id="MyLink" data-min="10" data-max="50" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
Then iterate through the inputs in your form, drawing from the data attributes, and checking for the required length.
You can collect elements in a collection, either take them from the whole document or some its containing element. You can use e.g. getElementsByTagName('input');, getElementsByName('myInput'); or getElementsByClassName('shapable_input'); methods, if tags have set the corresponding attribute:
<input name="myInput" class="shapable_input" value="...." />
and then all collected tags can be tested in the loop:
window.onload = function() {
var links = document.getElementsByTagName('input');
//var linksc = links.getElementsByClassName('link');
var i, thelink, linksize;
for (i = 0; i < links.length; i++) {
thelink = links[i];
linksize = thelink.value.length;
if (linksize <= 10) {
thelink.size = 10;
}
if (linksize > 10) {
thelink.size = 50;
}
}
};
example

Categories

Resources