Question

I am trying to create a script using JQuery that changes the attributes of another script. The issue is that the two attributes I am working with have a "-" in between them. This triggers an unexpected token error. My code is below.

$( document ).ready(function() {
    $( "#test" ).attr({
        data-ids: "5sH7qfUk5T",
        data-fields: "firstName,lastName,industry, location"
    });
});
Was it helpful?

Solution

Quote the keys with the hyphens in the object, as hyphens are not valid in object keys

$( "#test" ).attr({
    'data-ids'    : '5sH7qfUk5T',
    'data-fields' : 'firstName,lastName,industry, location'
});

The Property Identifier type is used to associate a property name with a Property Descriptor.

Values of the Property Identifier type are pairs of the form (name, descriptor), where name is a String and descriptor is a Property Descriptor value.

When you use the hyphen character outside string literals it's interpreted as a 'minus' sign, and so it's not valid in object keys that are not quoted.

OTHER TIPS

This isn't a jquery/attribute problem, it's an object literal problem. To use a key with special characters such as spaces and dashes, wrap the key in quotes.

$( document ).ready(function() {
    $( "#test" ).attr({
        "data-ids": "5sH7qfUk5T",
        "data-fields": "firstName,lastName,industry, location"
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top