Reputation: 17
I'm trying to set a variable attribute name, ie <a data-33="string">
, with 33 being a random number generated by Math.random().
I have tried:
var randomNum1 = Math.floor(Math.random() * (200 - 100 + 1)) + 100;
var attrb = 'data-' + randomNum1.toString();
$(this).attr({
attrb : 'someString',
attrb2 : 'someString'
});
But instead of adding an attribute of data-randomNumber="someString", it adds attrb="someString"
I'm trying to pass multiple attributes. I know I'm missing a basic javascript concept, but any help would be appreciated!
Upvotes: 0
Views: 119
Reputation: 3039
Try this:
function getRandom(){
return (Math.floor(Math.random() * (200 - 100 + 1)) + 100).toString();
}
var attrs = {};
attrs["data-" + getRandom()] = "something";
attrs["data-" + getRandom()] = "something";
attrs["data-" + getRandom()] = "something";
//console.log(attrs);
$(".target").attr(attrs);
This will do something like:
<div class="target" data-108="something" data-123="something" data-107="something">something</div>
What I am doing is first creating the attributes obj separately, then passing in the .attr() method of jQuery.
Working Demo: http://jsfiddle.net/xBdcq/
Upvotes: 0
Reputation: 841
jQuery has a built in data()
function see here for the proper method documentation.
As for your specific propblem I would suggest
var randomNum1 = Math.floor(Math.random() * (200 - 100 + 1)) + 100;
var attrb = randomNum1.toString();
var $this = $(this);
$this.data(attrb, 'someString');
$this.data(attrb2, 'somestring');
Upvotes: 0
Reputation: 2832
var randomNum1 = Math.floor(Math.random() * (200 - 100 + 1)) + 100;
var atts = {};
atts['data-' + randomNum1.toString()] = 'someString';
$(this).attr(atts);
Setting the names of object literals with variables works using square brackets.
Upvotes: 0
Reputation: 7076
try this
var randomNum1 = Math.floor(Math.random() * (200 - 100 + 1)) + 100;
var attrb = 'data-' + randomNum1.toString();
$(this).attr(attrb,"someString");
$(this).attr(attrb2,"someString");
Upvotes: 1
Reputation: 3939
When you are doing, {attrb: "something", attr2: "something"}
, the keys, attrb
and attr2
are not evaluated and are taken as it is. So you cannot use variables over there.
To solve your problem, what you can do is, call the attr()
method with two arguments - 1: the attribute, 2: the value:
var el = $(this);
el.attr(attrb, 'someString');
el.attr(attrb2, 'someString');
In this case the first argument of attr()
is evaluated and the variable is substituted with the value.
Upvotes: 2