populating JavaScript key value pair

0 votes
asked Jun 5, 2014 by marcel

I have a form with file-names and check-boxes that comes from the server already pre-populated. My form is supposed to update the check boxes.

I have code in JavaScript that selects the rows and attempts to build a key value object with the updated values from the check-boxes in each row.

When the selector is set to only return the ones that are checked, the dictionary gets built perfectly, but I also want to add to the dictionary the entries that might have gotten ticked off.

When I make the selector select all rows (including where the checked attribute is undefined) then the dictionary doesn't get populated at all.

Here is my input element:

<input type="checkbox" name="Map" data-id="@file.FileId" checked="checked" class="auto-accept-checkbox" />

Here is the javascript snippet:

var map = {};
$("#shareable-file-settings-form table tr").each(function () { map[$(this).attr('data-id')] = $(this).attr('checked') === 'checked';
});

I have tried on the console item by item and my right hand operand expression works there! I don't know why that look would misbehave like that (not putting anything in the dictionary) when the selector is modified

from:

"#shareable-file-settings-form table tr :checked"

to:

"#shareable-file-settings-form table tr"

1 Answer

+3 votes
answered Nov 29 by ryan-erdmann

Like Joe said, you're selecting the tr element, not the input[type=checkbox] inside. First, change your selector to

"#shareable-file-settings-form table tr input[type=checkbox]"

Further, the "checked" property on checkboxes is an HTML property, not an attribute. Also, you can use jQuery's .data() method to access the id data attribute.

You can change it to

map[$(this).data('id')] = $(this).prop('checked');
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...