JonnySerra
JonnySerra

Reputation: 1074

Adding Hyphen in data-value string dynamically jQuery

So i have a page with a simple UL that's supposed to be populated at runtime via AJAX calls and JSON responses.

$(".select-brands").append("<li data-value=" + manufacturerName + ">" + manufacturer + "</li>");

After this i'm using that data-value attribute in order to scroll to the element of the same name as the one the user selected in a different selection box. So when they select the Harley Davidson picture the jQuery will look in the for an element with

data-value="HARLEY-DAVIDSON"

However the result is not what i expected, instead of that data-value i'm instead getting elements like this

<li data-value="HARLEY" davidson="">HARLEY DAVIDSON</li>

How can i make it so that i can select the elements based on this name? can it be done via the text inside of the li tags?

// Get corresponding brand on list by custom data-value attribute //
var listBrand = $('li[data-value="'+ selectedBrand.toUpperCase() +'"]');
var parent    = $('#brands-select');
var index     = listBrand.index();

parent.animate({
        scrollTop: $('#brands-select li:nth-child('+ index +')').position().top - $('#brands-select li:first').position().top
}, 'slow');

That's the code i use in order to scroll to the element selected.

Upvotes: 4

Views: 824

Answers (1)

Scimonster
Scimonster

Reputation: 33399

$(".select-brands").append("<li data-value=" + manufacturerName + ">" + manufacturer + "</li>");

You don't have quotes around the attribute name. You should do it like this:

$(".select-brands").append("<li data-value='" + manufacturerName + "'>" + manufacturer + "</li>");

With quotes.

Without them, it gets parsed as two separate attributes, like this: <li data-value=HARLEY-DAVIDSON>, because the hyphen gets ignored.

Upvotes: 5

Related Questions