Adding class to Drupal field via jQuery outputs wrong loop

70 views Asked by At

I'm adding a class to a field depending on the contents of that field so I can style each field differently depending on the content. Imagine a burger rating from one to ten...I want to replace the rating with an image for one, another image for two ...and so on.

To do this I need each field class to reflect the field content. Here is the code I'm using:

Drupal.behaviors.burgerRating = {
attach: function (context, settings) {
    var burgerRating = $('.field-name-field-rating2').text();
    $('.field-name-field-rating2').addClass(burgerRating);
    }
}

This outputs the contents of the field as a class which I can style. However in a blog View with for example three posts on the page, this code adds all three classes to all three fields when I want each specific field content for each field instance.

What I'm getting is this:

<div class="field-name-field-rating2 rating-1 rating-5 rating-8">
<div class="field-name-field-rating2 rating-1 rating-5 rating-8">
<div class="field-name-field-rating2 rating-1 rating-5 rating-8">

Instead of:

<div class="field-name-field-rating2 rating-1">
<div class="field-name-field-rating2 rating-5">
<div class="field-name-field-rating2 rating-8">

I'm thinking I need to get this working with .this() or .each() but I can't get it to work.

Any help? thanks.

1

There are 1 answers

1
Etienne On BEST ANSWER

Why to do that in Javascript ? You can :

A formatter is the way a field is displayed. It depends of the type of the field (text, number, taxonomy_reference, ...). If your rating field is a text field, you have to create your formatter for a text field. After creating it, all text fields can use this formatter.

You have to associate this formatter to your field on the display tab of your content type.

enter image description here

It's an amazing system, you can add settings form for your formatter as well (hook_field_formatter_settings_form)