views:

19

answers:

1

In order to highlight spacing between Chinese characters I've got this code

function replaceSpaces(){
    var segmented = $(this).val().replace(/\s/g, "<span>&emsp;</span>");
    $('#preview').html(segmented);
}
$(document).ready(function(){
    $('.tobesegmented').focus(replaceSpaces);
    $('.tobesegmented').change(replaceSpaces);
});

however, it does NOT trigger the change when I hit the space bar, only when i add text. Is there a way to trigger the replaceSpaces when a person hit's the space bar?

Bonus: Also, why does "&emsp;" become "&amp;emsp;"?

+2  A: 

You can use the keyup event instead (or in addition), like this:

$('.tobesegmented').bind('focus keyup', replaceSpaces);

.bind() can also take multiple event names separated by a space, so illustrating that as well, shaving a bit of code off :)

For the bonus: because it gets HTML encoded for you, as another example, .text('&') on an element will actually render &amp; in the HTML :)

Nick Craver
note that keyup will fire on non-printing keypresses as well, so (while in this case it's OK) it's sometimes a good idea to filter it to something approximating printables if that's what you're interested in.
DDaviesBrackett
this is perfect, will accept when i can (8 minutes)
Moak