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"])
Related
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 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()}
Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.