So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
Array#push adds items to the end of an array. eg: arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
to append to an array you can use push
list.push({name:"sudarshan",rno:"33"});
or just
list[list.length] = {name:"sudarshan",rno:"33"};
which is the same as above.
Related
Declaring an array within a function triggered by button causes the function to fail and not work as intended. What is the reason this happens? The "function C" block is having the problem.
I have also noticed that the ES6 syntax of "export ..." causes the entire thing to jam as well, it only accepts "module.export".
I am a total beginner, so I have no idea of what is going on.
This is my code:
<!-- Bootstrap CSS -->
<link href="resources/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="resources/custom2.css">
<link href="resources/TCJA's CSS.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
let TA = [0, 0, 0, 0]
function MF() {
TA = [0, document.getElementById("test1").value, document.getElementById("test2").value, document.getElementById("test3").value]
document.getElementById("shout1").innerHTML = TA[1]
document.getElementById("shout2").innerHTML = TA[2]
document.getElementById("shout3").innerHTML = document.getElementById("testCheck").checked
}
function C() {
var ACArray[0] = 2; //AttackerCard Array
var DCArray[0] = 1; //DefenderCard Array
var para = document.createElement("p");
var node = document.createTextNode("The attackers dealt " + document.getElementById("wand").value + " damage to the defenders.");
para.appendChild(node);
var element = document.getElementById("newElement");
element.appendChild(para);
}
</script>
</head>
<body>
<!-- Put code below -->
<br>
<label class="control-label">Tester Input</label>
<input class="form" id="test1">
<input class="form" id="test2">
<input class="form" id="test3">
<br>
<button id="doge" class="btn btn-primary" onclick="MF()"><h3>Result</h3></button>
<br>
<input id="testCheck" type="checkbox"> Check it?
<br>
<h2>Result:</h2>
<p id="shout1">Hello?</p>
<p id="shout2">Hello again?</p>
<p id="shout3">Hello a third time?</p>
<br>
<label class="control-label">Creator Input</label>
<input class="form" id="wand">
<button id="god" class="btn btn-success" onclick="C()"><h3>Create</h3></button>
<br>
<div id=newElement>
</div>
<button id="show">Show</button>
<!-- JQuery -->
<!-- End of body -->
</body>
</html>
What do you mean, by declaring var ACArray[0]=2;? Yes, it looks like declaring new array with first element equals 2, but, where is your array declaration?
The right way to do this: var ACArray = [2]; var DCArray = [1]; and so on.
Declare arrays Before assigning values into an array.
var ACArray = [];
var DCArray = [];
function C(){
ACArray[0] = 2;
DCArray[0] = 1;
}
The following syntax is incorrect:
var ACArray[0]=2; //AttackerCard Array
var DCArray[0]=1; //DefenderCard Array
The most convenient way to declare an array in JS is an Array literal like this:
var array = ['item1', 'item2'];
What we now have done is multiple steps in one. First we have created memory for an array using the var keyword and the array literal syntax.
Step 1:
var array = [];
Then we have initialized the array and put actual values inside the array like this:
Step 2
array[0] = 'item1';
array[1] = 'item2';
Important to understand is that you now can refer to all these elements in the following way:
console.log(array[0]); // logs item1
console.log(array[1]); // logs item2
And also be aware that the counting of the elements in the array starts with 0, not 1.
I'm trying to create an HTML page that allows the user to input integers into a stored array using a button and then search that array for the inputted integers using another button. I am very confused and new to coding so any help would be much appreciated!
Try this out
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="data">[]</p>
<input id="inputNumber" value="0"/> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0"/> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for(var i=0; i < data.length; i++){
if(data[i]==toFind) return alert("found at "+i);
}
return alert("couldn't find that number");
}
function refresh(){
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>
Basically, I'm just using using the buttons to call the functions within the script that handles insertion and query for me. Additionally a refresh function is there to refresh the newly added data
I want to get the names of the n (say n==5) children of a given person, by using the same form each time.
I can't seem to be able to produce javascript code that will accomplish this simple task.
for (var i = 0; i<5; i++){
<form id="child_form">
Child name:
<input type="text" id="child_name" name="child_nm" size="40">
<br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
}
<script language="javascript">
<script>
function myFunction() {
add_child_to_array();
}
var array_of_children = [];
function add_child_to_array(){
var input_string = document.getElementById("child_name").value;
alert(input_string);
array_of_inputs.push(input_string);
}
</script>
But clearly one can't do that.
I've tried taking the data out of the form and then resetting the form. It turns out you can do either but not both.
I haven't found a website that deals with this problem.
Help would be greatly appreciated.
You have multiple options to accomplish this task. I would prefer to use the HTML5 template element functionality.
You could alternatively create and append the DOM Elements by yourself.
This is certainly a bit of a mess. Assuming I understand correctly, you need to create the form in javascript, so it can be dynamically added as many times as you want. I have written a generalised way of doing this. You may want to change / simplify it. I have made sure all elements are dynamic so that can be accessed properly. Also, I have used JQuery which I highly suggest.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function(){
var allForms = document.getElementById("all-forms");
for(var i = 0;i<5;i++){
form = document.createElement("div");
form.id = "form-" + i.toString();
if(i!=0){
form.style.display = "none";
}
input = document.createElement("input");
input.id = "child_name"+i;
input.placeholder = "input"+i;
submit = document.createElement("button");
submit.innerHTML = "go"+i;
submit.id = "submit-"+i;
submit.className = "buttons";
form.appendChild(input);
form.appendChild(submit);
allForms.appendChild(form);
}
$(".buttons").click(function(){
var id = $(this).attr("id").substring(7);
$("#form-"+id).hide();
var nextID = (parseInt(id)+1).toString();
$("#form-"+nextID).show();
});
});
</script>
</head>
<body>
<div id = "all-forms"></div>
</body>
</html>
We are working with the facebook api and have stored the data retrieved in a JSON format into an array. We would like to display this information in a different HTML page but are unable to do so, please help regarding this?
<p id="demo"></p>
<script> var str=""; var names1 = new Array(); //creating names1 array
getFriendsList = function() { //calling from another function
FB.api('me/taggable_friends', function(response) {
for (var i = 0; i <= response.data.length; i++) {
names1.push(response.data[i].name); str=str+"<br>"+"<br>"+names1[i]; //appending thenames to str
document.getElementById("demo").innerHTML = str;//displaying the element in the html page.
}
});
} </script>
I am still a little confused by your question, but I am assuming that you want to know how to display the elements from an array onto your HTML page.
If this isn't what you are asking, then just expand on your question and I will see how I can help.
Explanation for code below
You are accessing your JavaScript file in your HTML by adding the <script type="text/javascript" src="app.js"></script> reference.
The JavaScript is creating a simple array called myArray. We then loop through our array and display content using the document.write(...); line.
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>
JavaScript
var myArray = [1, 2, 3];
// for each loop
for (var i in myArray) {
document.write(myArray[i]);
}
I have a collection of arrays which are generated dynamically. What I am trying to do is to implement an AutoComplete functionality. I want to use those arrays in click event handler, by getting name dynamically and assigning that to local array. But that is not working (I'm not sure abt my code). Is there any way to achieve that?
Here is my code which I believe should work (which does not work):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
var ga_input1 = new Array('India','Russia','Norway');
var ga_input2 = new Array('Delhi','Mumbai','Hyderabad');
</script>
<body>
Countries: <input id="input1" type="text"/>
Cities: <input id="input2" type="text"/>
<script>
var arrayTmp = new Array();
$('input').keydown(function(){
var id = $(this).attr('id');
arrayTmp = "ga_"+id; // What I believe here is the values of ga_input1/ga_input2 are assigned to array 'arrayTmp'
//alert(arrayTmp[0]);
});
</script>
</body>
All global variables are members of the window object, so:
arrayTmp = window["ga_"+id];
But I'd personally put the data in an object like this:
data = {
'input1': ['India','Russia','Norway'],
'input2': ['Delhi','Mumbai','Hyderabad']
};
...
arrayTmp = data[id];
You can put that arrays in a "Map" and later fetch them from it easily.
Here's how it's done:
var countryMap = {};
countryMap["Europe"] = ['Russia', 'England', 'Norway'];
countryMap["America"] = ['USA', 'Canada', 'Mexico'];
....
var arrayTmp = countryMap["America"];
alert(arrayTmp[0]); //USA
alert(arrayTmp[1]); //Canada
alert(arrayTmp[2]); //Mexico
What you have in arrayTmp is just a string "ga_input1". Instead, try eval("arrayTmp=ga_"+id);.
eval('var arrayTmp = ga_' + id);
alert(arrayTmp[0]);