checkbox check/uncheck using d3

跟風遠走 提交于 2019-12-13 03:48:25

问题


I am having difficulty checking and unchecking checkboxes using d3 selection. The following code doesn't seem to work. I want all check boxes to be checked when 'check' is pressed, and all checkboxes unchecked when 'uncheck' is pressed.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type='button' onclick='checkAll()'>Check</button>
<button type='button' onclick='uncheckAll()'>Uncheck</button>

<script src="http://d3js.org/d3.v2.min.js?2.10.0"></script>

<script>
function checkAll(){
    d3.selectAll('input').attr('checked','true');
}
function uncheckAll(){
    d3.selectAll('input').attr('checked','false');
}
</script>
</body>

回答1:


Use property() instead of attr():

function checkAll() {
    d3.selectAll('input').property('checked', true);
}
function uncheckAll() {
    d3.selectAll('input').property('checked', false);
}

From https://github.com/mbostock/d3/wiki/Selections#wiki-property:

Some HTML elements have special properties that are not addressable using standard attributes or styles. For example, form text fields have a value string property, and checkboxes have a checked boolean property. You can use the property operator to get or set these properties.




回答2:


Change your uncheckAll function to set the checked attributes to null instead of false:

function uncheckAll(){
    d3.selectAll('input').attr('checked',null);
}

The checked attribute is either present, optionally set to checked="checked", or absent (no checked attribute at all). Setting it to null will remove the attribute, in this case.




回答3:


What you need to do is update the checked value of the element as follows:

d3.selectAll("input").each(function(d){ 
  if(d3.select(this).attr("type") == "checkbox") 
    d3.select(this).node().checked = true;
});

This will ensure only all checkbox states are changed




回答4:


You can limit your selection to only checkboxes by filtering the selection on the type attribute,

d3.selectAll("input[type=checkbox]").property("checked", true);

This avoids setting the checked attribute on non-checkbox inputs that are present.



来源:https://stackoverflow.com/questions/25487249/how-to-remove-foreignobject-from-rect-on-toggle-in-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!