Reputation: 6531
I have a textbox called names
that allows a user to enter individual words, each word separated by a space.
I then have a div
called preview
which contains nothing initially, but with each character that appears in the names
textbox, I'd like to show this in the preview div, with each individual word (based on 'space' seperation) to be output as individual span tags (so I can then apply a style to each individual 'name' within the preview.
I should also mention that in some scenarios, values will be arriving in the names
textbox via a jQuery UI Autocomplete list (which I've already got working), and also pre-filled (when I'm editing a record for example and prefill the textbox with previously chosen names).
My jQuery isn't great and I've had a look around for a solution, but not had much success.
How would I go about achieving this?
Upvotes: 0
Views: 479
Reputation: 39669
You can do it like this.. create a javascript function which is called every time when user press some key on textbox field.
<script language="javascript">
$("#names").keypress(function() {
populateWord('keypress');
});
//blur function is to fix the bug, because last word may not contain space in the end, and we only want to perform update when textbox loose focus and word may or may not end with space
$("#names").blur(function() {
populateWord('blur');
});
function populateWord(type){
val = $("#names").val();
var gotLetter = false; //to avoid word which contains only space in loop back lookup
//we first check if we got a space then it means we got a word
if((val[val.length-1] == ' ' $$ type == 'keypress') || type == 'blur'){
var word = '';
for(var i= val.length-1; i >= 0; i--){
if (val[i] == ' ' && gotLetter){
//we got the last entered word
//now append it to preview div
$("#previewDiv").append("<span>"+word+"</span>");
break;
}
else{
word = val[i]+word;
if (val[i] != ' '){
gotLetter = true;
}
}
}
}
}
</script>
Upvotes: 0
Reputation: 12674
I would just take all the text from the names
textbox and populate it in the preview div at each key-stroke unless performance becomes an issues.
$('#names').bind('keyup', function(){
var text = $(this).val();
var tokens = text.split(" ");
var output = "";
for(int i=0; i<tokens.length; i++){
output+= "<span>"+tokens[i]+"</span>&nbps;"; //note extra space at the end
}
$('#preview').innerHTML=output;
});
Upvotes: 1