Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use hyphen in object property name?

Tags:

javascript

$('.class').data({data-toggle: "whatever-value", data-target: "#id"});

I keep getting syntax errors for the -

I originally tried .attr then switched to .data because I thought that would fix it.

Can someone help with this easy problem?

Thanks

like image 625
John_911 Avatar asked Apr 05 '14 03:04

John_911


2 Answers

If you want to set/update a data-* attribute, you need quotes if you set the attribute:

$('.class').attr({"data-toggle": "whatever-value", "data-target": "#id"});

Otherwise it parses it like

data-toggle

meaning

data - toggle

subtracting two variables.

You can also use .data() with

$('.class').data({"toggle": "whatever-value", "target": "#id"});

but that does not assign data-* attributes it just stores the data in jQuery's storage system.

like image 69
loganfsmyth Avatar answered Sep 23 '22 07:09

loganfsmyth


Just to add to what's alredy been pointed out, in Javascript, objects have properties defined by arbitrary strings.

obj.prop is really just sugar for obj["prop"], with the latter being more expressive because all characters are allowed in the latter. Likewise, {prop: "val"} is really sugar for {"prop": "val"}. This is just one of many cases where you'll have to resort to the desugared syntax.

like image 32
acjay Avatar answered Sep 26 '22 07:09

acjay