Silverburch Silverburch -4 years ago 86
jQuery Question

How to search on part of element name + variable

I can search all id's using the start of a variable name:

"month2015Jan" (one of the id's)

"month2015Feb" (one of the id's)

$('[id^="month"]').prop('disabled', false)

But I want to also use a variable for the year:

KEYyear = "2015"

I've tried:

$('[id^="month" + KEYyear]').prop('disabled', false)
$('[id^="month"]'+ KEYyear).prop('disabled', false)
$('[id^="month"] + KEYyear').prop('disabled', false)

Nothing works. Any ideas anyone?

Answer Source

This is the correct approach: $('[id^="month' + KEYyear + '"]'), or, to make it more explicit:

var idPattern = 'month' + KEYyear; // What you're looking for
var jqPattern = '[id^="' + idPattern + '"]'; // What the selector looks like

Your first pattern was almost correct, but it was looking for "month"2015 instead of "month2015"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download