Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple dynamic selectors in jQuery using variables

Using a single dynamic selector I have no problems:

var answer_id = <?php echo $answer_id; ?>;

$('#a_flag_' + answer_id).click(function(e) {
        e.preventDefault();

         //Ajax etc...

But if I add several dynamic selectors they do not work (ie, no errors on Firebug console, but also no action when clicked):

var answer_id = <?php echo $answer_id; ?>;

$('#a_flag_' + answer_id,'#a_comments_link_' + answer_id,'#a_best_answer_' + answer_id).click(function(e) {
        e.preventDefault();

         //Ajax etc...

Any ideas what I am doing wrong?

like image 608
pepe Avatar asked May 25 '26 17:05

pepe


1 Answers

You need the commas inside the quoted constant strings.

$('#a_flag_' + answer_id + ', #a_comments_link_' + answer_id + ',  #a_best_answer_' + answer_id).click(// ///

What you want to end up with is a string that looks like

"selector, selector, selector, ..."

so you need to concatenate a bunch of strings with commas.

Alternatively, you could build up your separate selectors in an array of strings and then ".join()" them with a comma separator (the parameter to ".join()").

like image 137
Pointy Avatar answered May 27 '26 08:05

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!