0

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'.

5
  • var targetItem = $("#"+target); Commented Jul 31, 2015 at 10:50
  • stackoverflow.com/questions/12134605/… Commented Jul 31, 2015 at 10:52
  • just one doubt. Why do you need this code? because object which you will get is same one you get by simply using this Commented Jul 31, 2015 at 10:53
  • 1
    if this refers to the node you can just do $(this) Commented Jul 31, 2015 at 10:53
  • Provide minimalistic sample to replicate your issue because your posted code doesn't make sense or maybe your example sample isn't relevant to your use case issue Commented Jul 31, 2015 at 10:55

2 Answers 2

2

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)

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

3 Comments

You can also please correct the way he is trying to concatenate strings
@sabithpocker :) Thanks.
@sabithpocker You Are Welcome. ;)
1

Simply like

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

4 Comments

But because IDs must be unique on document context, it doesn't make sense
@soosmca No need id value ,You can use this directly $(this)
@Balachandran - I am just notices what mistake the OP had done
That is good but i gave suggestion you can wrap this with $ directly

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.