1

I'm doing some kind of screen keyboard where you click in some shapes and letters are written on a textarea. However I want it to work with the physical keyboard as well.

After writing the text into the textarea. I want to save the text on a string and print it.

Well it is working with the shapes, but with the physical keyboard, for some reason, it doesn't recognize the first character written. Only the second one. Thank you!

Demo: http://jsfiddle.net/bcorreia/e49v18bh/2/

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg width="60px" height="60px">
    <rect width="50" height="50" data-character="a" />
</svg>
<svg width="60px" height="60px">
    <rect width="50" height="50" data-character="b" />
</svg>

<textarea id="text"></textarea>

JS

 function getText() {
        var search_id = $("textarea#text").val();
        console.log(search_id);
        var dataString = 'search='+ search_id;

        if(search_id!='') {
            console.log("enter");
        };
    }

    $(function() {
        $('svg rect[data-character]').click(function() {
            var character = $(this).data('character');
            $('#text').val(function(i, old) { return old + character; });
            getText();
        });

        $('#text').keypress(function(e) {
            var character = String.fromCharCode(e.which);
            getText();
        });
    });  

3 Answers 3

1

You can see that it's one keypress behind, use keyup:

$('#text').keyup(function(e) {
    var character = String.fromCharCode(e.which);
    getText();
});

http://jsfiddle.net/e49v18bh/4/

Sign up to request clarification or add additional context in comments.

Comments

1

Try use keyup event instead on keypress

$('#text').keyup(function(e) {
   var character = String.fromCharCode(e.which);
   getText();
});

Demo: http://jsfiddle.net/e49v18bh/3/

keyup - Event fired when a key is released on the keyboard.

keypress - Event fired when a key is pressed on the keyboard.

Comments

0

I'm noticing some unnecessary code. On $('#text').keypress(), you declare the variable character yet don't use it.

The reason it's not printing the initial keyboard entry is because you are using .keypress(), which fires right as the key is being pressed (umm, yeah) which is before the character gets input. Use .keyup() instead to have it fire after the character is input and the user finishes their keypress.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.