I have an empty array for example called const arr = []; and when I click the button in page I want to create new Object inside this array, I do that with this following code line
//add is button element
const add = document.querySelector(".add");
//value is input element
const valueInput = document.querySelector(".value");
add.addEventListener('click', ()=> {
arr.push(new Object)
console.log(arr)
})
it makes object but I want to grab this Object and insert inside new property for example to called "text" and array should look like that
arr[{text: ''}]
and every click I want to create new object in this array and property still must be text, inside the text I will put input value
I tried on my own
arr.push(new Object = {text})
arr.Object.text = valueInput.value
but both of them give me left-hand error
Just use the object literal with a property text and its value would be valueInput.value.
//add is button element
const add = document.querySelector(".add");
//value is input element
const valueInput = document.querySelector(".value");
const arr = [];
add.addEventListener("click", () => {
arr.push({
text: valueInput.value
});
console.log(arr);
});
<input type="text" placeholder="Insert text" class="value" />
<button class="add">add</button>
Related
I am getting the value of id and quantity during the click button. I want add a new array inside the object array. Below is the code
adddata =(d,v) => {
const product = [];
for (let i = 0; i < 1; i++) {
product.push({
product_id:d,
cart_quantity:v
});
}
console.log(product);
<button value={this.state.quantity} className="btn" onClick={adddata} data-id={item.product_id}>Add to cart</button>
The only issue with this implementation is that. it replacing the new value with an existing one. I want to merge it dynamically every time click on the button.
Please help
You defined the variable product inside the function, So each time when you execute the function, It will be reinitialized.
Use Global Variable / State
// global
const product = [];
addData =(d,v) => {
// I removed the loop because it's useless here.
product.push({
product_id:d,
cart_quantity:v
});
}
I am creating simple App using Vanilla JavaScript, I have some issue, Let's explain my problem,In the beginning i have empty array, I want to push some values from Input field, and it's works fine, but i want to push only one object into arrOfObj:[], that means i want replace old value by new value, without changing the length.
var arrOfObj = [];
function pushObject() {
var inputVal = document.getElementById('mainInput').value;
arrOfObj.push({ id: 1, value: inputVal });
console.log(arrOfObj);
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
I think instead of using push, you can directly replace the first index with your new object
var arrOfObj = [];
function pushObject(){
var inputVal = document.getElementById('mainInput').value
//replace the first value of array
arrOfObj[0] = {'id':1, 'value':inputVal};
console.log(arrOfObj)
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
You can achieve this by simply updating the 0th element of your array if there is one.
var arrOfObj = [];
function pushObject(){
var inputVal = document.getElementById('mainInput').value
if (arrOfObj[0]) {
arrOfObj[0].value = inputVal
} else {
arrOfObj.push({'id':1, 'value':inputVal})
}
console.log(arrOfObj)
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
I push strings to an array and display the elements in a textarea. The array populates as expected when onchange is triggered, and then I need to get the number of elements in the array, but the IDarr.length stays fixed on 2. Can anybody advise me on the error? Here’s my code:
Script:
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
var IDarr = [array];
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr;
alert(IDarr.length);
}
Receiving textarea:
<textarea id="array"></textarea><br>
Input text (from databaseloop) to populate IDarr onchange:
<input Type="text" id="event<%=ct%>" value="<%=events(dates)%>" onchange="UpdBttn(this, '<%=ct%>')">
I'm not exactly sure what you're trying to achieve, but you might do something like this:
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
var IDarr = array.split(',');
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr.join(',');
alert(IDarr.length);
}
You need to define your variable outside of the function to prevent it from initializing each time you call the function try this:
var IDarr = [];
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr;
alert(IDarr.length);
}
innerHTML returns a string. So when you retrieve array using var array = document.getElementById('array').innerHTML; it is single string. So you have one element that is string in your array and after pushing another element it become two.
const button = document.querySelector('button');
button.addEventListener('click', function() {
const divContent = document.querySelector('#array').innerHTML
const idArr = [divContent];
console.log(idArr);
idArr.push('lorem');
document.getElementById('array').innerHTML = idArr;
// The length will be same
console.log(idArr.length);
});
<div id="array">Item1, Item2</div>
<button>Click Me</button>
I am not really sure about how your innerHTML (Note - If you need only the contents between tag, better use textContent) looks. But you need to convert your textContent from string to array.
const button = document.querySelector('button');
button.addEventListener('click', function() {
const divContent = document.querySelector('#array').innerHTML
const idArr = [...divContent.split(',')];
console.log(idArr);
idArr.push('lorem');
document.getElementById('array').innerHTML = idArr;
console.log(idArr.length);
});
<div id="array">Item1,Item2</div>
<button>Click Me</button>
This implementation is wrong. when use create var IDarr = [array];
you always create a new array with one element. So when you push output array is same 2 for all the time. If you trying to implement the char counter functionality. Please user string, not an array.
Wrong:
var arr = ['s']
console.log(arr.length) // 1
console.log(arr) //s
arr.push('e')
console.log(arr.length) // 2
console.log(arr) //se
//next time
var arr = ['se']
console.log(arr.length) // 1
console.log(arr) //se
arr.push('e')
console.log(arr.length) // 2
console.log(arr) //se,e
Correct Way:
var text = 's'
console.log(text.length) // 1
console.log(text) //s
text = text + 'e'
console.log(text.length) // 2
console.log(text) //se
//next time
var text = 'se'
console.log(text.length) // 2
console.log(text) //se
text = text + 'ee'
console.log(text.length) // 3
console.log(text) //see
I have the following HTML:
<input class="type" id="carbNumber">
<input class="type" id="otherId">
I want to store the input values in an object.
let data = {
inputData: []
}
document.querySelector('input').addEventListener('blur', updateItem)
function updateItem(){
data.inputData.push(this.value)
}
As I have multiple input elements I want to store their values in an array. If I input another value in the same input element - in which I had already input some other value - how can I figure out where I have stored the previous value the first time and therefore replace it with the new value?
You can use the index number from the input elements as they are returned by querySelectorAll:
const data = {
inputData: []
}
// Use the callback argument of `Array.from` and the `i` index:
Array.from(document.querySelectorAll('input'), (inp, i) => {
inp.addEventListener('input', updateItem.bind(inp, i)); // pass `i`
});
function updateItem(i){ // capture `i`
data.inputData[i] = this.value;
console.log('inputData:' + data.inputData);
}
<input id="a">
<input id="b">
<input id="c">
NB: I used the input event to display the results immediately as you type.
Simply do not use an array, use an object.
The object will map the ids of your input elements to their values
"use strict";
(function() {
var values = {};
function updateAllInputs() {
var inputs = document.querySelectorAll('input');
Array.prototype.forEach.call(inputs, function (input) {
// ensures exactly one value per input (if all inputs have ids, adjust as needed)
values[input.id] = input.value;
});
}
// if you still need an array for some reason, you can create one from the object.
function getSnapshotOfInputValuesAsArray() {
return Object.keys(values).map(function(key) {
return values[key];
});
}
}());
I have an object declared, and I have an html form with some matching fields.
All fields in the form are in the object, but the object also has a couple of additional variables and functions.
I'd like to fill the object with the data entered in the form, what I'm trying right now overwrites the declared object, and so doesn't have the functions nor the other variables.
The object :
var Container = {
nodes: [],
Contains: function (Node) {
for (var i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].nodeID === Node.nodeID)
return (i);
}
return (-1);
}
How I fill it from the form :
const handleContainerForm = event => {
event.preventDefault();
ContainerFormToJSON(form.elements);
var i = JSONData.Contains(Container);
if (i === -1)
JSONData.containers.push(Container);
else
JSONData.container[i] = Container;
output = JSON.stringify(JSONData, null, " ");
displayContents(output);
};
The form has ID, Title, Folder, Image and Description as fields, so this last Container object doesn't have the Contains() function nor the nodes[] array.
How do I end up with a complete, filled version of the object I have declared ?
In ContainerFormToJSON function, before the statement
return Container
define:
//container.nodes and container.contains
You are right, JavaScript is very different from C#, especially in regards to OOP. But that doesn't make it better or worse.
In JavaScript, you don't need to declare an object's properties, like you have to when you use classes. I think that you only want to serialize the form's input values to JSON. I recommend not to use an object that additionally has a nodes property and a Contains method.
If you need to keep a copy of the unserialized object, create two objects:
class Container {
constructor () {
this.nodes = [];
}
indexOf (node) {
return this.nodes.findIndex(n => n.nodeID === node.nodeID);
}
}
Container.nodeID = 0; // think of it as a static property
function extractValues (elements) {
// 'elements' is an array of <input> elements
// the 'container' will be filled and serialized
var container = new Container();
for (var index in elements) {
var element = elements[index];
container[element.name] = element.value;
}
container.nodeID = Container.nodeID++; // give the container a unique ID
return container;
}
var inputs = document.querySelectorAll('input');
var jsonData = new Container();
document.querySelector('button').addEventListener('click', function () {
var newContainer = extractValues(inputs);
var index = jsonData.indexOf(newContainer);
if (index === -1) {
jsonData.nodes.push(newContainer);
} else {
jsonData.nodes[index] = newContainer;
}
var jsonString = JSON.stringify(jsonData, null, ' ');
console.log(jsonString);
});
<input name="containerID">
<input name="containerTitle">
<!-- ... -->
<button>Serialize</button>
Please note: only setting an object's properties doesn't make it to JSON. It's only JSON if it's serialized to a string. I recommend this article. To serialize a JavaScript object, use JSON.stringify.
Edit:
Looking at the edit of your question, I think it might be preferable to create a Container class. Both jsonData and the containers of the form data will be instances of that class. It can contain other containers (nodes), and can get the index of such a nested container using the indexOf method. I implemented this in the above code snippet. Whenever you hit the "Serialize" button, a new container with the current <input>s' contents will be added to jsonData. The JSON form of jsonData will be logged to the console.
I hope this is what you are looking for. To better understand JavaScript OOP,
take a look at some of the articles at MDN.