2

How can I style part of a string that is the value of a text-input while it is still in the input-field?

I know one can do this with an element with a contentedible attribute in an element, but Google does it in an input of type text with their instant suggestions. The first completion / suggestion appearing in the input.

IMUXIxD
  • 1,223
  • 5
  • 23
  • 44
  • can you attach screenshot? – monkeyinsight Apr 14 '13 at 06:08
  • Google does not use an input for suggestions :) but a `table`. That way they can manipulate styles inside `span` elements. – Roko C. Buljan Apr 14 '13 at 06:09
  • 1
    @roXon actually, google uses input for search queue and another input under previous one for suggestion. – Klaster_1 Нет войне Apr 14 '13 at 06:11
  • @roXon Well, you can manipulate the styles inside a span if its parent is another thing besides a table. It doesn't have to be a table, I don't think. – IMUXIxD Apr 14 '13 at 06:12
  • http://stackoverflow.com/questions/3121683/is-there-a-way-to-style-part-of-an-input-fields-value – Roko C. Buljan Apr 14 '13 at 06:14
  • @Klaster_1 Ah, I see. Sounds hacky and involves unnecessary markup. I was just wondering how they did it. Unless, can an input have an open and closed version and have a child then or is it infertile? Meaning, does an input have to look like `` or can it be `autocomplete` – IMUXIxD Apr 14 '13 at 06:15

2 Answers2

6

While Google uses something like this

Unfortunately you cannot " open + close " an input element like:

<input> <span>Bold</span> normal </input>

My suggestion is to go this way using contenteditable: Live Demo.

<div id="input" contenteditable="true"><span>This is </span> quite cool!</div>

CSS sample:

#input{
  font-family:Arial, Helvetica, sans-serif;
  border:1px solid #ccc;
  background:#eee;
  height:20px;
  width:200px;
  padding:7px;
  color:#888;
}
#input span{
  color:#444;
  font-weight:bold;
}

Then in JS to retrieve the element "value" you can use:

alert( this.textContent );

Example

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

In terms of UX, I think the best user experience would to not complete what the user is typing, but to show suggestions / completed options underneath the input.

IMUXIxD
  • 1,223
  • 5
  • 23
  • 44