1

How could I add attributes without values using d3.js?

For example, how could I construct such an option:

<option value="" disabled selected>Select something...</option>

In this example the disabled and selected attributes have no value. And value attribute has a value of "".

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
manymanymore
  • 2,251
  • 3
  • 26
  • 48
  • Possible duplicate of [How to remove an attribute in D3.js?](https://stackoverflow.com/questions/15322556/how-to-remove-an-attribute-in-d3-js) – Shashank Jun 12 '18 at 18:51
  • 1
    Please do not edit your question to address comments. Comments go on the comments section. I rolled it back. – Gerardo Furtado Jun 12 '18 at 22:48
  • @GerardoFurtado, but it is not a comment. You can see clearly that the question is marked as a duplicate. – manymanymore Jun 12 '18 at 23:37
  • @GerardoFurtado, lol. Is it that now anyone can tell me that the question is just a duplicate without any explanations provided? – manymanymore Jun 12 '18 at 23:38
  • 1
    Yes, anyone with sufficient RP can vote to close, for right or wrong reasons. If you disagree with the person that left the comment regarding his/her vote, write another **comment** complaining about it, or take it to the meta... but don't edit your question to answer comments. On the other hand, if you have **additional information** relevant to the problem which can show to the user that your question is not a duplicate, then you should edit your question accordingly. – Gerardo Furtado Jun 12 '18 at 23:43
  • @GerardoFurtado, you deleted the **additional information** I provided. – manymanymore Jun 13 '18 at 10:21
  • @YaroslavTrofimov No, I didn't. Anyway, feel free to edit it the way you want, I won't edit this question again. – Gerardo Furtado Jun 13 '18 at 10:50

1 Answers1

3

For exactly these purposes you can use selection.property():

Some HTML elements have special properties that are not addressable using attributes or styles, such as a form field’s text value and a checkbox’s checked boolean. Use this method to get or set these properties.

Your <option> can thus be constructed along the following lines:

d3.select("select")
  .append("option")
    .property("value", "")
    .property("selected", true)
    .property("disabled", true)
    .text("Select something...");
altocumulus
  • 21,179
  • 13
  • 61
  • 84
  • Does it mean that if I put `... .property("selected", false)`, then I will delete the attribute `selected` ? – manymanymore Jun 12 '18 at 22:07
  • Well, that's partly true. If you want to **delete** the property, you need to use `.property("selected", null)`. Technically, this is equivalent to setting it to `false` as the absence of the attribute represents a `false` value. See the spec for the definition of [boolean attributes](https://www.w3.org/TR/html50/infrastructure.html#boolean-attribute). – altocumulus Jun 12 '18 at 22:15