1

Using (custom) jQuery data-attributes to retrieve the elements where these icons are displayed, I am successfully changing icons with this working code:

<i class="glyphicon glyphicon-check" data-year="2014" data-flag_check="1"></i>
...
<script>
   ...
   $('i[data-year="2014"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

But, if I attempt to replace the constant 2014 with a variable, my code stops working.

var yearIn = "2014";
$('i[data-year=yearIn]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

Is it possible to perform this operation with a variable?

If so, what is wrong in my syntax?

2 Answers 2

5

You're just missing string concatenation:

var yearIn = "2014";
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^^^^^^^^^^^^^^

Or in ES2015+ you could use a template literal with a substitution token:

  var yearIn = "2014";
  $(`i[data-year=${yearIn}]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
//  ^------------^^^^^^^^^-^

FWIW, I always use quotes around the value in the selector when it comes from a variable, just in case the variable ends up with something in it with spaces, etc.:

var yearIn = "2014";
$('i[data-year="' + yearIn + '"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^--------------^

or

var yearIn = "2014";
$(`i[data-year="${yearIn}"]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^---------^
Sign up to request clarification or add additional context in comments.

2 Comments

Or use template literals :)
@Vucko: Quite. I really should start mixing those in, two years later...
2

You are using the string literal 'yearIn' rather than the variable yearIn. Do something like this to concatenate the strings:

$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.