Javascript array return "a"? - javascript

I wrote this piece with expectancy to store name and score in each and every array element.
Expected output:
var students = [
['David', 80],
['Dane', 77],
['Dick', 88],
['Donald', 95],
['Dean', 68]
];
However, I stumble upon assigning the second value in an array element... In codepen.io, the value returned is "a".
HTML:
name: <input type="text" id="namebox"><br><br>
score: <input type="text" id="scorebox"><br><br>
<input type="button" value="Add" onclick="addStudent()">
<input type="button" value="Display" onclick="displayArray()">
Javascript:
var x = 0;
var students = [];
function addStudent(){
students[x] = document.getElementById("namebox").value;
students[x][1] = document.getElementById("scorebox").value;
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "";
document.getElementById("scorebox").value = "";
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y] + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}

as suggested by #Y.C. if you add students[x][0] = document.getElementById("namebox").value; your code will work. I wanna propose just a minor modification though so that your json array keeps its "pattern". Enclose document.getElementById("scorebox").value in parseInt() so you get the score as a number. In other words just write parseInt(document.getElementById("scorebox").value);
UPDATE
since my previous suggestion only works if you predefine the array I editted the code so now this should work.
instead of assigning the value to each cell I used push() function so now the addStudent method looks like this:
function addStudent(){
students.push(document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value));
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
UPDATE #2
my last update was only for addStudent to work since I thought this was the problem. So now this whole thing has to work by following the steps below:
on your html add a div with the id result because it seems that you forgot
<div id="result"></div>
on your Javascript just copy and paste the following
var x = 0;
var students = [];
function addStudent(){
students.push([document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value)]);
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y][0] + " " + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}
Notice that I have changed the addStudent function a bit just to add every student as a seperate array consisted of his/her name and his/her score.

do something like this
function addStudent(){
var studentArray = [],
tempArray = [],
index= 0;
tempArray[0] = document.getElementById("namebox").value; // David
tempArray[1] = document.getElementById("scorebox").value; //80
// this will insert array into main array.
studentArray.push(tempArray); // [['David', 80]]
// rest of your code
return studentArray;
}

Related

Function to Search for a Specified Value Within an Array?

I am fairly new to JavaScript and StackOverflow and am currently trying to create a function to search for a specialized value within a created array. I have written out what seems like a function that would work, any ideas or any obvious flaws in it? It is currently not working. Thanks!
HTML:
<td>Index: <input style = "width: 50px" input type ="textbox" id="Index" value="2"/></td> <!-- HTML code to create the index textbox -->
<br/> <!-- Line Break -->
Value: <input style = "width: 50px" input type = "textbox" id="Value" value = "10"/> <!-- HTML code to create the value textbox -->
<br />
<td>Enter Value to Find: <input style="width: 50px;" type="textbox" value="20" />
<input type="button" value="Search Array" onClick = searchArray(); /></td>
<br />
<input type = "button" value = "Create" onClick = "createArray();"/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<div id="result">
JS:
var myArray = [];
var d = ""; //This global variable is going to be used for clearing and populating the screen
function createArray (){
//This functions is to clear the current information on the screen so the array can populate
clearScreen();
//The next thing we want to do according to the lecture is create a FOR loop to run 100 times to set the various array values
for (var i = 0; i <100; i++){
myArray[i] = Math.floor(Math.random()* 100 + 1); //Math.floor rounds an number downards to the nearest integer then returns. Math.random returns a integer randomly withing given variables
}
popScreen(); //function to fill the screen with the array
}
function clearScreen(){
d = ""; //Global string variable mentioned before
document.getElementById("result").innerHTML = "";
}
function popScreen(){
for (var i = 0; i < myArray.length - 1; i++){
d += i + ' : ' + myArray[i] + "<br/>";
}
document.getElementById("result").innerHTML = d;
}
function insertIntoArray(){
clearScreen();
var i= parseInt(document.getElementById("Index").value);
var j = parseInt(document.getElementById("Value").value);
d = "inserting " + j+ " at " + i + "<br/>";
var temp = myArray[i];
for (i; i < 100; i++) {
myArray[i] = j;
j = temp
temp = myArray[i+1];
}
popScreen();
}
**function searchArray(myArray, value){
var searchResult = 0;
var searchIndex = -1;
for(var i = 0; i<myArray.length; i++){
searchResult++;
if(myArray[i] == value){
searchIndex = i;
break;
}
}
if (searchIndex == -1){
console.log("Element inquiry not found in array. Total Searched: " + searchResult);
}else{
console.log("Element found at index: " + searchIndex + ", search count: " + searchResult);
}**
}
The issue is caused by the fact there are no arguments passed to the searchArray function via the inline onclick attribute... And they are necessary.
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The error thrown is because myArray is undefined and therefore has no length property.
To have it working, I would modify the HTML from:
<input type="button" value="Search Array" onClick = searchArray(); />
to:
<input type="button" value="Search Array" onClick = searchArray(this); />
And the function would change like this:
function searchArray(element) {
let value = element.previousElementSibling.value
// rest unchanged
searchArray being already defined at global scope, you don't need to pass it.
But you need the value from the input right before the button. You can get it using previousElementSibling.

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

HTML input - getting the value via innerHTML or XMLSerializer

I have an input box on a html page. I know I can get just the value, but I want the entire input string, i.e. , but with the value present:
<input id="myInput" value="my entry that I just typed in"/>
I have tried innerHTML, I have tried XMLSerializer, etc.
var htmlDiv = document.getElementById('myInput');
var str = s.serializeToString(htmlDiv);
The value is always empty.
If you are wondering why I want to do this - it is because this is my simple example of what in reality is about 60 inputs, all part of an HTML string that I want to send to XSLT translation. That part works like gangbusters, I just have to get it HTML with values intact.
Another related problem is that innerHTML has a nasty habit of getting rid of the / at the end of the input box, which throws off the XSLT translation.
Try this:
console.log(document.getElementById("myInput").outerHTML);
<input id="myInput" value="my entry that I just typed in"/>
And if you want to add / at the end:
myVar = document.getElementById("myInput").outerHTML;
if(myVar.charAt(myVar.length - 1) !== "/"){
console.log(myVar.slice(0, myVar.length-1) + "/>");
}
<input id="myInput" value="my entry that I just typed in"/>
I ended up doing the following: Serializing with XMLSerializer, which solved the / problem. And I just got the values from the DOM and inserted them myself.
function htmlCleanup(htmlDiv) {
//serialize the html. It will lack the latest user changes in the inputs.
var s = new XMLSerializer();
var str = s.serializeToString(htmlDiv);
var lines = str.split("\n");
//get all of the inputs in the div
var inputs = htmlDiv.getElementsByTagName('input');
//Here we put in the latest values
var inputIndex = 0;
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line.indexOf('<input') >= 0) {
var value = inputs[inputIndex].value;
lines[i] = fixInputValue(line, value);
inputIndex++;
}
}
str = lines.join('\n');
//Some other weird aftertaste stuff that needs fixing. <tbody> is added to tables - wrongly.
//the div at the top is also a problem.
//Then we turn it all into proper xhtml for the trip back to the server.
var contents = str.replace('<div xmlns="http://www.w3.org/1999/xhtml" id="documentEditBody">', '');
contents = contents.replace(/<tbody>/g, '');
contents = contents.replace(/<\/tbody>/g, '');
contents = '<?xml version="1.0" encoding="UTF-8"?><html><head></head><body><div>' + contents + '</body></html>';
return contents;
}
function fixInputValue(input, value) {
var valuePos = input.indexOf('value');
var result = "";
if (valuePos > -1) {
for (var i = valuePos + 7; i < input.length; i++) {
var chr = input[i];
if (chr === '"') {
var last = input.substring(i + 1, input.length)
result = input.substring(0, valuePos - 1) + ' value="' + value + '" ' + last;
break;
}
}
}
return result;
}

Write multiple strings on the same id [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have the input of 'Fred'.
How can I print it so that it looks like this?
Character List:
F
r
e
d
And that it is all being written to a paragraph element in html with the id = 'msg2'
So far all that I can get it to write is either F or d
Apologies, forgot to include code
function start () {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString (pString) {
for (i = 0; i < pString.length; i++) {
t = i + 1
var vReturnName = ('Character list: <br />' + (pString.substring(i, t)))
}
return (vReturnName);
}
Split the string and use forEach to loop over the array then create new element and just put it in the DOM:
let str = "FRED";
str.split('').forEach(s => {
let p = document.createElement('p');
p.textContent = s;
document.body.appendChild(p);
})
p{border-bottom:solid 1px #c8c8c8;}
Your code has few issues:
var vReturnName = inside loop will always have last value as you are overriding it. Move declaration outside loop and the use vReturnName += to append
(pString.substring(i, t)) This will give you single character but you are not adding <br/> after it and so you will have no line-breaks. Also you can use string.charAt instead of it.
for (i = 0; Any variable defined without var|let|const becomes global.
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = 'Character list: <br />'
for (i = 0; i < pString.length; i++) {
t = i + 1
vReturnName += (pString.substring(i, t) + "<br/>")
}
return (vReturnName);
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
Alternate solution:
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = wrapInP('Character list:')
for (var i = 0; i < pString.length; i++) {
vReturnName += wrapInP(pString.charAt(i))
}
return vReturnName;
}
function wrapInP(str){
return "<p>" + str + "</p>"
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
References:
Is it sometimes bad to use <BR />?
string.charAt(x) or string[x]?
Use String#split to get array of each character.
Use Array#join to get the string concatenated with <br><br>
var name = "Fred";
var newName = name.split('').join('<br><br>');
document.getElementById('msg2').innerHTML = newName;
<div id='msg2'></div>
You have to split up the text and append it to the div like so:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
$('#msg2').append(characters[i]+'<br/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = 'msg2'></div>
If using Pure JS:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
document.getElementById('msg2').innerHTML+=characters[i]+'<br/>';
}
<div id = 'msg2'></div>

Sum of form input in Javascript

I want the user to enter a number then when it is submitted, it is inserted into the array totalBags.
The user can then submit another number, when submitted the array elements are added together.
E.g. Input = 2
Press submit
Output = 2
New input = 3
Press submit
Output = 5
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitOrder()
{
var allBags = [];
var bags_text = document.getElementById("bags").value;
allBags.push(bags_text);
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i]; // here is the problem... i think
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
function resetOrder()
{
document.getElementById("container").innerHTML = "<p><label for=\"bags\">No. bags: </label><input type=\"text\" id=\"bags\" /></p><p><input type=\"button\" value=\"Subit order\" onClick=\"submitOrder()\"> <input type=\"reset\" value=\"Reset Form\" /></p>";
}
</script>
</head>
<body>
<form name="order_form" id="order_form">
<div id="container">
<label>Total bags: </label><input id="bags" type="text" ><br>
<input type="button" id="submitButton" value="Subit order" onClick="submitOrder()">
<input type="reset" value="Reset" class="reset" />
</div>
</form>
</html>
I should rewrite the program a bit. First, you can define global variables which won't be instantiated in the function. You are doing that, which resets the variables. Fe
function submitOrder()
{
var allBags = [];
// ...
}
It means that each time you're clicking on the button allBags is created as a new array. Then you add an value from the input element. The result is that you have always an array with one element. It's best to declare it outside the function. By this, you ensure that the variables are kept.
// general variables
var allBags = [];
var totalBags = 0;
function submitOrder()
{
// the result is a string. You have to cast it to an int to ensure that it's numeric
var bags_text = parseInt(document.getElementById("bags").value, 10);
// add result to allBags
allBags.push(bags_text);
// total bags
totalBags += bags_text;
// display the result
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
by leaving out the loop, you have an more performant program. But don't forget to clear the array and the totalBags variable to 0 if you're using the reset button.
function resetOrder()
{
document.getElementById("container").innerHTML = "...";
// reset variables
totalBags = 0;
allBags = [];
}
Try to use:
for (var i = 0; i < allBags.length; i++)
{
totalBags += parseInt(allBags[i],10);
}
Or use Number(allBags[i]) if you prefer that.
Your element allBags[i] is a string and + between strings and concatenting them.
Further study: What is the difference between parseInt(string) and Number(string) in JavaScript?
function submitOrder()
{
var allBags = parseInt(document.getElementById("bags").value.split(""),10);//Number can also used
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i];
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}

Categories