Page 1 of 1

JavaScript to prevent user from removing *part* of a value

Posted: Wed Feb 08, 2006 11:41 am
by Chris Corbyn
To give an idea of why I need this I'll explain.

I'm writing a tool that mimics a command line console... it uses JavaScript on the client side along with a bit of AJAX.

The cursor sits inside an input (type="text") element waiting for commands to be typed. This box has a prompt inside it:

Code: Select all

<input type="text" name="foo" value="prompt> " onkeyup="checkCommand()" />
Now when the command is sent, JavaScript simply removes the prompt text. The user can actually just backspace to delete the prompt at the moment though... I don't want that :( I actually want to somehow stop the caret from going in that part of the text box (hmm... I think I'm starting to figure this out in my head with document.selection).

I'm very aware that there are better ways to place the prompt there (use a div or span) but this just means that the styling and spacing will be consitent with the rest of the app... I'll change it if there really isn't a way to do this.

Anyone got any bright ideas? :)

Posted: Wed Feb 08, 2006 11:50 am
by feyd
heheh.. some trickery is in order! I've employed something like this previously with great success, although I can't remember the exact syntax, but hopefully it'll give you the idea:

Code: Select all

input, div.input { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 1em; line-height: 1.3em; height: 1.3em }
div.input { position: absolute; top: auto; left: auto }
div input { background: transparent; padding-left: 10em; border: 1px solid black }

<div>
  <div class="input">Prompt></div>
  <input type="text" value="sometext" />
</div>

Posted: Wed Feb 08, 2006 11:57 am
by pickle
In your onkeyup event, couldn't you check if the key was a 'backspace' or 'delete' and check if the cursor position is in the first 7 characters?

Otherwise, ~feyd's solution would work too.

Posted: Wed Feb 08, 2006 12:05 pm
by Chris Corbyn
pickle wrote:In your onkeyup event, couldn't you check if the key was a 'backspace' or 'delete' and check if the cursor position is in the first 7 characters?

Otherwise, ~feyd's solution would work too.
Problem with doing it onkeyup is that the user would see the "bounce" ... i.e. it would actually delete the character and then do the check. I think I'll just do what feyd suggested actually since you won't get the issues across different browsers... I was thinking about things like if the user changed the font size then the spacing between the prompt and the input wouldn't be one space character like it should be :( That and it would make it easier for users to write templates without including the prompt themselves...

I'll let you know how it goes :)

Thanks guys ;)