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];
});
}
}());
Related
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>
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">
When i tried to see all input values, its always showing last ones.
function addInput() {
$('.addElement').append('<label>Sağlık Etkisi</label><input id="health" name="health[]" type="text" class="form-control message">');
$('.addElement').append('<label>Yaşam Tarzı Önerisi</label><input id="lifeStyle" name="lifeStyle[]" type="text" class="form-control message">');
$('.addElement').append('<label>Öneriler</label><input id="advice" name="advice[]" type="text" class="form-control message">');
}
I'm appending 3 input to my form.
$('#test').submit(function(e) {
e.preventDefault();
var text = [];
$("input[name='health[]']").each(function(index, item) {
text['health'] = item.value;
});
$("input[name='lifeStyle[]']").each(function(index, item) {
text["lifeStyle"] = item.value;
});
$("input[name='advice[]']").each(function(index, item) {
text["advice"] = item.value;
});
I did text[index]['health'], and this gave me error too.
this code on output, always giving me last 3 input value.
Sorry for my english.
The issue is because you're overwriting the values of the health, lifeStyle and advice properties in every iteration, hence on the final values in each loop are accessible.
One solution to fix this would be to build arrays of the input values and assign those to the properties instead:
$('#test').submit(function(e) {
e.preventDefault();
var healthVals = $("input[name='health[]']").map(function() { return this.value; }).get();
var lifestyleVals = $("input[name='lifeStyle[]']").map(function() { return this.value; }).get();
var adviceVals = $("input[name='advice[]']").map(function() { return this.value; }).get();
var text = [];
text['health'] = healthVals;
text['lifeStyle'] = lifestyleVals;
text['advice'] = adviceVals;
});
Also note that the fact you're looping over the appended elements implies that there can be multiple copies of them. In which case you should remove the id attribute from the HTML you append, as it will result in duplicates which is invalid.
I'm working on a feature where the user needs to be informed that there are unsaved changes in a form in case if they decide to navigate away from the page.
I am almost done but there's a tiny problem-
I am setting a boolean dirty on input change event.
The .change() event will detect any kind of change, as in it doesn't keep track of changes. For example, if an input field has the original value hello, which is modified to bye and back to hello, it will still set the dirty boolean.
Is there any way where I can take a backup of the form with initial values and then compare it with itself at every change event?
You need a way to serialize the form data into a JSON object, and then you could either compare the JSON object by iterating the properties or by comparing the JSON.stringify values.
I have slightly modified the method of objectifying the form data from here in order to do this.
var form = document.getElementById("myForm");
var originalFormData = objectifyForm(form);
var originalFormDataString = JSON.stringify(originalFormData);
setInterval(function() {
var formData = objectifyForm(form);
var formDataString = JSON.stringify(formData);
console.log("Form is dirty: " + (formDataString != originalFormDataString));
},1000);
function objectifyForm(formArray) {//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['id']] = formArray[i]['value'];
}
return returnArray;
}
<form id="myForm">
<input id="myInput" value="test" type="text" />
</form>
You can do something like this. Remember this solution is just a sample. You have multiple input element, than use array/object to save there defaultValue.
var defaultValue = document.getElementById("myText").defaultValue;//Get the default value
var handleChange = function (){
let value = document.getElementById("myText").value;//get the current value
if(defaultValue===value){
console.log("dirty false")
}else {
console.log("Dirty True")
}
}
<input type="text" id="myText" value="abc" onkeyup="handleChange()">
I think you can create a javascript empty initial_values = {} object. initialised it with the default values in the form of key:value pairs. and if dirty boolean is set, it can be used to compare later on.
I would like to get the values of dynamically created hidden fields with a class reference.
Example of created hidden field
<input class="SelectedClaimants" id="CodesList_2__Claimant" name="CodesList[2].Claimant" type="hidden" value="Jason Statham">
This is something along the lines of what i have tried.
$('.listSelected').on('DOMSubtreeModified', function (event) {
$(".SelectedClaimants").find('input[type=hidden]').each(function () {
var testC += $(this).val();
});
});
I was aiming to have them create into an array object, but at the moment i am happy just to get the values out into a concatenated string.
Try this (the result is logged to the console). It's based onn Tushar's answer, but the selector was wrong.
$('input[type="hidden"].SelectedClaimants').map(function () {
return $(this).val();
}).get().join(',')
You can use .querySelectorAll(), spread element, for..of loop. Note, id, e.g., CodesList_2__Claimant should be unique in document.
var testC = [];
for (let el of [...document.querySelectorAll("input[type='hidden'].SelectedClaimants")]) {
testC.push(el.value)
}