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]
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 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.
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>
In one of my HTML page, there are a few input fields with the same name attributes since I want to send them as an array to another PHP for back-end transactions.
Suppose the input field like below :
<input type="text" name="language_names[]" value="english">
<input type="text" name="language_names[]" value="french">
<input type="text" name="language_names[]" value="spanish">
Now I want to use Jquery to send this array? I am using the .post() method for this, I know for single value it could be send as {key1: value1, key2:value2...}, but for array How can I do it like this ? I guess it should be close to
{'language_names[]' : $('#input[name="language_names[]"]').val()}
But it doesn't work (I check the request body). Anyone can help ?
Use serialize function of jquery like this
// This returns a json representation of your form values
$('#formid').serialize();
Since you need a simple array with the values of those specific input elements, you could use something like:
function getLanguageValues() {
var language_names = [];
$.each($("input[name=language_names\\[\\]]"), function (indexInArray, valueOfElement) {
language_names.push($(valueOfElement).val());
});
return language_names;
}
Here is the jsfiddle.
Or you can also do this :
{'language_names[]' : $('input[name=language_names\\[\\]]').serialize()}