0

im using Span text fields, and i want it to be cleared when clicking on them, how do i do?

My code looks like this:

<div class="text3">

<span contenteditable="true">något</span>
</div>
braX
  • 11,506
  • 5
  • 20
  • 33
m.wallgren
  • 79
  • 1
  • 4
  • Welcome to stackoverflow, please read our [ask] page to help you improve your question – blurfus Oct 20 '15 at 19:09
  • 1
    Possible duplicate of [How to clear content of div container using JS/Jquery?](http://stackoverflow.com/questions/11412861/how-to-clear-content-of-div-container-using-js-jquery) – blurfus Oct 20 '15 at 19:10

2 Answers2

0

How would you edit the text if you clear it everytime you click ? Anyway here is a trick :

<div class="text3">
<span contenteditable="true" onclick="this.innerText=''">något</span>
</div>
Arsonik
  • 2,276
  • 1
  • 16
  • 24
  • Thanks! hmm.. hehe i have not thought about that... i just want to clear the field one time, like get rid of the first letters.. – m.wallgren Oct 20 '15 at 19:15
0

Use the node’s textContent property to set the “inner” text, which is the actual text node.

To clear the text when the span gets the focus for editing its content, use the onfocus attribute to set an empty string:

span{
    display:inline-block;
    min-width:30px;
    min-height:18px;
    outline:1px dotted grey;
}
<div class="text3">
    <span contenteditable="true" onfocus="this.textContent='';">något</span>
</div>

Since the content will be set to empty string, the <span> inline element will be nearly invisible without entering any text. You probably should add some visual to the interface in order to guide the user. The above CSS will keep it at arbitrary minimum dimensions, adding an outline to keep the “input” from disappearing.

Also, you could select the text content instead of removing it. Unfortunately, it seems the Range interface doesn’t work for contenteditable non-input elements, so that’d be qualified for another question.

Community
  • 1
  • 1
dakab
  • 5,379
  • 9
  • 43
  • 67
  • Thanks, but as Arsonik said, i have to be able to go back to the text field later and not delete all text inside – m.wallgren Oct 20 '15 at 19:24
  • How about trying to select? – m.wallgren Oct 20 '15 at 19:42
  • @m.wallgren: Please see edited answer: some styling can prevent the element von vanishing and will also help users, and selecting in contenteditable elements seems harder than in input elements. – dakab Oct 21 '15 at 04:18