1

I’m new with LESS and I cannot figure out how to apply variable to input field with specific data- attribute. This is my problem:

I have multiple input fields

<input type=“text” data-value=“white” />
<input type=“text” data-value=“yellow” />
<input type=“text” data-value=“red” />

and each input field has a backround image according to data-value attribute, like this:

input[data-value=“white”]{
    background-image: url(“../images/white.svg”);
}
input[data-value=“yellow”]{
    background-image: url(“../images/yellow.svg”);
}
input[data-value=“red”]{
    background-image: url(“../images/red.svg”);
}

How can I shortend this with LESS?

Thank you in advance!

seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
tortoise
  • 23
  • 4
  • Possible duplicate of [Loop through array of variable names in Less](https://stackoverflow.com/questions/21440789/loop-through-array-of-variable-names-in-less) – Mario Nikolaus Nov 22 '17 at 23:48
  • Thus the proper duplicates would be https://stackoverflow.com/questions/22492261, https://stackoverflow.com/questions/24626408, https://stackoverflow.com/questions/20954762, https://stackoverflow.com/questions/20369614 and so on. – seven-phases-max Nov 23 '17 at 00:37
  • Weirdly enough "Loop through array of variable names" seems to be quite popular topic when it comes to these kind of things despite the fact it's a *wrong* solution. Instead of looping through *names of variables* one usually needs to loop through just *values*. – seven-phases-max 23 mins ago – seven-phases-max Nov 23 '17 at 00:42

1 Answers1

-1

See here and there for some hints on solving this. One issue is that you cannot just use attr() within url(), so you need another approach which includes loops. You need to define all possible values for data-value before.

@colors: "green", "red", "blue";

.-(@i: length(@colors)) when (@i > 0) {
    @name: extract(@colors, @i);
    input[data-value="@{name}"] {
        background-image:url("../images/@{name}.svg");
    }
    .-((@i - 1));
} .-;
friedemann_bach
  • 1,418
  • 14
  • 29