HTML:
<html>
<body>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit">Find Student </button>
<script type = "text/javascript" src="ObjectTest.js"></script>
</body>
</html>
Javascript:
var Matt = {
GPA: 4.0,
Faculty: "Science",
Year: 1
};
I have an object that I've defined with some values.
What I am trying to do is to allow text to be entered into the textbox.
When the submit button is hit, a javascript function will be run that grabs the value in the textbox and if it equals the object value, then it will console.log the properties.
Here is my better attempt:
function findStudent(){
var student = document.getElementById('name').value;
return student;
}
console.log(student);
Hard to know exactly what you're trying to achieve or where your object is coming from but your object probably needs to look something like:
var student = {
name:'Matt',
gpa:4.0,
faculty:'Science',
year: 1
}
Try something like:
function checkName(){
var name = document.getElementById('name').val();
if(name === student.name){
console.log('same');
}
else{
console.log('different');
}
}
Called in your button, with something like:
<button onclick="checkName()">Check Student</button>
You have to think about the structure. There should be a lot of students. It's not practical to set multiple objects for each student:
var st1 = { ... }
var st2 = { ... }
Instead it's more practical to declare one object with all students. And put the values in an array:
var students = {
"Matt": ["4.0", "science", "1.0"],
"Laura": ["3.0", "comedy", "2.2"],
...
}
You can output the array as an info to the corresponding student:
function findStudent() {
var info = [];
var student = document.getElementById("name").value;
for (name in students) {
if (name === student) {
info = students[name];
}
}
alert(info);
}
JSFiddle
If you want to use a submit button, it should be in a form. This also makes dealing with inputs easier, even if you don't want to submit the form. I've modified the object so that it has a name property.
var Matt = {
name: 'Matt',
GPA: 4.0,
Faculty: "Science",
Year: 1
};
function checkValue(form) {
if (form.studentName.value == Matt.name) {
form.output.value = ('Match');
} else {
form.output.value = ('Not a match');
}
return false;
}
<form onsubmit="return checkValue(this);">
<label for="studentName">Name: <input name="studentName" id="studentName"></label>
<button>Check the name</button>
<br>
<label for="output">Output: <input name="output" id="output"></label>
</form>
The body of the checkValue function could be:
form.output.value = form.studentName.value == Matt.name? 'Match' : 'Not a match';
However the longer version is simpler to understand.
Related
I need some help with figuring out how local storage and JSON works.
I have the following html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Script.js"></script>
</head>
<body>
<form name="test" method="post" action="javascript:storage()">
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
<input type="submit" value="test">
</form>
<div id="tabletest"></div>
</body>
</html>
the following javascript:
function storage(){
var surname = document.getElementById('surname').value;
var lastname = document.getElementById('lastname').value;
var person = {
"surname" : surname,
"lastname" : lastname,
"dateofbirth" : "01-01-1990"
};
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person);
var tabletest = document.getElementById('tabletest');
var person3 = JSON.parse(person2);
tabletest.innerHTML += JSON.stringify(person3);
}
My problems/troubles:
The output I get in tabletest is this:
{ "surname":"surname", "lastname":"lastname", "geboortedatum":"01-01-1990" }
How do I get only the surname and the lastname in the 'tabletest' div?
How do I add a new value with the inputs from the textfields when the submitbutton is clicked (because push doesn't work)?
To get lastname(or I should say any value inside JSON) use
tabletest.innerHTML +="Lastname:"+person3.lastname+" Sirname:"+person3.sirname;
And to add to the JSON use:
person.newName = newName
//or
person["newName"] = newName;
Localstorage works on key-value pairs. Since you are using the same key, 'person', you are simply overwriting previous value. You could use an array of persons which you store using 'person' key but you are responsible for parsing/stringifying the array each time.
var personsStore = [];
function storage() {
var s = localStorage.getItem("person");
if (s) {
personsStore = JSON.parse(s);
}
var person = {...} //after you get properties from dom input
personsStore.push(person);
var stringForm = JSON.stringify(personsStore");
localStorage.setItem("person", stringForm);
var tabletest = document.getElementById('tabletest');
tabletest.innerHtml += stringForm;
}
If you want particular attributes the easiest way to do that is to use a tool like underscore (underscore.org). Appending to 'tabletest' becomes
tabletest.innerHtml += JSON.stringify(_.map(personStore, fucntion(p) {
return _.pick(p, "firstname", ....);
});
Here is a fiddle
Right now, your logic shows you grabbing the value of first and last name, which is, currently: surname and lastname, respectively:
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
You need to run this function on the button click event and get the value and simply use the storage setItem(key,value) function. Here is the documentation . You only need to stringify, then parse on the storage data. After that, it is an object that you can get the properties from.
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person2);
var tabletest = document.getElementById('tabletest');
tabletest.innerHTML += persons.surname + ' ' + persons.lastname;
You were very close on the logic, but you needed something like this:
document.getElementById('btnTest').onclick = storage;
I also modified the 'submit' button to a standard 'button' element so that the form doesn't post:
<button id='btnTest' value="test">Test</button>
You could then do Ajax. Otherwise, you would need to do a pre-submit function
I have source, like this :
<label>Name:</label>
<input type="text" name="text1"/>
<label>Weight:</label>
<input type="text" name="text2"/>
<button onclick="myfunction">Add</button>
<p id="demo"></p>
<script>
var array = new Array();
function myFunction() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if(text1 == "" || text2 == ""){
alert("Empty!!");
}else{
array = {'data' : [{"Text1" : text1, "Text2" : text2}]}
}
}
</script>
My question is, how do i post value each of text to 2 dimensional array in java script? technically, we can post value to 2D array again and again, so the array will looks like:
var data = {{text1,text2},....,{text-n,text-n+1}}
Then figure it out in table based on 2D array. I have tried, but still not work. I'm not proficient with javascript. Really need help..
You can push a new element to your array every time the button is clicked. The use this array.
var array = [];
function change() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if (text1 == "" || text2 == "") {
alert("Empty!!");
return;
}
array.push({
'data': {
"Text1": text1,
"Text2": text2
}
});
console.log(array);
}
Also, you are trying to get element by Id but no Id is assigned to input elements. I corrected that in the this Fiddle. This is working, take a look.
You need to use Jquery for this
var array = {
'x': { a: 'aaa', c: 'xxx' },
'y': { b: 'bbb', d: 'yyy' }
};
Use Jquery here
$.post( '/herp.php', array, function(d) {
// process response here
});
Put your input in a form, then use serializeArray in jquery.
I have a form and a javascript object.
<form id="myForm">
<input type="text" name="title">
<input type="text" name="image">
</form>
var myObject = {title: 'this is the title', image: 'image.jpg'}
Is there a way to run through the form inputs, and it any of the input names match the keys in the object, set the value?
Please note, I wish to run through the form and not the object, as the object has lots of other data in it which is not relevant to the form (not shown in example).
You can do:
$("#myForm input:text[name]").each(function() {
var name = $(this).attr("name");
for (var key in myObject) {
if (key == name) {
$(this).val(myObject[key])
break;
}
}
});
With this you don't ever loop the object, but you'll have to write an if-clause for every attribute:
var myObject = {title: 'this is the title', image: 'image.jpg'}
$('#myForm input').each(function()
{
if($(this).attr('name') === 'title')
{
$(this).val(myObject.title);
}
});
I found this fiddle and I am trying to get it to work...I can not figure out why the names are not being added to the list, for some reason Add button is acting like a submit button and I can not tell why...It should add all the numbers to a list so when I click submit, then it should send the numbers in an array..
JavaScript:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("inputNames");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByTagName("inputNames").length;
var newGuy1 = document.createElement("inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
HTML:
<h1>Enter Name</h1>
<div id="mainName">
<h2>name</h2>
<label for="name">Add Names: </label>
<input id="name" type="text">
<button id="addName">Add</button>
<form>
<div id="names">
</div>
<input METHOD="POST" action="text.php" type="submit" value="Submit">
</form>
</div>
I've seen
document.createElement("inputNames");
Shouldn't be
document.createElement("input");
?
Because this /^[0-9]{10}$/; will accept only 10 numbers and only that, try entering 1234567890 and you will see no error.
I'm not sure why your "name" field is restricted to 10 digit numbers, but I've got the thing to work.
http://jsfiddle.net/y8Uju/4/
I think the problem was that you were trying to create an element with the tag name inputNames, but that's not a valid tag. Instead I changed it to create inputs, and set the class to inputNames.
Lets say I have the following in C
struct address{
char name;
int id;
char address;
};
struct address adrs[40]; //Create arbitrary array of the structure. 40 is example
adrs[0].name = 'a';
id[0] = 1;
...
What is the equivalent way of defining and creating array of a user defined structure.
Thanks
If you're going to have a predefined layout for an object, you'd probably want to use a contructor-style function.
function address() {
this.name = null;
this.id = null;
this.address = null;
}
arrays are not typed and you don't have to specify a length.
var adrs = [];
you can create a new instance of address like so
var item = new address(); // note the "new" keyword here
item.name = 'a';
item.id = 1;
// etc...
then you can push the new item onto the array.
adrs.push(item);
alernatively you can add a new item from the array and then access it by indexer.
// adrs has no items
adrs.push( new address() );
// adrs now has 1 item
adrs[0].name = 'a';
// you can also reference length to get to the last item
adrs[ adrs.length-1 ].id = '1';
Equivalent would be creating an array of associative arrays.
var arr = new Array();
arr[0] = { name: "name 1", id: 100, address: "addr 01" };
arr[1] = { name: "name 2", id: 101, address: "addr 02" };
//...
After this, you will be able to do:
arr[0].name = "new name 1";
Or access element:
if (arr[1].name == "name 2") { // will be true
}
Hope it helps.
Answer is veryyyy Simple.
const address = {
name: ""
id: 1,
address: ""
}
Or Dynamic
const address = (name, id, address) => {
// Here your checks if enters is correct
return {name, id, address}
}
If You Use TypeScript? It's so simple to.
interface address {
name: string;
id: number;
address: string;
}
const adress: adress = {
.....
}
<script type="text/javascript">
function address()
{
this.name="";
this.id=0;
this.address=""
}
var addresses = new Array(40);
addresses[0] = new address();
addresses[1] = new address();
.....
.....
addresses[0].name = 'a';
addresses[1].id = 5;
</script>
A common problem that is solved by structure is ranking system. An array that contains name and number of some users and then sorting users according to number. Here is javascript implementation of this problem.Object array is used here
<!DOCTYPE html>
<html>
<head>
<title>Structure</title>
</head>
<body>
<label>Enter Student Name 1:</label>
<input type="text" id='n0' name=""><br>
<label>Enter Student Mark 1:</label>
<input type="text" id='m0' name=""><br>
<label>Enter Student Name 2:</label>
<input type="text" id='n1' name=""><br>
<label>Enter Student Mark 2:</label>
<input type="text" id='m1' name=""><br>
<label>Enter Student Name 3:</label>
<input type="text" id='n2' name=""><br>
<label>Enter Student Mark 3:</label>
<input type="text" id='m2' name=""><br>
<input type="button" value="Ranking" onclick="result()">
<div id='id'></div>
<script type="text/javascript">
function result()
{
var b=new Array(100);
var n1=document.getElementById('n0').value;
var m1=document.getElementById('m0').value;
var n2=document.getElementById('n1').value;
var m2=document.getElementById('m1').value;
var n3=document.getElementById('n2').value;
var m3=document.getElementById('m2').value;
var a=new Array(100);
var b=new Array(100);
var n,m,j,i,temp,t,r="<br>Ranking<br><br>";
for(i=0;i<3;i++)
{
n=document.getElementById('n'+i).value;
m=document.getElementById('m'+i).value;
m=parseInt(m);
a[i]={name:n,mark:m};
}
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if(a[j].mark>a[i].mark)
{
temp=a[i].mark;
t=a[i].name;
a[i].mark=a[j].mark;
a[i].name=a[j].name;
a[j].mark=temp;
a[j].name=t;
//console.log(a[i].name);
//console.log(a[i].mark);
}
}
}
for(i=0;i<3;i++)
{
r=r+a[i].name+" ";
r=r+a[i].mark+"<br>";
//console.log(a[i].name);
//console.log(a[i].mark);
}
document.getElementById('id').innerHTML=r;
}
</script>
</body>
</html>