I have a couple of input fields with the following ID:
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
I fetch data in JSON format via my ajax call and push() certain values in my array.
How could I create a loop that will loop through the array and then inserts each value in one of the above input fields?
so let's say I have the following array:
var testArray = ['hi', 'bye', 'stackoverflow'];
and I have the following 3 input fields:
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
Whenever I loop through it I unfortunately get the highest value in all of my input fields.
I try to loop through my array in JavaScript and insert each value in each input field. so testArray[0] should go in the first input field, testArray[1] in the second input field and testArray[2] in the third.
Sources I used: Find DOM element by ID when ID contains square brackets?
The id in dom is always unique.Instead use document.querySelectorAll to get all the element with same name then loop through them and use the index to check if an element exist in the index of testArray. If so then set the value of the input
var testArray = ['hi', 'bye', 'stackoverflow'];
document.querySelectorAll('[name="numberC[]"]').forEach(function(item, index) {
if (testArray[index]) {
item.value = testArray[index]
}
})
<input type="text" name="numberC[]" id="numberC[1]">
<input type="text" name="numberC[]" id="numberC[2]">
<input type="text" name="numberC[]" id="numberC[3]">
If you change your HTML to have different ids
<input type="text" id="numberC[1]"/>
<input type="text" id="numberC[2]"/>
<input type="text" id="numberC[3]"/>
you can easily set the values like this:
var testArray = ['hi', 'bye', 'stackoverflow'];
for(let i in testArray) {
document.querySelector('#numberC\\[' + (+i+1) + '\\]').value = testArray[i];
}
Related
I have an object of URL parameters that I had originally appended to a form using this method, but I am attempting to adjust that to also create a single string concatenated from each of the values of the inputs to then.
I have this code here, which creates the inputs and prepends them to the top of the form:
for (property in parameters) {
$('<input>', {
type: 'hidden',
id: `${property}`,
class: 'urlparameter',
name: `${property}`,
value: `${property}: ${parameters[property]}`
}).prependTo('form');
}
That code creates this inputs, from the testing URL I am currently using:
<input type="hidden" id="utm_content" class="urlparameter" name="utm_content" value="utm_content: comm">
<input type="hidden" id="utm_medium" class="urlparameter" name="utm_medium" value="utm_medium: email">
<input type="hidden" id="utm_source" class="urlparameter" name="utm_source" value="utm_source: sig">
From there, I am trying to loop through all the inputs with the class urlparameter and grab the value and append it to the previous input value for a single string. Right now I am just trying to console.log them just for testing sake. No matter what I do, it keeps listing them all individually, or I break the syntax and can't figure out how to fix it.
The only way that comes close is this:
var inputs = $(".urlparameter");
for(var i = 0; i < inputs.length; i++){
let inputvalue = $(inputs[i]).val();
console.log(inputvalue + ",");
}
This creates the following:
utm_content: comm,
utm_medium: email,
utm_source: sig,
What I am trying to get is:
utm_content: comm, utm_medium: email, utm_source: sig,
How do I get them all to iterate and add to a single string on one line?
Use .map() and .join().
console.log(inputs.map((i, el) => el.value).get().join(','));
You can use .map to get all the values, convert to an array, then call Array#join.
let res = $(".urlparameter").map((i, el) => $(el).val()).toArray().join(', ');
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="utm_content" class="urlparameter" name="utm_content" value="utm_content: comm">
<input type="hidden" id="utm_medium" class="urlparameter" name="utm_medium" value="utm_medium: email">
<input type="hidden" id="utm_source" class="urlparameter" name="utm_source" value="utm_source: sig">
I would suggest using reduce, which is JavaScript's version of an accumulator.
console.log(
Array.prototype.reduce.call($('input.urlparameter'),(p,v) => p + v.value + ', ',"")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="utm_content" class="urlparameter" name="utm_content" value="utm_content: comm">
<input type="hidden" id="utm_medium" class="urlparameter" name="utm_medium" value="utm_medium: email">
<input type="hidden" id="utm_source" class="urlparameter" name="utm_source" value="utm_source: sig">
I am try to set the value of an input field for which i can not assign an ID so I can't use document.getElementById. Is there any other way I can assign a value to this text input field that has a name?
You can use a basic queryselector to select attributes and to do so, you need to put the attributes name between brackets [ and ]. The attributes can have an optional value too by using an equal sign.
Here is a working example:
document.querySelector('[name=hello]').value = 'Hello World'
<form>
<input type="text" name="hello">
</form>
Use document.getElementsByName: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
const el = document.getElementsByName('name')[0];
el.value = 'someValue';
You can use Document.getElementsByname().
This method returns an array of elements, so you might want to access the first element in the array.
Live Example:
var myInput = document.getElementsByName("my-input")[0];
myInput.value = "Some Text";
<input type="text" name="my-input">
If the input field, named 'x', for example, is in a form with name 'f' for example, then:
document.f.x.value = 'some value';
function test()
{
document.f.x.value = 'It works!';
}
<html>
<body>
<form name="f">
<input name="x" size="20">
<br>
<input type="button" value="Test" onclick="test();">
</form>
</body>
</html>
I am building an full-stack application in where I have a form submitting data to one of my post routes. On this form, I have all of my input fields bundled into req.body.model, thanks to the fact that I can add a name attribute with square brackets around the key, like so name="model[height]".
This should equate to something like this:
model = {
height: //value,
weight: //value,
age: //value
}
However, I want one of the values to be an empty array so I can push URLS into the array, like so:
model = {
height: //value,
weight: //value,
age: //value,
urls: [//urls here]
}
Since you can automatically create an object using the name attribute, I was wondering if there was a way to create a nested array using the name attribute as well?
Code snippet
<form>
<input type="text" name="model[height]">
<input type="text" name="model[weight]">
<input type="text" name="model[age]">
// these 2 inputs would go into the urls key in the models object
<input type="text">
<input type="text">
<button>Submit</button>
</form>
Not sure if I worded this properly...but let me know if I can explain in further detail.
If you pass index next to the property you can create an array. Something like this
// these 2 inputs would go into the urls key in the models object
<input type="text" name="model[urls][0]">
<input type="text" name="model[urls][1]">
Not sure if I got what you are trying to do exactly, but it seems like you can first process the submitted data and then send the processed data to wherever you want to send it. It's a bit more verbose, but I feel like it may give you more flexibility when organising your data. So maybe you can do something like this:
html
<form name="model">
<input type="text" id="height">
<input type="text" id="weight">
<input type="text" id="age">
<input type="text" id="url1">
<input type="text" id="url2">
<button onclick="processForm()">Submit</button>
</form>
script
function processForm() {
let height = document.querySelector("#height").value;
let weight = document.querySelector("#weight").value;
let age = document.querySelector("#age").value;
let url1 = document.querySelector("#url1").value;
let url2 = document.querySelector("#url2").value;
let model = {
"height": height,
"weight": weight,
"age": age,
"url": [url1, url2]
}
// now you can send model object to where it is needed
}
I have multiple input fields under different headings:-
<label>User</label>
<input type="text" ng-model="a.arr.username" name="arr[0]"/>
<input type="text" ng-model="a.arr.userdob" name="arr[0]"/>
<input type="text" ng-model="a.arr.userpanNo" name="arr[0]"/>
<label>Employee</label>
<input type="text" ng-model="a.arr.empname" name="arr[1]"/>
<input type="text" ng-model="a.arr.empdob" name="arr[1]"/>
<input type="text" ng-model="a.arr.emppanNo" name="arr[1]"/>
<label>Daily Workers</label>
<input type="text" ng-model="a.arr.dwname" name="arr[2]"/>
<input type="text" ng-model="a.arr.dwdob" name="arr[2]"/>
<input type="text" ng-model="a.arr.dwpanNo" name="arr[2]"/>
I want to save above data in the format:- [{a.arr.username:any value},{a.arr.empname:any value},{a.arr.dwname:any value}]. But the structure I am getting is:- {a.arr.username:any value,a.arr.empname:any value,a.arr.dwname:any value}.
Is there any way to do this?
Where you are storing data you will have to store it like :
a.arr=[];
//here you have to define object for each index before making keys of it.
a.arr[i]={};
Try this
var arr=[]; arr.push({'a.arr.username':$scope.a.arr.username,{'a.arr.empname':$scope.a.arr.empname}})
Basically, you want to make your object as an array of it's properties. I suggest you to leave the code as it is and just add a code to make another controller property which will hold the array of those properties.
To get the array of properties, below code will help you:
var x = {username: "any value", empname: "any value", dwname: "any value"};
var newArr = [];
var properties = Object.keys(x);
for(var i=0;i<properties.length;i++){
newArr.push({});
newArr[newArr.length - 1][properties[i]] = x[properties[i]];
};
Let me know if you need to understand anything else regarding this.
Best Regards
So, I have a group of key value pairs on a document. They are sets of 2 inputs. I'll also need to reject any non-pairs, so if there is only a key or only a value, I don't want one of those sides included.
Like this, input1 is key, input2 is value:
<div id = "group_o_inputs">
<div class="ind_form">
<input class="input1" type="text"><input class="input2" type="text">
</div>
<div class="ind_form">
<input class="input1" type="text"><input class="input2" type="text">
</div>
<div class="ind_form">
<input class="input1" type="text"><input class="input2" type="text">
</div>
</div>
How could I extract these, I am thinking of putting them into a json array. I am thinking of a syntax like this:
var items1 = $("#group_o_inputs .ind_form .input1");
var items2 = $("#group_o_inputs .ind_form .input2");
Then I can use the two arrays with a for loop or something? And like I mentioned, since the user can leave one input out by accident, I'd like to account for that. Eventually it would come out like this:
{
key: value, key: value, key: value, key: value
}
Iterate the ind_form class and map an array of objects
var data = $('.ind_form').has('.input1,.input2').map(function(){
return {
key : $(this).find('.input1').val(),
value : $(this).find('.input2').val()
}
}).get();
Produces
[
{key: 'input1-1 value', value : 'input2-1 value'},
{key: 'input1-2 value', value : 'input2-2 value'}
]