Khaynes
Khaynes

Reputation: 1986

How to concatenate multiple variable and strings in functions in jquery

This seems like it should be simple, so not sure what i'm missing

// this works
$("#Q270_1, #Q271_1").change(function () {
    alert("Check 1")
});

// this works
var m1c1 = "#Q270";
$(m1c1+"_1").change(function () {
    alert("Check 2")
});

// This doesn't work
var m1c2 = "#Q271";
$(m1c1+"_1",m1c2+"_1").change(function () {
    alert("Check 3")
});

Here is a jsfiddle where it shows the above: https://jsfiddle.net/9Led5cv9/

Any assistance much appreciated. Thanks!

Upvotes: 1

Views: 3408

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You are creating 2 parameters which jQuery interprets as:

$(selector, context)

This would be the same as $(context).find(selector)

You need to concatenate the full string instead keeping the comma inside quotes

$(m1c1+ "_1, " + m1c2+"_1")

Upvotes: 2

user6765872
user6765872

Reputation:

stringify that comma:

$(m1c1+"_1, "+m1c2+"_1").change(function () {
    alert("Check 3")
});

Now the 1 argument references both elements.

Note: I'd give the elements a class, instead of generating long complicated lists of jQuery selectors.

Upvotes: 0

Related Questions