Getting array out of data attribute without jQuery - javascript

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

Related

geting an objects array stored in an hidden input

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"])

How to write HTML5 Data Attribute as JavaScript Array Elements

I have the following code:
HTML:
<span data-test="15, 17">
JavaScript / JQuery:
$value = [ $(object).data('test') ]
The $value variable now contains an array with one element. This element has the value "15, 17". I want to change the value of data-test in HTML in a way that $value will contain an array with two elements "15" and "17". In my environment I can only change the data-test attribute of the span. I can not change the JavaScript.
jsFiddle how the result currently looks like: ["15, 17"]
But I need it to be: ["15", "17"]
Is there any way?
Edit 1: I want to highlight the following part again: I can not change the JavaScript, only the HTML
Edit 2: I guess from the answers and comments below that with these requirements it is not possible to achieve the result I aimed for.
You need to store the value as a serialised array, in other words like this:
<span data-test="[15, 17]">
When jQuery stores it in the data cache object it will be deserialised to an array:
var value = $('span').data('test'); // == Array
console.log(value.length); // = 2
Updated fiddle
The right answer: is impossible what you want, if you can't change the Javascript.
However, using javascript, an way to do is:
var array = $('#demo').data('test').split(',');
Example: https://jsfiddle.net/3xfez/65/ (Don't forget to open the console.)
You need to store the array in JSON format.
See this fiddle: https://jsfiddle.net/3xfez/62/
The correct data value should be: [15, 17].
<span id="demo" data-test="[15, 17]"></div>

jQuery parsing html into JSON

I am currently using the following code:
jQuery('#book-a-service').click(function(){
var selectedServices = jQuery('.selected').parent().parent().html();
console.log(selectedServices);
});
and that returns:
<td rowspan="3">Brakes</td>
<td class="service-title">BRAKES SET</td>
<td class="service-description"><p>Setting of front and rear brakes for proper functioning (excluding bleeding)</p></td>
<td class="service-price">R <span id="price-brakes-set">R75</span><div id="select-brakes-set" class="select-service selected"></div>
</td>
which is what i want, except i need an array of all the elements with '.selected' class in JSON.. i just want to know how i could almost parse it in a way that i only get the contents of the td tags and as for the "service-price" only the numeric value and then how would i insert those values into a json object?
Any Help Greatly Appreciated..
jQuery is not my most formidable frameworks, but this seems to do the trick.
jQuery('#book-a-service').click(function(){
var selected = jQuery('.selected');
selected.each( function() {
var children = jQuery(this).parent().parent().find('td');
var json = {};
console.log(children);
json.type = jQuery(children[0]).text();
json.title = jQuery(children[1]).text();
json.description = jQuery(children[2]).find('p').text();
json.price = jQuery(children[3]).find('span#price-brakes-set').text();
console.log(json);
console.log(JSON.stringify(json));
});
});
in action: http://jsfiddle.net/3n1gm4/DmYbb/
When various elements share the same class and you select them with $(".class"), you can iterate through all of them using:
$(".selected").each(function() {
var element = $(this); // This is the object with class "selected" being used in this iteration
var absoluteParent = $(this).parent().parent();
// Do whatever you want...
var title_element = $(".service-title", absoluteParent); // Get service-title class elements in the context provided by "absoluteParent", I mean, "inside" of absoluteParent
var title = title_element.html();
});
In the specific case of prices, I don't know exactly what is the price (probably R75?). Anyway, it should be inside a div and then select that div to obtain the price. If it is R75, then note that the "id" property should be unique for every DOM object in your HTML.
Also note that, when getting HTML, you're only getting a string, not the actual element, so it will probably not be useful for getting new values in an easy way (you won't be able to navigate through DOM elements with an ordinary string, even if it represents HTML from an actual object). Always get jQuery objects and work with them, unless you actually need the HTML.
For generating a JSON string, just create a global array and add the objects/values you need there. Then you can obtain a JSON string using var jsonText = JSON.stringify(your_array);
Consider not doing this in Javascript, as it's not useful in the majority of cases. Just send the values through POST value to a script (PHP, for example) and in the PHP you will get the actual value. The other way (PHP to Javascript) will be useful to return JSON (using json_encode($a_php_array)) and then, in Javascript, transform to a JS array using var my_array = JSON.parse(the_string_returned_by_php);.

How can I get a HTML data value as a string with jQuery?

I have the following in my source HTML:
<li>Test</li>
I want to get the value of the data attribute so I am using the following:
var abc = $(this).data('value');
This works okay BUT not if there is a leading zero. For example the above
placed the value "1" into abc.
Is there a way that I can get it not to convert the "01" into "1" ?
this.dataset.value;
// Or old school
this.getAttribute('data-value');
const a = document.querySelector("a");
console.log('Using getAttribute, old school: ', a.getAttribute('data-value'));
console.log('Using dataset, conforms to data attributes: ', a.dataset.value);
<ul>
<li>Test</li>
</ul>
Thanks to #MaksymMelnyk for the heads up on dataset
You can use the attr() operator of jQuery:
var abc = $(this).attr('data-value');
From the jQuery data() documentation, it appears that you have to use .attr() to prevent the automatic type conversion:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
So, not to duplicate other answers, but rather to reinforce, the way to access the attribute without doing type conversion is:
var abc = $(this).attr('data-value');
$(this).attr('data-value');
This will return the string value with the leading 0.
have you tried?:
$(this).attr('data-value');
or
$(this).attr('data-value').toString();
Try :
this.data('value');
I think this is best way to get data attribute value.
<article id="electric-cars" data-columns="3"data-index-number="12314" data-parent="cars">
</article>
const article = document.querySelector('#electric-cars');
article.dataset.columns // "3"
article.dataset.index-number // "12314"
article.dataset.parent // "cars"

How to retrieve value from object in JavaScript

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.

Categories

Resources