score:0

use .property('value') instead of .attr('value').

score:0

when you do

.attr("id", "textinput")
.attr("size", "40")
.attr("value","default text");

you are giving the #textinput element a value=default text i.e:

<div id="textinput" value="default text"></div>

so you are not making its innerhtml default text but you are giving it an attribute like a class. and in the console you are asking for that value with your d3 selection.

score:1

you would get the same "default text" from dom if you called:

document.getelementbyid("textinput").getattribute("value")

you can get the input value from a d3 selction accessing node() first:

d3.select("#textinput").node().value 

score:3

instead of using .attr(), you should use .property() instead.

according to: https://github.com/d3/d3-3.x-api-reference/blob/master/selections.md#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, or any other addressable field on the underlying element, such as classname.

the reason why you can set the value via the .attr() method, but not get it, is because .attr() interacts with the underlying html. user interaction doesn't affect the html, so those changes aren't reflected when you get via .attr().

edit: updated the link to the d3v3 api. the same also holds true for d3v4, though the description is slightly different: https://github.com/d3/d3-selection/blob/master/readme.md#selection_property


Related Query