简体   繁体   中英

How to update the contents of a text input with d3?

I am trying to create a text input control in D3 that needs to push data into the text input. I am able to set the initial value with

d3.selectAll('#textfield')
    .data([number])
    .attr('value', function(d) { return d })

but this is of no use once someone edits the text and then tries the external update. Is there some way of setting the contents to some arbitrary value?

I've got the code in JsFiddle .

Update:

I've found a workaround :

var node = d3.selectAll('#textfield')
    .data([number])
    .node()
node.value = number

But I'm not sure if this is the right approach. Any clues?

You are setting the value of the value attribute and value just happens to be a special attribute which does not play well with setAttribute function (which d3 internally uses for setting an attribute).

This approach is not much better, but more pragmatic use of D3 :

d3.selectAll('#textfield')
    .data([number])
    .each(function (d) {
        this.value = d;
    });

Demo: http://jsfiddle.net/LGtDD/3/


Besides, one can (and perhaps should ) use plain JS to do this unless you have a compelling argument against it. Using D3 for this might just be overkill:

document.getElementById('textfield').value = number;

您可以使用设置文本输入值

d3.select('#textfield').property('value', "<your desired text>");

This also seems to works:

function changeValue() {
    var number = Math.round(Math.random()*100);
    d3.select('#textfield')[0][0].value = number;
}

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