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);
});
});
Related
what has already been described in the title, but basically I want to send a function perimeter and use it to call one of the three different variables. Also so it doesn't come to a miss understanding the "$('#'+id)" part of the code works all I need is the correct syntax for the "id =" part (if even possible). And I know there is a workaround but I am trying to minimize code and this seems like the most optimal solution.
my code:
<div class="one">
<p>ime:</p>
<input type="text" id="name">
<p>kraj:</p>
<input type="text" id="city">
<p>starost:</p>
<input type="text" id="age">
<p id="one_output"></p>
</div>
var name = "1";
var city = "2";
var age = "3";
function statement(id) {
id = $('#'+id+'').val();
$("#one_output").text("Sem " + name + " in živim v " + city + ". Star sem " + age);
};
$('.one input[type="text"]').keyup(function() {
switch($(this).attr("id")) {
case "name":
statement(the_id);
break;
case "city":
statement(the_id);
break;
case "age":
statement(the_id);
break;
}
});
ok, I think I finally understood what you're after
so you're passing a variable name and want to dynamically call it, instead of going the global way using this, I would recommend to do it by having all your vars in just one global one, for example
var formInputs = { name: '1', city: '2', age: '3' }
and then you can easily read/write them with formInputs[ var_name_here ]
so your example, would be written as
var formInputs = { name: '1', city: '2', age: '3' }
function statement(name, val) {
formInputs[name] = val
var txt = `Sem ${formInputs.name} in živim v ${formInputs.city}. Star sem ${formInputs.age}`
$("#one_output").text(txt)
}
$('.one input[type="text"]').keyup(function() {
var elm = $(this)
statement(elm.attr("id"), elm.val())
})
var formInputs = { name: '...', city: '...', age: '...' }
var statement = function(name, val) {
formInputs[name] = val // assign value to variable
var txt = `Sem <b>${formInputs.name}</b> in živim v <b>${formInputs.city}</b>. Star sem <b>${formInputs.age}</b>` // the new text
$("#one_output").html(txt) // output
}
$('.one input[type="text"]').keyup(function() {
var elm = $(this) // our key element
statement(elm.attr("id"), elm.val()) // pass id and why not the value, so we dont need the element again
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<p>ime: <input type="text" id="name"></p>
<p>kraj: <input type="text" id="city"></p>
<p>starost: <input type="text" id="age"></p>
<p id="one_output"></p>
</div>
If you want to minimize your code, you can start by doing this:
id = $(`#${id}`).val();
Instead of this:
id = $('#'+id+'').val();
Modify your keyup callback to a more cleaner code:
$('.one input[type="text"]').keyup(function() {
var myId = $(this).attr("id"));
var id = $('#'+myId+'').val();
$("#one_output").text("Sem " + name + " in živim v " + city + ". Star
sem " +
age);
});
I'm a javascript newbie and I have try this.
<html>
<style>
#WoodNumInput {
width:40px;
}
</style>
<body>
<script>
var i;
var woodtypeAB = ["AB_W15_L100","AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4 ; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<input type = "button" value = "calculate" onclick= "Calculation()">
<div id = "Test"></div>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("woodtypeAB[3]").value;
document.getElementById("Test").innerHTML = ShowResult;
}
</script>
</body>
The value returns undefined and I still can't figure it out.
Thank in advance for your help and suggestions.
This
var ShowResult = document.getElementsByName("woodtypeAB[3]").value
should be
var ShowResult = document.getElementsByName(woodtypeAB[3])[0].value
Since "woodtypeAB[3]" is surrounded by quotation marks it will be interpreted as a string rather than the actual array value.
document.getElementsByName() returns a NodeList of elements so you will have to explicitly say that you want the first item in the NodeList, hence [0]
There are a few things wrong.
First, you're trying to get the .value from a collection instead of from individual elements.
Also, the elements you're creating have a name value of AB_... but you're trying to fetch using a very different name.
I think you perhaps thought that the woodtypeAB[3] you're fetching would somehow translate to the variable and index you used to create the element's name. That's not how it works.
When you created the element, the concatenation did not add woodtypeAB[3] as the name, but rather the value located at that index of that array. So to fetch that particular name, you'd use its array value of AB_W30_L100.
<html>
<style>
#WoodNumInput {
width: 40px;
}
</style>
<body>
<input type="button" value="calculate" onclick="Calculation()">
<div id="Test"></div>
<br>
<script>
var i;
var woodtypeAB = ["AB_W15_L100", "AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("AB_W30_L100");
if (ShowResult.length != 0) {
document.getElementById("Test").innerHTML = ShowResult[0].value;
}
}
</script>
</body>
Although something tells me that you actually are going to want to select all those input elements and perform some calculation on them. That'll require additional tweaks to your code.
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.
I have these text fields.
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Here tab_4_*_li_data is a <li> html of tab , and tab_4_0_li_div_content is id of <div> which will be show on <li> click.
Now I want to extract data from this input fields using regular expression. For example
client,lab
as key
and
<p>aaaaaaaaaaa</p>,<p>dddd</p>
as value of key.
If you see these are related to each others.
tab_4_0_li_div_content tab_4_0_li_data
<p>aaaaaaaaaaa</p> lab
tab_4_1_li_div_content tab_4_1_li_data
<p>dddd</p> client
Div content part can content any thing, It's an text area.
So how we do this?
There is no reason to have to use a regular expression to parse HTML. One thing, you are not going to have a good time going it. Second, use the power of the DOM
var contents = $("[id$=content]"); //find the elements that have an id that end with content
var datas = $("[id$=data]"); //find the elements that have an id that end with data
var details = {}; //object to hold results
datas.each( function(i) { details[datas[i].value] = contents[i].value; }); //start looping and generate the object with the details you are after
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Now that code assumes the data and content elements are in the same order, if not, than it would require a little processing, but it is not that hard to do.
var datas = $("[id$=data]");
var details = {};
datas.each(function(i, elem) {
var id = elem.id;
var val = $("#" + id.replace("data", "div_content")).val();
details[elem.value] = val;
});
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content">
<input type="text" value="lab" id="tab_4_0_li_data">
<input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content">
<input type="text" value="client" id="tab_4_1_li_data">
You can do it like this:
function getValuesById(id1,id2){
var vals = {};
if(id1 === undefined)
id1 = "\\d+";
if(id2 === undefined)
id2 = "\\d+";
$("input").each(function (index, value) {
console.log(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
var match = value.id.match(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
if (match) {
vals[value.value] = $("#tab_" + match[1] + "_li_div_content").val();
}
});
return vals;
}
Here I search through all input fields and match against tab_DIGITS_DIGITS_li_div_data and put that as a key and corresponding li_div_content as value in object values.
Check it out here: JSFiddle
UPDATE: I have updated the code to a function where you can send in a parameter to your two numerical values and will use any number if not supplied, i.e. use as getValuesById(4) for values like tab_4_*_li
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.