开发者

Bind checkbox to boolean variable

I have quite a lot of checkboxes on my page and each checkbox corresponds with a certain variable in my JavaScript code. Currently, I have this kind of code for each checkbox:

$("#checkbox_var1").click(function() {
    Settings.var1 = $(开发者_JAVA百科this).checked();
});

I was wondering whether it would be possible to store a reference to a variable in an element (using data() perhaps) so that that's sufficient to bind a checkbox to a boolean variable. My current code becomes rather long since I have a fair amount of checkboxes.

So is it possible to bind a checkbox to a boolean variable directly? Or is there a general way of binding an element's value to a variable?


You can use the same event handler for multiple check boxes, using the element's id to connect the two on the settings object, like so:

function checkListener (evt) {
    var id = this.id.substr(9);
    Settings[id] = $("#" + this.id + ":checked").length > 0;
}

Assuming you follow the same convention to name all pertinent check boxes in your application, you should adjust the substring function accordingly. Then, to apply to multiple check boxes simultaneously, you could do something along these lines:

$(":checkbox[id*='checkbox']").click(checkListener);

Which translates to: "For all input elements of type checkbox, that have an id containing 'checkbox'". This way, you can handle multiple checkboxes with a few lines of code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜