Getting array input key and value using jquery - javascript

I need to get unique id and map it to value from array input using jquery/javascript
HTML
<input type="text" name="parameter['abc']" value="first value">
<input type="text" name="parameter['zxv']" value="second value">
Required output
[
'abc' : 'first value'
'zxv' : 'second value'
]
My attempts: managed to get values, but not indexes.
$('input[name^="parameter"]').map(function(){return
$(this).val();}).get();

var obj = {};
$.each($(".inputs"), function(key1, index1) {
var res = $(this).attr('name').split("parameter");
var parameterkey = res[1];
var res = parameterkey.replace("['", "");
var resd = res.replace("']", "");
var key = resd;
var value = $(this).val();
obj[key] = value;
console.log(obj);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="inputs" type="text" name="parameter['abc']" value="first value">
<input class="inputs" type="text" name="parameter['zxv']" value="second value">

Related

jquery populates attribute input form multiple value

is that possible to populate attributes name, value, type from :input or something like jQuery serialize for all kinds of input, and combine the value if there is have multiple name like checkbox and radio choices
the concept like this :
$(this).attr('name');
$(this).attr('type');
$(this).attr('value'); // <--- combine this value when the type is checkbox or radio
i try to populate the attributes using each function :
it work but i still don't know how to combine type
$('.submit').click(function(){
var tipe = {}
var form = {}
$('input[type=text], textarea', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
form[name] = value;
tipe[name] = type;
});
$('input[type=checkbox], input[type=radio]', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
if(form[name] === undefined) {
form[name] = [value];
tipe[name] = [type];
} else {
form[name].push(value);
}
});
console.log(form);
//console.log(tipe);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">
you can use below logic where you can create one map to store value of each input and append values if input type is of type radio or checkbox
$('.submit').click(function(e){
var formValues = {};
$('.register :input').each(function(){
var name = $(this).attr('name');
var type = $(this).attr('type');
var value = $(this).val();
var inputElement = {};
var valid = true;
if(type == 'radio' || type == 'checkbox') {
valid = $(this).is(':checked');
if(valid) {
if(formValues[name]) {
inputElement = formValues[name];
var preVal = inputElement['value'];
value = preVal + ',' + value;
}
}
}
if(valid) {
inputElement['name'] = name;
inputElement['type'] = type;
inputElement['value'] = value;
formValues[name] = inputElement;
}
});
console.log(formValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">

Grabbing form data into an object with jQuery to make values that are arbitrary arrays and objects

I've got an HTML form that consists of a series of units like this:
<input name="categoryColor[]" />
<input name="categoryName[]" />
Using this jQuery code, I can capture this data and return it in an object like this:
{categoryColor: [array of values],
categoryName: [array of values]}
Here's an example of the code in action:
const getFormDataFromElem = function($elem, options) {
options = options || {};
const vis = options.onlyVisible ? ":visible" : "";
const formInputs = $elem.find(`:input${vis}, [contenteditable=true]${vis}`);
const data = {};
formInputs.each(function() {
const $this = $(this)
const type = $this.attr('type');
const val = type === "checkbox" ? (this.checked ? "1" : "0") :
($this.is('[contenteditable=true]') ? $this.text() : this.value);
const name0 = $this.attr('name');
const doArray = name0 && name0.slice(-2) === "[]";
const name = doArray ? name0.slice(0, -2) : name0;
if (!name || (!options.saveEmpty && !doArray && val === "")) {
return;
}
if (doArray) {
if (data.hasOwnProperty(name)) {
data[name].push(val);
return
}
data[name] = [val];
return;
}
data[name] = val;
});
return data;
};
const data = getFormDataFromElem($('.input'));
$('.output').text(JSON.stringify(data, null, 2));
.output {
font-family: monospace;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Input</h2>
<div class="input">
<input name="categoryName[]" value="phase1"/>
<input name="categoryColor[]" value="red"/>
<input name="categoryName[]" value="phase2"/>
<input name="categoryColor[]" value="green"/>
<input name="categoryName[]" value="phase3"/>
<input name="categoryColor[]" value="blue"/>
</div>
<h2>Output</h2>
<div class="output"></div>
BUT I'd like to be able to write the HTML form units like this
<input name="categories[].color" />
<input name="categories[].name" />
since I really need this data in this form:
{categories: [array of objects],
}
where the objects have the form {name: '<name of category>', color: '<color string>'}.
How would I rewrite my general-purpose form-capturing routine to produce values that are arbitrary arrays and objects?
Following assumes you are able to group each set of inputs that make up one object. Then rather than having to parse names use data attributes on the group container for the main object property name.
Still a bit unclear if this is what you are after but can also modify to suit more specific needs. I realize the names are not unique and not sure if that is an issue or not
const data = {};
$('.input').each(function(i){
const $cont = $(this),
{struct, prop} = $cont.data(),
inputs = $cont.find('input').toArray();
if(struct === 'obj'){
data[prop] = data[prop] || [];
const obj = inputs.reduce((a,c)=>({...a, [c.name]:c.value}),{})
data[prop].push(obj);
}
})
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input" data-struct="obj" data-prop="otherCat">
<input name="name" value="phase1" />
<input name="color" value="red" />
</div>
<div class="input" data-struct="obj" data-prop="categories">
<input name="name" value="phase2" />
<input name="color" value="green" />
</div>
<div class="input" data-struct="obj" data-prop="categories">
<input name="name" value="phase3" />
<input name="color" value="blue" />
</div>

How to place values from html inputs into a javascript array of objects

I have three inputs which will be given by the user and i want these 3 inputs to make up objects in an array in my javascript file, i.e, the values for these 3 inputs will make up each object in thearray, everytime the user inputs the 3 values and clicks enter, a new object with those 3 values as properties should be added into the array. How do i achieve this?
I have tried to get the values, and onclick to push them into the array but i keep get a "Cannot access 'arr_items' before initialization
at addName"
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
let i = 0;
function addValues() {
arr_items[i].name.push(input2.value);
arr_items[i].weight.push(input3.value);
arr_items[i].value.push(input4.value);
i++;
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<button onclick="addValues()" id="name">Enter</button>
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
</div>
I expect everytime the user inputs the 3 values and clicks enter, a new object with those 3 values as properties should be added into the array.
You are trying to call the property name, weight etc on the array element using .. This is wrong. Try do:
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
let i = 0;
function addValues() {
arr_items[i] = {
name: input2.value,
weight: input3.value,
value: input4.value
};
i++;
console.log(arr_items)
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<button onclick="addValues()" id="name">Enter</button>
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
</div>
You were doing it wrongly try this:
const arrayItems = new Array();
function addValues(){
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
let inputs = {
input1 : input2.value,
input3 : input3.value,
input4 : input4.value
}
arrayItems.push(inputs);
console.log(arrayItems);
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addValues()" id="name">Enter</button>
</div>
You can just push to array again and again without counter. Like so:
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
function addValues() {
arr_items.push({name: input2.value, weight: input3.value, value: input4.value});
console.log(arr_items);
}
Here is a small chunk of code, that I stripped down, that takes every input field, within a parent, that has a name attribute and uses those name attribute values as the keys in an object.
If uses the value of the input fields as the values in the object.
This allows the output object to change based on which input fields are in the parent element. If the input element does not have a name then it is not included.
This code can be reused and it always hands back the object needed.
const getEls = srcEl => {
const subs = [...srcEl.querySelectorAll('[name]')];
return subs.reduce((acc, sub) => {
acc[sub.getAttribute('name')] = sub.value;
sub.value = '';
return acc;
}, {});
subs[0].focus();
}
let results = [];
function doIt() {
const srcEl = document.getElementById('container');
const values = getEls(srcEl);
results.push(values);
console.log(JSON.stringify(values,0,20));
}
const btn = document.getElementById('submit');
btn.addEventListener('click', doIt);
const resultsBtn = document.getElementById('show');
resultsBtn.addEventListener('click', () => {
console.log(JSON.stringify(results,0,2));
});
<div id="container">
<p>Items Information:</p>
<input id="itemName" name="name" type="text" placeholder="enter item name"/><br/>
<input id="itemWeight" name="weight" type="number" placeholder="enter item weight(kg)"/><br/>
<input id="itemValue" name="value" type="number" placeholder="enter item value"/><br/>
<button id="submit">Enter</button>
<hr/>
<button id="show">Results</button>
</div>
There are two main aspects to note in the answer. One is that the array should be declared as a variable (not a constant), the other is that you should move the input var code into the function.
I added an alert so that you can see the outcome (wasn't sure if you wanted to allow them to be added without weight etc? This would cause confusion in your storage/retrieval of data.. so I moved the enter button)
Hope this helps
var arr_items = [];
function addValues() {
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
var item2 = input2.value + " " + input3.value + " " + input4.value;
arr_items.push(item2);
alert( [arr_items]);
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" name="item" placeholder="enter item name">
<input id="itemWeight" type="number" name="item" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" name="item" placeholder="enter item value">
<button id="name" onclick="addValues()">Enter</button>
</div>

How to make label to appear instead of name?

My form should contain key=>value pair, where key should be labelof the form and value should be details entered by user,
My issue is getting name of the field instead of label,
Expected output:
ENTER YOUR AGE:25
but i m getting output like this:
name-preview : 25;
How can it be achieved for expected output?
var result = [];
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
//console.log(label);
value = $this.siblings().attr('value');
//console.log(value);
result.push({
label: label,
value: value
});
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
>
how can i make for this elements:https://jsfiddle.net/ktgmtwd7/1/
Try this—when you change the the input value then the results array will auto update:
var result = [];
var input;
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
input = $this.next();
result.push({
label: label,
value: input.val()
});
console.log(result);
$this.next().on('keyup', function() {
result = [];
result.push({
label: label,
value: input.val()
});
console.clear()
console.log(result);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
</form>
<h3></h3>

Creating an array and skipping empty fields

I have the following form:
<input type="text" name="name1" id="names1" class="names" value="" placeholder="1) Name Here . . .">
<input type="text" name="name2" id="names2" class="names" value="" placeholder="2) Name Here . . .">
<input type="text" name="name3" id="names3" class="names" value="" placeholder="3) Name Here . . .">
<input type="text" name="name4" id="names4" class="names" value="" placeholder="4) Name Here . . .">
I am trying to create an array when the user clicks the submit button that stores each name:
var values = $('.names').map(function() { return this.value; }).get();
It works, but it also collects the empty fields which I do not need. I figure I require a conditional For statement for this, but I can't manage the syntax for it.
Thanks
Try this:
var values = $('.names').map(function() { if(this.value.trim() != '') return this.value; }).get();
Or:
var result = [];
var elements = getElementsByClassName('names');
for(var i = 0; i < elements.length; i++){
if(elements[i].value.trim() != '')
result.push(elements[i].value);
}
just select all .names with non empty value
var values = $('.names[value!=""]').map(function() { return this.value; }).get();
in real world you will need to store names also:
var values = $('.names[value!=""]').map(function() {
return {name: this.name,value: this.value};
}).get();
http://jsfiddle.net/oceog/7ZcbY/

Categories