112233
112233

Reputation: 2466

How to convert variable value into jQuery object?

For some reason I need to convert jquery variable value into object.

$("input[type=text]").on("keyup", function () {
    var target = this.id; //outputs 'subject'
    //how to convert here?
    var targetItem = $("#subject");//originally like this.
    //I tried something like below
    //var targetItem = $("#+target+");
    alert(targetItem);
});

All I'm trying to do is , changing the word in this: $("#subject") with whatever value of variable 'target'.

Upvotes: 0

Views: 573

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

Use this -

var targetItem = $(this); // Will always hold the current element object

And for the code you are using it should be -

var targetItem = $("#" + target);

target is a variable. "#+target+" will be treated as #+target+ not #subject (in your case)

Upvotes: 2

Sudharsan S
Sudharsan S

Reputation: 15393

Simply like

var target = this.id;
var targetItem = $("#"+target);

Upvotes: 1

Related Questions