Span inside text input field?

Snorreri picture Snorreri · Jun 27, 2011 · Viewed 35.2k times · Source

Is it somehow possible to place a span as the value of a text input field?

I am making a mailing system for a website and want a nice looking receivers input field, where added receivers are contained and added to the value of input text field. At the moment i use a separate "adding field" while showing added receivers in a span-container. I want to merge these to fields together. Just like any input field in regular e-mail software.

Help would be most appreciated! Thanks in advance!

Answer

jacob.toye picture jacob.toye · Jun 27, 2011

Short answer: no, you cannot include a <span /> within an <input />.

You have a few options. You could use javascript to emulate behaviour like the email To: field. E.g. listen to key presses and handle actions like backspace after a ;.

Another option would be to make a list appear (css styled) like a textbox. Have the last <li /> contain a textbox with cleared styles. Every time the user adds a new email then insert a new <li /> before the textbox.

E.G.

html:

<ul class="email-textbox">
    <li>[email protected];</li>
    <li>[email protected];</li>
    <li><input type="text" /></li>
</ul>

css:

.email-textbox {
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 2px 4px; 
}

.email-textbox li {
    display: inline-block;
    list-style: none;
    margin-left: 5px;   
}

.email-textbox input {
    background: none;
    border: none;
}

javascript (jQuery, can change to vanilla)

$(function () {
    $('.email-textbox').find('input').focus();
});

You will need to extend this javascript to include a keypress handler etc, but it gives the general idea.

Demo: http://jsfiddle.net/UeTDw/1/

Any option will require some javascript however.

If you can use jQuery, you could check out jQuery UI autocomplete