Reputation: 5409
This is a tough question, and I'll do my best to describe it.
I have an text input where users can enter in tags.
After a user types a tag in the input (such as "starcraft") and presses the comma key, I want all characters before the comma (i.e. the word starcraft) to change color and background color. Thus after a user types a tag and presses comma, he can see the word in a tag form.
How would I do this using jquery?
Upvotes: 2
Views: 653
Reputation: 23142
To my knowledge, there's no easy way to modify the style of just part of the text in a textbox. However, you could do something like this:
HTML
<span id="tags"></span><input id="enterTag" type="text" />
JavaScript/jQuery
$('#enterTag').keydown(function(event) {
var tag = $(this).val();
// 188 is comma, 13 is enter
if (event.which === 188 || event.which === 13) {
if (tag) {
$('#tags').append('<span>' + tag + '</span>');
$(this).val('');
}
event.preventDefault();
}
// 8 is backspace
else if (event.which == 8) {
if (!tag) {
$('#tags span:last').remove();
event.preventDefault();
}
}
});
CSS
#tags span {
display: inline-block;
background: #6999c0;
color: #FFFFFF;
padding: 4px;
border: solid 1px #477eab;
margin-right: 4px;
}
Working example: http://jsfiddle.net/FishBasketGordo/xckjk/
Upvotes: 6
Reputation: 114377
Textboxes can't do this. You can take a few approaches:
1) set focus to a hidden input box and listen to key events. Then simulate a textbox and the behaviour you describe using DIVs, SPANs and CSS.
2) Show the highlighted terms (or tags) below the textbox (easier)
3) Use the technique kingjiv suggests
In either case this is not a simple task.
Upvotes: 0
Reputation: 69905
This is not possible just using input textbox. You will have to use a combination of div/span and input textbox. On keypress event you have to dynamically create the required tags and append in the div.
Upvotes: 0
Reputation: 78650
You will need to use a contentEditable
div
for this. You cannot style chunks of text within a regular input
. You will want to create a contentEditable
div
, and then run code on keypress (or keydown) which will wrap the text in a span which is then styled.
Upvotes: 0