Jayapal Chandran
Jayapal Chandran

Reputation: 11140

jquery selector for radio button group in which the name attributes value has array notation

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?

Upvotes: 4

Views: 17327

Answers (3)

doublesharp
doublesharp

Reputation: 27599

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)
})​;​

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 11

Adil
Adil

Reputation: 148110

You have to escape the [ and ] within selector.

Live Demo

$("input:radio[name=show\\[\\]]").click(function(){
    alert(this.value)
})​

Upvotes: 1

Related Questions