150

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
  • 16,038
  • 10
  • 74
  • 104
DG3
  • 5,070
  • 17
  • 49
  • 61

2 Answers2

281

try:

$("td[id^=" + value + "]")
Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • 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
61

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
  • 182,163
  • 62
  • 281
  • 385
  • 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