72

I have a group of buttons on my web page which all have an id that end with the text "EditMode".

I'm using jQuery to assign an event to like so

$('[id $=EditMode]').click(editHandler);

However now I want to prefix the id with a name (which I will know in advance) so the id would be "aName+someotherstuff+EditMode". How do I alter the above expression so I match on aName AS WELL as editMode?

chaos
  • 122,029
  • 33
  • 303
  • 309
AJM
  • 32,054
  • 48
  • 155
  • 243

2 Answers2

160
$('[id ^=aName][id $=EditMode]')
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 2
    I would always just add quotes around your selector name like so `$('[id ^="aName"][id $="EditMode"]')` See fiddle for working example https://jsfiddle.net/u6mzs720/ – Phil Cook May 30 '18 at 12:45
  • This works great for filling ASP BeginCollection elements via javascript. – Vasily Hall Feb 20 '20 at 16:43
13

Alternatively, you can use the "add()" function for readability, but I would recommend Chaos's method:

$("[id ^=aName]").add("[id $=EditMode]")
Richard Clayton
  • 7,452
  • 3
  • 23
  • 19
  • 1
    Actually this answer does not achieve the same as chaos answer. This selects all elements with id's beginning with 'aName' and all id's ending with 'EditMode'. Chaos' answer would select all elements that both begin 'aName' and end 'EditMode' within each id. I used this 'for readability', before realising my mistake, as I was selecting input fields and the square braces are a little confusing. If it helps any one else that is written like: `$("input[name^='start_term']input[name$='[end_term]']")` – dading84 Dec 18 '16 at 22:14