简体   繁体   中英

populating JavaScript key value pair

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"

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM