Object property sent from HTML input "undefined" - javascript

I'm beginner in coding. I've tried to find similar problem on SO but with no proper result.
I'm writting a code where HTML form sends its value to an object's property, then I want to print it in document using innerHTML method. I save object in array so then I can manipulate them.
Some problems appears when I add one more dimension to my array (arr[i][j] in code below - 2nd dimension will be needed further) - then object's properties change to "undefined" when printed. What should I do to get access to object's properties in array's 2nd dimension (using JS only)? This is my JS code:
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
and HTML in body:
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick=A ddProduct()>

Try substituting
onclick="AddProduct()"
for
onclick=A ddProduct()
at html; and add [0] at
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
for
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
as you pushed an array containing an object to arr at first for loop. To reference the index of the array, use bracket notation to retrieve object at index 0 of array in arr
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick="AddProduct()">

Related

Why I can't get multiple value of inputs using getElementsByTagName()?

I'm trying to get into a set of inputs values using TagName and store only even numbered ones in a table with the position. It seems like there is an error.
function call() {
var v = document.getElementsByTagName('input');
var s = '<table border = 1><tr><td>position<td>value</tr>';
for (var i = 0; i <= v.length; i++) {
var p = v[i].value;
console.log(p);
if (p % 2 === 0) {
s += '<tr><td>' + i + '<td>' + p + '</tr>';
}
}
s += '</table>'
document.getElementById('result').innerHTML = s;
}
<p>elm 1 : <input type="texte" name="" value="10"></p>
<p>elm 2 : <input type="texte" name="" value="12"></p>
<p>elm 3 : <input type="texte" name="" value="10"></p>
<p>elm 4 : <input type="texte" name="" value="12"></p>
<button onclick="call()">calculat</button>
<hr>
<p id="result"></p>
jsBin for my code

Unable to generate a multiplication table with user input in JavaScript

I have a page which prompts the user to enter a positive integer from 1 to 9, then the javascript code will generate a multiplication table from the input value all the way to 9. I am getting an error in which I cannot retrieve the value and do a multiplication with it.
function timesTable()
{
var values = document.getElementById('value1');
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
Expected result:
You have to take the value of the element not the element itself
var values = document.getElementById('value1').value;
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
You are trying to multiply the element itself. What you actually want is the value.
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property.
You just have to find it's value, replace you line
var values = document.getElementById('value1');
with
var values = document.getElementById('value1').value;
This does what you want.
Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.)
const userValue = document.getElementById("value1").value;
const p_tables = document.getElementById("tables");
let outputHtml = "";
for(let i = 1; i < 10; i++){
outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>";
}
p_tables.innerHTML = outputHtml;
you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use
<\br>(please ignore '\').
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<=9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="Number" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>

Javascript wrong variable type

Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good

Make a html unordered list from javascript array

I'm having a bit of a problem. I'm trying to create a unordered list from a javascript array, here is my code:
var names = [];
var nameList = "";
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
nameList += "<li>" + names + "</li>";
document.getElementById("name").innerHTML = nameList;
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="submit()">
<br>
<br>
<div id="name"></div>
For example, if I post 2 names, Name1 and Name2 my list looks like this:
•Name1
•Name1,Name2
I want it to look like this:
•Name1
•Name2
If you look at your code, you are only creating one li with all your names as the content. What you want to do is loop over your names and create a separate li for each, right?
Change:
nameList += "<li>" + names + "</li>";
to:
nameList = "";
for (var i = 0, name; name = names[i]; i++) {
nameList += "<li>" + name + "</li>";
}
If you are interested in some better practices, you can check out a rewrite of your logic here: http://jsfiddle.net/rgthree/ccyo77ep/
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
document.getElementById("name").innerHTML = "";
for (var I = 0; I < names.length; I++)
{
nameList = "<li>" + names[I] + "</li>";
document.getElementById("name").innerHTML += nameList;
}
}
You are using an array, when you print an array JavaScript will show all the entries of the array separated by commas. You need to iterate over the array to make it work. However you can optimize this:
var names = [];
function displayUserName()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="displayUserName()">
<br>
<br>
<div id="name"><ul></ul></div>
In this example the HTML is syntactically correct by using the UL (or unordered list) container to which the lis (list items) are added.
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
This line selects the div with the name: name and its first child (the ul). It then appends the LI to the list.
As #FelixKling said: avoid using reserved or ambiguous names.
<div>
<label for="new-product">Add Product</label><br /><br /><input id="new-product" type="text"><br /><br /><button>Add</button>
</div>
<div>
<ul id="products">
</ul>
<p id="count"></p>
</div>
var products = [];
var productInput = document.getElementById("new-product");
var addButton = document.getElementsByTagName("button")[0];
var productListHtml = "";
var abc = 0;
addButton.addEventListener("click", addProduct);
function addProduct() {
products.push(productInput.value);
productList();
}
function productList() {
productListHtml += "<li>" + products[abc] + "</li>";
document.getElementById("products").innerHTML = productListHtml;
abc++;
}

Can't Find Dynamically Generated Textboxes

I have two functions - one takes a URL in a certain format (e.g. "test.com?action=query&max_results=20") and breaks it down into dynamically generated textboxes for editing. The other puts it back together along with any edits. Both functions are called by clicking a button.
The second function is unable to find the ids of the dynamically generated textboxes - they're coming back as "null". How do I get the function to recognise ids created after the page loads?
Code:
<script>
function Split()
{
//Get table body for insert
var table = document.getElementById("ValueTableBody");
//Clear table of rows
table.innerHTML = '';
//Grab URL
var URLquery = document.getElementById("oldquery").value;
//Split on ? to isolate query
var querysplit = oldquery.split("?");
//Store main url
var mainURL = document.getElementById('mainURL');
mainURL.value=querysplit[0];
//Split on & to isolate variables
var splitagain = querysplit[1].split("&");
var i = 0;
//Loop on number of variables in query
for(i = 0; i < splitagain.length; i++){
//Split on = to isolate variables and values
var splitthird = splitagain[i].split("=");
//Insert new row into table
var row = table.insertRow(i);
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '"/>';
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
}
}
function Unsplit()
{
var mainURL = document.getElementById('mainURL').value;
var completequery = [];
var URLarray = [];
var rowCount = document.getElementById('ValueTableBody').rows.length;
for(i = 0; i <= rowCount; i++){
//Get variable of current row
var value1 = document.getElementById('query' + i).value;
//Get value of current row
var value2 = document.getElementById('queryvalue' + i).value;
if (value1) {
if (value2) {
//If both have value, then push into array
valueArray = [];
valueArray.push(value1);
valueArray.push(value2);
//Merge into one to push into next array
var newvalue = valueArray.join("=");
URLarray.push(newvalue);
}
}
}
//Join all sections of the query together
mergearray = URLarray.join("&");
//Push mainURL
completequery.push(mainURL);
//Push completed query
completequery.push(mergearray);
//Join the query together to make complete new URL
mergearray2 = completequery.join("?");
//Display new URL
var newquery = document.getElementById('newquery');
newquery.value=mergearray2;
//Output new URL to iframe
document.getElementById('webservicedisplay').src = mergearray2;
}
</script>
HTML:
<div style="float:left;">
<h1>Webservice Tester</h1>
<p><label style="font-weight:bold; display:inline-block; vertical-align:top;">Old Webservice Call:</label> <textarea cols="60" rows="4" id="oldquery"></textarea></p>
<input type="submit" name="button" id="splitbutton" onclick="Split()" value="Split!" /> <br><br>
<p><label style="font-weight:bold;">URL:</label> <input type="text" size="50" id="mainURL"></input></p><br>
<table id="ValueTable">
<thead>
<th>Variable</th>
<th>Value</th>
</thead>
<tbody id="ValueTableBody">
</tbody>
</table>
<br>
<p><input type="submit" name="button" id="unsplit" onclick="Unsplit()" value="Unsplit!" /></p> <br><br>
<p><label style="font-weight:bold; vertical-align:top;">New Webservice Call:</label> <textarea cols="60" rows="4" id="newquery"></textarea></p>
</div>
<div style="float:left; padding-left:20px;">
<p><label style="font-weight:bold;">Output:</label></p><br>
<iframe height="450" width="500" id="webservicedisplay" src="">
</iframe>
This was fixed by the author because the 'issue was actually the loop having the "<=" condition - it was looking for one more table row that didn't exist.'
I had suggested to write the JS differently as so:
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '" value="' + splitthird[0] + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '" value="' + splitthird[1] + '"/>';
And remove:
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];

Categories

Resources