问题
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!
回答1:
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>bob@email.com;</li>
<li>jane@email.com;</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
回答2:
One way to do it would be to layer a text input on top of a div that is styled to look like a text input.
<div id="fake-input">
<span class="input-item">John Doe</span>
<span class="input-item">Jane Deere</span>
<input id="receiver-input" type="text" />
</div>
You can strip all styling off of receiver-input, and add borders, background colors, and such to fake-input so that it appears to be a text field. When a receiver is added, you can create a new input-item span and append it to the list.
回答3:
Input text fields are typically used to accept raw text input. Attempting to wrap input text inside of a text field opens you to user error and potential difficulties with parsing data if the person is able to manipulate the tags.
Personally I would suggest keeping your current method but enabling some form of AJAX support to make things more dynamic and less error-prone to the user.
(My $0.02)
回答4:
TextExtjs is probably what you want. It's a jquery plugin for allowing removable tags with autocompletion etc in a textarea.
And here is a related SO discussion - where I found this plugin - on mimicking the similar behavior found in some inputs on facebook.
来源:https://stackoverflow.com/questions/6499163/span-inside-text-input-field