-1

Its a simple question, could not find an answer from google.

Code

$.click(function(){
var curID = $(this).parent()[0].id;
$("#"+curID input).attr("checked",true);
});

Onclick function is giving me the parent id, Now, using the parent id i want to find the input element and add checked attribute.

I am not sure of the syntax of querying by dynamic ID.

I want to know how can i query by dynamic variable.

Thanks in advance.

KrankyCode
  • 431
  • 1
  • 8
  • 23

3 Answers3

2
$("#"+curID).find('input').attr("checked", true);

Or

$(this).parent().find('input').attr("checked", true);

Or

$('input', $(this).parent()).find('input').attr("checked", true); // using the scope argument
MrCode
  • 61,589
  • 10
  • 82
  • 110
2

The selectors are strings... So should be handled as strings by concatenating the variables: and texts

$.click(function(){
var curID = $(this).parent()[0].id;
$("#"+curID+" input").attr("checked",true);
});
Salketer
  • 12,278
  • 2
  • 27
  • 57
1

Your search is probably too specific. Break tasks down into their components instead of looking for a complete solution to a very specific problem. You are just dealing with basic string concatenation here.

You want:

var selector = "#foo input";

You have foo in a variable.

var selector = "#" + foo_variable + " input";
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264