144

I am trying to get all elements with an id starting with some value. Below is my jQuery code. I am trying to use a JavaScript variable when searching for items. But it does not work. What am I missing below? So the id 'value' am searching is the value of the clicked element

$(document).ready(function() {
    $('input[name$="_chkmulti"]').click(function(){
        var value = $(this).val();
        $("td[id^= + value +]").each(function(){
            alert("yes");
        });


    });
});
informatik01
  • 15,636
  • 10
  • 72
  • 102
DG3
  • 4,860
  • 14
  • 48
  • 61

2 Answers2

272

try:

$("td[id^=" + value + "]")
Ryan M
  • 15,686
  • 29
  • 53
  • 64
None
  • 1
  • 30
  • 155
  • 213
  • A word of warning: this selector doesn't work if the 'value' is an HTML element, as I found out the hard way when my IDs for list items all started with 'li'. The solution was to start them with 'li_' – Tim Dawson Jun 28 '20 at 12:37
56

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

Šime Vidas
  • 173,790
  • 60
  • 275
  • 374
  • 1
    The quotes aren't actually mandatory: "value: An attribute value. Can be either an unquoted single word or a quoted string." From the linked docs in the answer. Similar to accepted answer. – Ralph Lavelle Feb 18 '14 at 00:44