Alex
Alex

Reputation: 7688

Why does this jQuery selector return only 1 element?

So, I have this next variable that contains my checked checkboxes:

var checked = $('input[name="article[]"]:checked');

But how can I know if there is 1 checked, 2 or even none? Because console.log(checked.length) always returns 1.

Upvotes: 2

Views: 277

Answers (3)

Alex
Alex

Reputation: 7688

I know it's a stupid mistake but for everybody to know, the problem was that I was doing this:

if(checked.length = 1) {

instead of this

if(checked.length == 1) {

btw, I don't know why the "hate" on the other answers (for those who down voted), the answers given... work (I've tested 2 of them)

Upvotes: 3

joevallender
joevallender

Reputation: 4293

Who downclicked codeparadoxes answer? Right selector, just needs length

<input type="checkbox" name="article" value="1" />
<input type="checkbox" name="article" value="2" />
<input type="checkbox" name="article" value="3" />
<button>go</button>

​ js

$(document).ready(function(){
    $('button').click(function(){
        alert($('input[name^="article"]:checked').length)
    })
});​

Working here http://jsfiddle.net/joevallender/GLjTg/

Upvotes: -1

Silver Light
Silver Light

Reputation: 45952

Try

$('input[name=article\\[\\]]:checked').length

See jsfiddle: http://jsfiddle.net/dyrD5/

Upvotes: 0

Related Questions