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()}
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'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>
I'm trying to submit a complicated form with jQuery. I want to submit the values to the server in an AJAX Request.
Given this array of <tr> values that I've got from jQuery Datatable plugin, how can I easily extract the data-id values into a format suitable for submitting to the form e.g. something like:
{
id: 65537, id: 32768, id: 65539
}
I have tried:
> $(table.rows().nodes())
> [<tr role="row" class="odd" data-id="65537">…</tr>, <tr role="row" class="even" data-id="32768">…</tr>, <tr role="row" class="odd" data-id="65539">…</tr>]
> $(table.rows().nodes()).length
3
What code is needed to just get the data-id values?
Updated Edit
Actually, I've just tested the form by hardcoding the values, and I need to convert it to look like this 0 indexed array, obviously with the numbers from the id field:
var formData = {"products[0]": 65537,
"products[1]": 65540};
Thank you.
Use this and the data variable will have all you want
$(function(){
var data = [];
$.each($('table.rows().nodes()'),function(k,v){
data.push($(this).data('id'));
});
console.log(data);
})
Well just loop through each tr and push its data-id with unique key-value paid into an array.
DEMO
var rows=$(table.rows().nodes())
var values=[];
$.each($(rows),function(key,value){
var vals ={}
vals[key]=$(this).attr('data-id')//or values.push($(this).attr('data-id');
values.push(vals);
});
console.log(values);
Note : You cannot have duplicate keys in an object say id as mentioned in your question so better use some unique index which you can obtain from key parameter of $.each
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]