Ingolf Krauss Ingolf Krauss - 2 months ago 9
jQuery Question

How to use .attr("name") when the name has an array structure

I want to get the length of a radio button using the jquery syntax

.length


The radio button names are like the following obj[1], obj[2] and so on. If I address it directly
$("input:radio[name='obj[1]']:checked").length
I get the correct length.

If I get the name using
.attr("name")
and try to get the
$("input:radio[name="+name+"]:checked").length
I do not get the correct length.

Please help with correct syntax how to address the radio buttons by name.

Answer Source

Problem is, in 2nd method, you are missing quotes. Use this:

$("input:radio[name='"+name+"']:checked").length

If name contains special characters including [] it has to be quoted, like you did in first case. You are just appending content of name variable into string, which is sent into jQuery like in the first case.