-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
  • 441
  • 1
  • 8
  • 24

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
  • 63,975
  • 10
  • 90
  • 112
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
  • 14,263
  • 2
  • 30
  • 58
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
  • 914,110
  • 126
  • 1,211
  • 1,335