0

I'm trying to retrieve the values in a series of checkboxes:

$(document).ready(function() {
    var folders = document.getElementsByName('note-behaviour-folder-add[]'); 
    for(var x = 0; x < folders.length; x++){
        if ((folders[x].type === "checkbox") && (folders[x].checked)) {
            alert("Yes!");
        }
    }
});

While there is data in the named elements, the above code appears not to be retrieving any of it. I also tried the jQuery alternative:

var folders = $("[name='note-behaviour-folder-add[]']");

But that went crazy and grabbed everything in the application.

As for the HTML itself:

<div class="note-behaviour-folder-box" id="note-behaviour-folder-box-2">
    <input type="checkbox" id="note-behaviour-folder-item-2" name="note-behaviour-folder-add[2]" value="2" checked="checked">Plot
    <dl>
        <dt><label for="note-behaviour-folder-item-select-2">Behaviours</label></dt>
        <dd><select name="note-behaviour-folder-item-select-2" class="chzn-select">
            <option value="1">List</option>
            <option value="2">Paragraph</option>
            <option value="3" selected="selected">Chapter</option>
        </select></dd>
    </dl>
</div>

Any ideas?

Wayne Smallman
  • 1,690
  • 11
  • 34
  • 56
  • Because `[]` are reserved characters in a jQuery selector, you'd have to escape them for the jQuery code to work; `$("[name='note-behaviour-folder-add\\[\\]']");` – Matt May 26 '13 at 19:54
  • 2
    Your code [works for me](http://jsfiddle.net/gZUUL/)? – Matt May 26 '13 at 19:55
  • 1
    @Matt He is using quotes for the attribute's value. – Ram May 26 '13 at 19:56
  • @undefined: Does that exempt it from needing to be escaped? I can't find an documentation that says that has to be the case (although, granted, it works in 2.0.1). – Matt May 26 '13 at 19:57
  • 1
    The code works for me here as well. Are you using `name="note-behaviour-folder-add"` or `name="note-behaviour-folder-add[]"`? Just so you know, no escaping and works: http://jsfiddle.net/4qCaU/ – acdcjunior May 26 '13 at 19:57
  • @Matt Yes, when quotation marks is used, there is no need to escape the values, please check this http://stackoverflow.com/questions/11849104/jquery-syntax-error-unrecognized-expression-name-basics-gender – Ram May 26 '13 at 20:03

1 Answers1

3

Since you are using:

<input ... name="note-behaviour-folder-add[2]" value="2" checked="checked">Plot
                                           ^-----

Then:

var folders = $("[name='note-behaviour-folder-add[]']");

Won't work. Use:

var folders = $("[name^='note-behaviour-folder-add']");
                      ^----                       ^---- notice the differences

That's called the Attribute Starts With Selector [name^="value"].

This will get you <input name="note-behaviour-folder-add[1]" ...>, <input name="note-behaviour-folder-add[3]" ...> and basically everything which name starts with note-behaviour-folder-add.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304