Javascript: how to extract string from attribute via Regexp - javascript

How can I extract the string from a certain data attribute via regexp.
<button data-loading-text="Some text on loading" data-toggle="button">Button</button>
<button data-finished-text="Some text on finished" data-toggle="button">Button</button>
And my javascript is
var Buttons = document.querySelectorAll([data-toggle="button"]);
[].forEach.call(Buttons, function (item) {
var data = item.getAttribute('data-'+INEEDTHIS+'-text')
var option = INEEDTHIS
return new Button(item,option);
})

You can use the Element.attributes property:
var attrs = item.attributes;
for(var i = attrs.length - 1; i >= 0; i--) {
var m = attrs[i].name.match(/^data-(.*)-text$/);
if (m) {
var option = m[1];
// do something
}
}

You can use the .attr() method of jQuery

Related

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

jQuery convert data-* attributes to lower camel case properties

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];
}

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);
}
}

getElementByName & Regex

How do I loop through all elements using regular expression in getElementByName?
If you mean like:
var elementArray = document.getElementsByName("/regexhere/");
then no that would not be possible.
To do what you want to do you would have to get all the elements, then go through each one and check the name of it.
Heres a function that will go through all the elements and add all the elements with a certain name to an array:
function findElements(name)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].name) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elName = "customcontrol";
var elArray = customcontrol(elName);
Or it might be easier by className
function findElements(className)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elClassName = "classname";
var elArray;
if (!document.getElementsByClassName)
{
elArray= findElements(elClassName );
}
else
{
elArray = document.getElementsByClassName(elClassName);
}
This would do what you want, without the need for getElementByName.
Although I think you meant getElementsByName
If you wanted to look for an element with only the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
If you wanted to look for an element with that STARTED with the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name);
EDIT:
If your using jQuery, which would be easier, then this would do:
var elArray = $("*[name^='customcontrol']");
//Use JavaScript to loop through
for (var a = 0; a< elArray.length;a++)
{
//Loop through each element
alert(elArray[a]);
}
//Or
$("*[name^='customcontrol']").css("color","red"); //Or whatever you want to do to the elements
Use a custom selector in jQuery. You probably want an example with parameters.

URL Bar id=1 Into jQuery ID

i want to get the id from the url bar and insert it into the href
$("a[href='send_message.php?act=pm&id=$id']").colorbox({width:"500", height:"350", iframe:true});
there's a jquery plugin to make this ridiculously simple:
see: http://plugins.jquery.com/project/query-object
e.g.
var id = $.query.get('id');
$("a[href='send_message.php?act=pm&id="+id+"']").colorbox({width:"500", height:"350", iframe:true});
For those not using jQuery or any other JS library:
var searchString = document.location.search;
// strip off the leading '?'
searchString = searchString.substring(1);
var gvPairs = searchString.split("&");
var getVars = [];
for (i = 0; i < gvPairs.length; i++)
{
var gvPair = gvPairs[i].split("=");
getVars[gvPair[0]] = gvPair[1];
}
So if the URL string was index.php?id=3&page=2&display=10 then:
getVars['id'] = 3;
getVars['page'] = 2;
getVars['display'] = 10;

Categories

Resources