I have a form where you can append additional input if needed. So I named my form like this.
<input type="text" name="sample[]" />
I want to access all the value of the inputs with a name "sample[]" and store it in an array using javascript. I used this code below:
var sample = document.getElementsByName(sample[]);
How can I get all the values individually? Any help would be greatly appreciated. Thank you!!!
Add this to your js function and you will get input values in values array.
Here I am getting a NodeList of all elements with name = "sample[]" and converting to Array for easy processing of data.
var sample = Array.prototype.slice.call(document.getElementsByName('sample[]'));
var values = sample.map((o) => o.value);
Tested it and following is the link to fiddle.
https://jsfiddle.net/mfw4rv9o/13/
String value 'sample[]' is totally different from eval value of sample[]. Hence is the confusion over all.
If you're very sure you want to pass 'sample[]' as a (string) value of name prop of , make sure you stringify it and add it.
The name of the input is name="sample[]". The parameter of getElementsByName is the value of the name attribute of the element(s) so that should be "sample[]".
getElementsByName will return a NodeList for which you could use a foreach to loop over, use item to return a node from a NodeList by index or use an index sample[0].
To get all the values in an array in es6 you could use the spread operator and map:
let items = [...document.getElementsByName("sample[]")].map(i => i.value);
var sample = document.getElementsByName("sample[]");
console.log(sample[0].value);
console.log(sample.item(0).value);
let items = [...document.getElementsByName("sample[]")].map(i => i.value);
console.log(items);
<form>
<input type="text" name="sample[]" value="value1" />
<input type="text" name="sample[]" value="value2" />
</form>
In ES6:
var values = [...document.querySelectorAll("input[name='sample[]']")].map(x => x.value);
But I would refrain from using sample[] as the input name.
var sample = document.getElementsByName('sample[]');
Add quotes between sample[]. Try to avoid [] in input name.
Related
I wish I could get an array of objets stored in an hidden input.
Thanks
Here is the hidden input in the html page :
<input type="hidden" name="idMusicians" value="[{"id":7069,"project_id":324,"name":"Gator","first_name":"Ali","instrument_id":28,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07",",{"id":7070,"project_id":324,"name":"Zhette","first_name":"Annie","instrument_id":29,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07",}]">
I tried this, but it doesn't work :
var musicians = $("#idMusicians").map(function(){
var musician = this;
return musician;
}).get();
And this also without success :
var musicians = $("#idMusicians").data('value');
You can get the value in your input if you give it an id and then use:
$("#idMusicians").val();
Once you have your value in a variable, you can parse it as JSON, which will then allow you to iterate over your array to access its objects. However, in order for JSON.parse() to work, the value in value needs to be valid JSON. At the moment, your value isn't valid JSON as it doesn't close your first object properly. If you fix this, you can then use JSON.parse() without getting errors.
See example below:
const musicians = $("#idMusicians").val();
const res = JSON.parse(musicians);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="idMusicians" name="idMusicians" value="[{"id":7069,"project_id":324,"name":"Gator","first_name":"Ali","instrument_id":28,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07"},{"id":7070,"project_id":324,"name":"Zhette","first_name":"Annie","instrument_id":29,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07"}]">
# is the id selector, but idMusicians is a name property. Try changing it to id=idMusicians or select by name attribute $(input[name="idMusicians"])
Context: The following function is called within a loop that is iterating through all of the inputs in a form.
collectCurrentSetting = function(index, element) {
element = $(element);
var name = element.attr('name');
var value = element.val();
currentValues[name] = value;
}
There is a section in that form that contains multiple inputs that use brackets in the name attribute to annotate that they belong as a part of an array. For sake of argument, let's say they are attributes of a person like so:
people[0][firstName]
people[0][lastName]
people[1][firstName]
people[2][lastName]
The goal is that it should create something like this:
currentValues[people][0][firstName] = 'jimbo';
It is technically, in that format, but it's treating everything in the brackets like a single key. And once it gets sent to the server it looks something like this:
currentValues["people[0][firstName"] = 'jimbo';
Question: How do I get it to properly parse these values and store them as an array in the currenValues variable?
Problem: So any time I attempted to use any built in parsing tools, it always used the entire name field as the key/name of the array. As such, the key for the array was person[0][firstName], whereas that should have been 3 keys each nested in a new layer of a multidimensional array.
Solution: However, I have just discovered a very helpful jQuery plugin that accomplishes this task perfectly:
https://github.com/macek/jquery-serialize-object
Now, you simply select the form and call serializeObject() and the result is a perfectly formatted multidimensional array.
Example:
// The form HTML
<form id="myForm">
<input type="text" name="test2" />
<select name="important_select">
// Select options go here.
</select>
<input type="text" name="categories[0][category_name]" />
<input type="text" name="categories[1][category_name]" />
<input type="text" name="categories[2][category_name]" />
</form>
// Include the dependancies
<script src="jquery.min.js"></script> // This requires jQuery as a dependancy
<script src="jquery.serialize-object.min.js"></script> // Be sure to include the plugin
// Parse the form into a multidimensional array.
var currentValues = $("#myForm").serializeObject();
The result upon using console.log(currentValues) is as follows:
categories: {
0: {category_name: "World Cuisine"},
1: {category_name: "Diet of Course"},
2: {category_name: "Meal Type"}
},
important_select: "2",
test2: ""
I want to work with an array to pass through using data-attribute.
In my HTML-tag I've this attribute:
data-toshow='["tblp"]'
I can access and use it with jQuery when using
$().data('toshow')
But when using dataset.toshow I don't get the same result. I actually don't get an array.
Can someone explain this to me? And give me the answer how to do the same without the use of jQuery?
jQuery's .data() method automatically tries to convert the string in your custom data attribute to whatever type it appears to be (in this case an array). JavaScript just treats it as a string, so you need to parse the string to get the same array output you get with jQuery. For example:
// jQuery approach
const jqtest = $('div').data('toshow');
console.log(jqtest);
// Plain JavaScript approach
const jstest = JSON.parse(document.querySelector('div').dataset.toshow);
console.log(jstest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toshow='["tblp"]'></div>
//Use dataset to get a string of all data-* props
const stringVal = document.querySelector('#divA').dataset['toshow'];
//Parse the value of "data-toshow" to get your array
const array = JSON.parse(stringVal);
console.log(array);
<div id="divA" data-toshow='["tblp"]'></div>
Assuming you have HTML similar to:
<div id="theThing" data-toshow='["tblp"]'></div>
or
<div id="theThing" data-toshow='["tblp","arrItem2","arrItem3"]'></div>
//jQuery
var container_jq = $("#theThing");
var container_jq_dataArr = decodeURIComponent(container_jq.data('toshow')).split(",");
//vanilla
var container_vanilla = document.getElementById("theThing");
var container_vanilla_dataArr = JSON.parse(decodeURIComponent(container_vanilla.dataset.toshow));
console.info({jQuery: container_jq_dataArr,vanilla: container_vanilla_dataArr});
jsfiddle in action
Every HTMLElement has dataset property, this property could be null if there is no data attribute in the element, but if there is any data attribute, the dataset property is an array containing all the data values declared on the element.
Given an html like <div data-name='Usher' data-max-number='5'> There are two ways you can get this data attribute using javascript,
One way is to call the element.getAttribute('data-name') or element.getAttribute('data-max-number') of that element.
The second way is through the dataset property of the element. which you would use element.dataset.name to obtain the name attribute or element.dataset.maxNumber
NOTE: How max-number becomes maxNumber. This is how you access hyphen seperated data-set attribute, using camelCase
I'm trying to have a form that allows to send json from a form.
One of my input should be an array of the form ["1","2","3"] or ["foo","bar"]
I'm having an issue with my user passing the array in a SINGLE field from the form.
I would like my user to be able to input(html) [1,2,3] and have it converted to ["1","2","3"] or [foo,bar] and have to converted to ["foo","bar"].
json.Stringify obviously doesn't work in that case.
I'm having difficulties doing that as i do not know in advance that the input field will be an array or a string or a number.
I'm currently storing the content of my form in an object in my controller but obviously when inputing [1,2,3] i get "[1,2,3]" and when inputing ["1","2","3"] that data passed i get [\"1\",\"2\",\"3\"]
Is there a tool/function to does that automatically ?
Note:
-the input of 1 field NEEDS to be an array is i don't know in advance the type of the array nor the number of items it will have.
- I'm using angular but that's more of a js problem i believe.
You could use this cast function:
function cast(s) {
if (s.match(/^\s*\[.*\]\s*$/)) { // array notation
return s.trim().replace(/^\[|\]$/g, '').split(',').map(cast);
}
// remove wrapping quotes if present
return s.trim().replace(/^'(.*)'$|^"(.*)"$/g, '$1$2');
}
// I/O for demo
document.querySelector('input').addEventListener('input', function () {
var s = cast(this.value);
document.querySelector('span').textContent = JSON.stringify(s);
});
Your input: <input><br>
Output JSON: <span></span>
Note that the user can optionally type the quotes. Whether they do so or not, the result will be the same. It works to same for singular values: if quotes are wrapped around the input, they give the same string as without.
You could use map function:
var arr = [1,2,3];
arr = arr.map(function(el){return el.toString()});
//The output array will be ["1","2","3"]
and for [foo, bar] I think you can't convert it because it's a variable and you will get it's value instead of it's name.
i wish that helps you.
Instead of user inputting [1,2,3], notify user to input 1,2,3 or foo,bar.
let arr = [];
for (let input of document.querySelectorAll("form input")) {
arr.push(input.value.split(","));
}
console.log(
JSON.stringify(arr[0])
, JSON.stringify(arr[1])
)
<form>
<label>input number,number,number:</label>
<input placeholder="input number,number,number" value="1,2,3"/>
<br>
<label>input word,word,word:</label>
<input placeholder="input word,word,word" value="foo, bar"/>
</form>
Is it possible to have a input field where user can input the array and the function which it passes the value treats it as an array? To be clear, is this possible using javascript and HTML?
<input....of some type....>
function (from input as a form of array){
calculation
}
I would like to have an input field where I can input something like [1,2,3,4..] or [(1,2),(2,3)...] and pass that to the function without any further manipulation, hoping that it will treat the array as array not as 'text'. I think I can use eval but I don't want to trust the user.
JSON.parse() will help out here
Support is IE8+
HTML:
<input type="text" id="t1" value="[1,2,3,4,5,6]"/>
<input type="text" id="t2" value="[[1,2],[3,4],[5,6]]"/>
JavaScript:
var a1 = JSON.parse(document.getElementById("t1").value);
var a2 = JSON.parse(document.getElementById("t2").value);
console.log(a1);
console.log(a2);
Fiddle
http://jsfiddle.net/NNcg7/
You can create an array from the text input if the data is entered with a standard delimiter. Meaning, if the user inputs 1,2,3,4 into the text field, you can create an array in Javascript using the split method.
var myInputValue = document.getElementById(yourElementId); //value will be "1,2,3,4"
var myArray = myInputValue.split(","); //value will be [1,2,3,4]