[TriLUG] javascript backspace || edit in textbox

Paul McLanahan pmclanahan at gmail.com
Fri Aug 21 16:43:25 EDT 2009


If you don't mind using jQuery, I believe the following should work,
though it's untested:

<!-- In the body somewhere -->
<input type="text" name="author" id="author" value="Default Value">

<!-- In the head somewhere -->
<script type="text/javascript">
author_key_presses = 0

// make this happen on DOM ready
$(function(){

$("#author").keyup(function(e){
    var key = e.charCode || e.keyCode || 0;
    if(author_key_presses == 0 && key == 8){
        this.value = '';
    }
    author_key_presses++;
});

});
</script>

It's similar to that if you don't use jQuery, but there are some
cross-browser issues with getting the event object with which you'll
have to deal.

hth,

Paul

On Fri, Aug 21, 2009 at 3:46 PM, Joseph Mack NA3T<jmack at wm7d.net> wrote:
> What I would like is for the user to click on the text box. If they then
> backspace, the text box clears. Otherwise any other keystrokes are allowed
> to do normal editing (including a subsequent use of the backspace).
>
> Here's the javascript so far. It just clears the textbox on a click.
>
> <head>
> <script language="JavaScript" type="text/JavaScript">
> function clearbox(thebox){
>        thebox.value = "";
> }
> </script>
> </head>
>
> Here I simulate the user's previous search with defaults.
>
> <body>
> <INPUT type="text"  name="/author" size="30" value="Mark Twain"
> maxlength="100" onClick="clearbox(this);">
> </body>
>
> As a first step, clearing the box is fine. I now want to fix the function so
> that it watchs for keystrokes. If the first keystroke is a backspace, test
> with
>
> if (evt.keyCode == "8" )
>
> and allow the line
>
> thebox.value="";
>
> to run, otherwise the keystroke is left in whatever buffer it sits in, and
> the function just exits. As long as the user doesn't click again (to avoid
> invoking the function) all subsequent keystrokes (I hope) will just be
> editing.
>
> My problem is that I don't know how to get the function to read a single
> keystroke. I only know how to read keystrokes with lines in the html like
>
> onKeyPress = myFunction(event);
>
> Any ideas?
>
> Thanks Joe
>
> --
> Joseph Mack NA3T EME(B,D), FM05lw North Carolina
> jmack (at) wm7d (dot) net - azimuthal equidistant map
> generator at http://www.wm7d.net/azproj.shtml
> Homepage http://www.austintek.com/ It's GNU/Linux!
> --
> TriLUG mailing list        : http://www.trilug.org/mailman/listinfo/trilug
> TriLUG FAQ  : http://www.trilug.org/wiki/Frequently_Asked_Questions
>



More information about the TriLUG mailing list