Limiting textbox inputs to numbers.

Started by Bearstonaut, Sat 30/04/2011 17:58:52

Previous topic - Next topic

Bearstonaut

Hello.

I'm halfway to finishing my first proper (50-room game).  It's been a long four months, but I couldn't have done it without reading all of the guidance present on these forums.

Now I've got a question of my own.

I have a textbox in a GUI that will appear under certain conditions.  When it does, I want the user to be able to enter any number they want. 
I want the user to be limited to entering numbers only.
I also want to check that the number entered is greater than zero.

I figure this involves string manipulation and dark magic.  Can somebody kindly steer me in the right direction?

Thanks, in advance.

Sephiroth

#1
You could create a global String called oldtext with no default value, then inside repeatedly_execute_always:

Code: ags


if(MyTextBox.Visible && MyTextBox.Text != oldtext)
{
  if(MyTextBox.Text.Chars[MyTextBox.Text.Length-1] <= '0' || MyTextBox.Text.Chars[MyTextBox.Text.Length-1] > '9')
  {
    MyTextBox.Text = oldtext;
  }
  oldtext = MyTextBox.Text;
}



It should filter the input, altho you will still see the char brievly.
Otherwise you should be able to use the on_key_press function with a label like this:

Code: ags


  if(MyLabel.Visible && keycode > 0 && keycode <= 9)
    MyLabel.Text.AppendChar(keycode);



Calin Leafshade

doesnt the text box have an OnChanged event?

If it does you can use that in a similar way to that which seph described

Sephiroth

I ran into this problem a while ago, and it seems there's only onActivate.

Bearstonaut

#4
The textbox is within a GUI.  Is it possible to have a repeatedly_execute_always within a GUI?  Or does it go in the rooms in which the GUI is accessed?

Sephiroth

#5
Nope, just put the code in the global script repeatedly_execute_always, replacing, MyTextBox with the scriptname of your textbox, or MyLabel with the scriptname of the label you're using inside the global script on_key_press.

The problem being, AGS textboxes have their own on_key_press event and are only passing i.e UP/Down keys to the regular on_key_press, all the letters/numbers and printable characters will not be intercepted by the on_key_press while the texbox is active on a visible gui.

Bearstonaut

It works exactly as you said.  Thank you very much.  Looks like I'll have to name my firstborn Sephiroth.

Sephiroth

I just wanted to edit the above code to reflect the "greater than zero" and a quick test to avoid comparing strings everytime (bad habit). It's just a matter of replacing the signs/operators, but you probably figured this out.

I hope you'll release it soon, we're always looking forward to playing new AGS games, especially when the author is working hard on it :)

SMF spam blocked by CleanTalk