jQuery convert data-* attributes to lower camel case properties - javascript

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
if (data['class-name']) {
options.className = data['class-name'];
}
if (data['align-x']) {
options.alignX = data['align-x'];
}
if (data['align-y']) {
options.alignY = data['align-y'];
}
if (data['offset-y']) {
options.offsetY = data['offset-y'];
}
if (data['offset-x']) {
options.offsetX = data['offset-x'];
}
$this.poshytip(options);
});

I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[keys] = data[keys];
}
// For older versions of jQuery you can use $.camelCase function
for (var keys in data) {
options[$.camelCase(keys)] = data[keys];
}
});
DEMO
for jQuery 1.4.4,
$('.poshytip-trigger').each(function(index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[camelCase(keys)] = data[keys];
}
});
//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
return (letter + "").toUpperCase();
});
}
DEMO for 1.4.4

Something like this - It does convert offset-x to offsetX:
http://jsfiddle.net/8C4rZ/1/
HTML:
<p data-test="sdsd" data-test2="4434"></p>​
JavaScript:
$(document).ready(function() {
var options = {};
for (var key in $("p").data()) {
options[key] = $("p").data(key);
}
console.log(options);
});​
But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take all data- attributes.

var names = ["className", "alignY", ...];
$(names).each(function(ind, name){
var dataName = name.replace(/[A-Z]/, function(letter){
return letter.toLowerCase();
});
if(data[dataName]){
options[name] = data[dataName];
}
});
Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.

Try using a for in loop.
var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x'];
for (x in array) {
if(data[array[x]]) {
options[array[x]] = data[array[x]];
}
}
Update: In response to the OP's clarification, he could write something like this:
var Pair = function(hyphenated, camcelCased) {
this.hyphenated = hyphenated;
this.camelCased = camelCased;
}
var array = [
new Pair('class-name', 'ClassName'),
new Pair('align-x', 'alignX'),
new Pair('align-y', 'alignY'),
new Pair('offset-x', 'offsetX'),
new Pair('offset-y', 'offsetY')];
var i, optionNameHyphenated, optionNameCamelCased;
for(i = 0; i < array.length; i++) {
optionNameHyphenated = array[i]['hyphenated'];
optionNameCamelCased = array[i]['camelCased'];
if (data[optionNameHyphenated]);
options[optionNameCamelCased] = data[optionNameHyphenated];
}

Related

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

Accessing all elements in array

I'm learning javascript and to practice traversing the DOM I have created a method that returns an array of parent elements based on the 'nodeName'. I have done this so that I could select all of a certain element (that is a parent of another) and style them or change them, etc.
Element.prototype.specificParent = function(nodeName1) {
nodeName1 = nodeName1.toUpperCase();
var x = this;
var matches = [];
var allParents = [];
while(x.parentNode !== null) {
allParents.push(x.parentNode);
x = x.parentNode;
}
for(i = 0; i < allParents.length; i++) {
if(allParents[i].nodeName === nodeName1) {
matches.push(allParents[i]);
}
}
return matches;
}
This, kind of, has my desired effect. However, to access all the elements in the returned array I would need to use something like a for loop, because I can only access the elements like this:
var parents = document.getElementById("startHere").specificParent("div"); //gets all parent div elements and returns the array
//I can then style them individually:
parents[0].style.background = "black";
parents[1].style.background = "black";
//etc, etc, etc
//or I could use a for loop to style them all:
for(i = 0; i < parents.length; i++) {
parents[i].style.background = "black";
}
What I want to do is this:
var parents = document.getElementById("startHere").specificParent("div");
parents.style.background = "black"; //changing all the elements in the array
Is there a way to change the "specificParent" method so that it allows this?
This may seem like a pointless exercise but I am learning!
Thanks
Probably the simplest way is to use arrays API.
If you can use ES6, it would look like so:
parents.forEach(parent => parent.style.background = "black")
In ES5 slightly less clear:
parents.forEach(function(parent) { parent.style.background = "black"; })
Based on your comments you can do this:
Element.prototype.specificParent = function(nodeName1) {
nodeName1 = nodeName1.toUpperCase();
var x = this;
var matches = [];
var allParents = [];
while(x.parentNode !== null) {
allParents.push(x.parentNode);
x = x.parentNode;
}
for(i = 0; i < allParents.length; i++) {
if(allParents[i].nodeName === nodeName1) {
matches.push(allParents[i]);
}
}
function setStyle(styleKey, styleValue) {
matches.forEach(function(parent) { parent.style[styleKey]= styleValue; });
}
return {
elements : matches,
setStyle : setStyle
};
}
And use it like so:
var parents = document.getElementById("startHere").specificParent("div");
parents.setStyle("background", "black");

How to build 2 dimensional array from a string of options for a select tag in Javascript?

In Javascript, I have a string of options for a select tag. This is my string:
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>';
In Javascript, I want to convert it to a 2-dimensional Array where 1st dimension will store the id and 2nd dimension will store the text of an option.
How can I do that? I am looking for Javascript solution; I am open to 3rd party solutions also like jQuery.
You can do it by converting the string into DOM options, then iterating over them, so:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsAsArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsAsArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
You can also do it by parsing the string, but that may be more work.
Edit
You can also use the new DOMParser, but fairly recent browsers are required for support:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
The above creates an array of:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
if you want pairs like:
[[id0, text0], [id1, text1], ...]
Then the above can be:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
which can be reduced to:
function optionsAsArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}
I have used jQuery for the solutions below.
If you want the array to be made from DOM then you can do this
<select id="selectopt"><option id="">Select</option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option></select>
var arr = [];
console.log('====array 1===');
$('select option').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
arr.push([id, value]);
console.log(arr);
});
If you need it to be made using the string then use $.parseHTML for converting the string to DOM nodes.
var arr2 = [];
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option>';
var options = $.parseHTML(myOptionsString);
console.log('====array 2===');
for (var i=0; i< options.length; i++){
var id1 = options[i].id;
var value1 = options[i].value;
arr2.push([id1, value1]);
console.log(arr2);
}
Fiddle Demo

mapping Json data and adding data attr

I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:
<div class="name" data-key="sth"> sty</div>
Key can be got like that: ['streme'].key
here is my buggy JS:
function getExistingLinks() {
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link'].key
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
// $('div').each( function(index) {
$('div')[index].data("key") = keys[index];
}
container.appendChild(div);
});
});
return false;
}
names.forEach(function(name,index) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key") = keys[index];
});
You need to remove the quotes in the $() selector!
As per your comment, may be try doing like:
var i = 0;
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$('div').addClass("name");
$('div').data("key", keys[i]);
container.appendChild(div);
i++;
});
the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.
psuedo code as not sure what name represents in your innerHTML:
var divs = [];
for (var i, len = names.length; i < len; i++) {
divs.push($(''+name+'').data("key", keys[i]));
}
$container.append(divs);
http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3
try something like this
$('.name').data('key') //will give you sth

Find all elements whose id begins with a common string

I have a XSL that created multiple elements with the id of "createdOn" plus a $unique-id
Example : createdOnid0xfff5db30
I want to find and store these in a variable using JavaScript. I've tried
var dates = document.getElementsById(/createdOn/);
but that doesn't appear to work.
Using jQuery you can use the attr starts with selector:
var dates = $('[id^="createdOnid"]');
Using modern browsers, you can use the CSS3 attribute value begins with selector along with querySelectorAll:
var dates = document.querySelectorAll('[id^="createdOnID"]');
But for a fallback for old browsers (and without jQuery) you'll need:
var dateRE = /^createdOnid/;
var dates=[],els=document.getElementsByTagName('*');
for (var i=els.length;i--;) if (dateRE.test(els[i].id)) dates.push(els[i]);
You should have just used simple CSS selector together with JavaScript's .querySelectorAll() method.
In your case :
var dates = document.querySelectorAll('[id^="createdOnId"]');
Because you didn't tag jQuery, and you probably don't need it, my suggestion would be to add a class to these elements when you create them. Then use the getElementsByClassName() function that's built into most browsers. For IE you would need to add something like this:
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
function idsLike(str){
var nodes= document.body.getElementsByTagName('*'),
L= nodes.length, A= [], temp;
while(L){
temp= nodes[--L].id || '';
if(temp.indexOf(str)== 0) A.push(temp);
}
return A;
}
idsLike('createdOn')
Try the following:
var values = new Array(valueKey_1);
var keys = new Array("nameKey_1");
var form = document.forms[0];
for (var i = 0; i < form.length; i++) {
name = form.elements[i].name;
var startName = name.toLowerCase().substring(0, 18);
if (startName == 'startStringExample') {
values.push(name.value);
keys.push(name);
}
}

Categories

Resources