-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");
1
  • 2
    You need to use backticks (`) not single quotes for template literals Commented Dec 28, 2021 at 11:51

4 Answers 4

0

Two approaches:

  1. String Concatenation

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

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

(You need to use ` instead of ')

Sign up to request clarification or add additional context in comments.

Comments

0

Use template literals (using backticks ``)

 $(`select option[value="${lastword}"]`).attr("selected","selected");

Comments

-1

You can use

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

Comments

-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");

4 Comments

thanks but this still does not change the select options if i use $('select option[value="text"]').attr("selected","selected"); it work
i updated my answer if you want to using it with backticks @MattSmith
I believe the second line of code is still incorrect, you are missing quotations to break the String.
thanks @Danbardo, i corrected it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.