-1

How to use JavaScript variables in jQuery selectors?

(function($){

var words = $('#readpcd').text().match(/(\w+)/g);
if (words.length) {
    var lastword = words[words.length - 1];
}
console.log(lastword);
 
$('select option[value=" + this.lastword +"]').attr("selected","selected");


}(jQuery || window.jQuery));

i tried

$('select option[value="${lastword}"]').attr("selected","selected");
Matt Smith
  • 15
  • 1

4 Answers4

0

Two approaches:

  1. String Concatenation

    $('select option[value="'+lastword+'"]')
    
  2. Variable injection

    $(`select option[value="${lastword}"]`)
    

(You need to use ` instead of ')

Danbardo
  • 761
  • 7
  • 12
0

Use template literals (using backticks ``)

 $(`select option[value="${lastword}"]`).attr("selected","selected");
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
-1

You can use

$('select option[value=' + lastword + ']').attr("selected","selected");
Cheng Adrian
  • 177
  • 10
-2

change this line

$('select option[value=" + this.lastword +"]').attr("selected","selected");

to this

$('select option[value="' + lastword + '"]').attr("selected","selected");

lastword is a local variable. you cannot use it as this.lastword.

and if you want to use it inline the use backticks

$(`select option[value="${lastword}"]`).attr("selected","selected");
farz bhullar
  • 451
  • 3
  • 10