jquery selector for radio button group in which the name attributes value has array notation
Solution 1
You need to escape the square brackets in the selector:
$("input:radio[name=show\\[\\]]").click(function(){
alert(this.value)
})
As mentioned By James Allardice, you can also put quotes around the attribute itself to stop the ambiguity:
$("input:radio[name='show[]']").click(function(){
alert(this.value)
})
Better yet, use a class.
Solution 2
You should escape the brackets with \\
:
$('input:radio[name=show\\[\\]]').on('click', function(){
alert(this.value)
});
To increase readability, you can also wrap the name selector in quotes:
$('input:radio[name="show[]"]').on('click', function(){
alert(this.value)
});
Solution 3
You have to escape the [
and ]
within selector.
$("input:radio[name=show\\[\\]]").click(function(){
alert(this.value)
})
Related videos on Youtube
Jayapal Chandran
A Enthusiastic Programmer http://vikku.info http://vikku.info/programming/
Updated on September 16, 2022Comments
-
Jayapal Chandran over 1 year
I want to use jquery selector for radio button group with array notation
I have radio buttons like this
<input name="show[]" type="radio" value="1" /> Show<br> <input name="show[]" type="radio" value="0" /> Hide<br>
I want to use jquery selector for the above and tried the following
$("input:radio[name=show[]]").click(function(){ alert(this.value) })
which is not working
I know we can give like show instead of show[] for the name attribute of radio button
yet IE had problems so by giving with array notation worked in all browsers.
Now i want to give like what i had done and is that possible or is it a different syntax to include array notation?
-
James Allardice over 11 years+1. Alternatively, you can just quote the attribute value part of the selector.
-
John Dvorak over 11 yearsHow is
on('click',
preferable toclick(
? Can you source? -
doublesharp over 11 yearsSorry, spaced... I was thinking of
live()
. -
John Dvorak over 11 yearsActually,
on('click',
does have its benefits ;-) -
doublesharp over 11 yearsI tend to prefer it, but... can you source the benefits, I'm curious as to what they are :)
-
John Dvorak over 11 yearsIt cannot be confused with
trigger('click')
(what doesclick(undefined)
do, trigger or listen?). -
John Dvorak over 11 yearsIt's more universal - you don't need to worry if every obscure event has its jQuery method (
click
is obvious,touch
isn't). I'd bettouch(function(){
doesn't work ;-) -
doublesharp over 11 yearsGood points, now that I think about it the shorthand being less readable between setting up a listener and triggering an event is why I go with
on
/trigger
-
John Dvorak over 11 yearsAlso, you unbind
on
withoff
andlive
withdie
, but how do you unbindclick
(neglecting that they are actually aliases)?