How to write HTML5 Data Attribute as JavaScript Array Elements - javascript

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>

Related

Getting array out of data attribute without jQuery

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

Append value without attribute to json javascript

I have this json
["ESp", "lBe", "IBp"]
and i want to append "abc" to it so it can look like this:
["ESp", "lBe", "IBp", "abc"]
I have tried some methods but all of them add attributes and i don't want attributes , only values.
Thanks
Unless there is more to your array than I can see, this should work:
var myList = ["ESp", "lBe", "IBp"];
myList.push("abc");

How to convert Javascript string of array to array?

I have a data-type element for each option in select box. When I select an option I get the data-type as "[{:type=>"textbox", :label=>"Age"}]" (string of array of hashes). I want to convert this to array of hashes. I searched in google but couldn't get any. Can anyone help.
I tried replace as well,
str.replace('"[', '[').replace(']"' , ']'); but didnt get result. I want this in Javascript.
Works for this one sample anyway:
var a = '[{:type=>"textbox", :label=>"Age"}]';
var b = JSON.parse(a.replace(/:/g, '"').replace(/=>/g,'":'));
console.table(b);

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 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