JavaScript Design Pattern for Text Input
October 22, 2013 4:31 PM   Subscribe

I'm writing a simple game in JavaScrip that needs to occasionally ask the user for text input. I don't want to use the JavaScript prompt() method. I want to display an HTML textbox and have my JavaScript code display the textbox and wait for the user to fill it out and hit ENTER. This seems like the sort of pattern that someone would have devised, but my Google-Fu is weak on this. Any help would be appeciated. Not looking for external libraries if they can be avoided, although JQuery would be acceptable. Thanks!
posted by DWRoelands to Computers & Internet (2 answers total) 1 user marked this as a favorite
 
Best answer:
<input type="text" id="textbox" value="default"/>

...

var textbox = document.getElementById("textbox");

textbox.onChange = function(){
  /* do stuff with text here */
  textbox.style.display = "none";
};

function thingThatAsksUserForInput() {
  /* other stuff ... */
  textbox.style.display = "";
}

posted by tylerkaraszewski at 4:41 PM on October 22, 2013 [1 favorite]


So occasionally, you want to force a site to do the following:

1. display a text box
2. put users cursor into the text box
3. display a question or instructions to the user
4. they finish typing and hit enter
5. you close the question and instructions

Is that it? Is there any validation of the input? If they mess up, do you do #5 above and then repeat at 1? Or should the text box respond somehow? Anything else?

And do you or do you not want jQuery. And do you have any other libraries available, and do you have any limitations as far as what browsers this needs to work in? And lastly, it sounds like JavaScript is obligatory, right? So no JS-free effort is required, right?
posted by artlung at 12:16 PM on October 23, 2013


« Older Plus Size Style 101, USA Female Edition   |   Is it worth it to insulate our apartment? Newer »
This thread is closed to new comments.