Submit inputField when Enter is clicked
Asked Answered
S

13

0

I tried the End Edit but it also submits when I click outside the inputField and I don’t want that.

I also tried the Event Trigger with type Submit but it doesn’t submit.

How can I submit an inputField only when the user clicks Enter?

Edit:
I want to use Unity 4.6 UI

Solley answered 17/1, 2024 at 17:46 Comment(0)
S
0
void Update()
{
    if (Input.GetKeyUp(KeyCode.Return)) { TapYourSubmitFunction(); }
}
Solley answered 17/1, 2024 at 17:40 Comment(0)
C
0

Not sure if there’s a built in way to do that as part of the GUI system, but you could always just do it manually using something like:

GUI.SetNextControlName("inputField");
input = GUI.TextField(new Rect(10, 10, 130, 20), input);
 
if(GUI.GetNameOfFocusedControl() == "inputField" && Input.GetKeyDown(KeyCode.Enter))
{
    DoWhatever();
}
Connubial answered 17/1, 2024 at 17:41 Comment(1)

Can't I do it with the new Unity 4.6 UI system?

Solley
S
0
void Update()
{
    if (Input.GetKeyUp(KeyCode.Return)) { TapYourSubmitFunction(); }
}
Solley answered 17/1, 2024 at 17:40 Comment(0)
P
0

Don’t put that in OnGUI(), put it in Update() instead.
OnGUI is used for the old IMGUI system.

Pearl answered 17/1, 2024 at 17:44 Comment(2)

I will change it, thank you very much

Solley

I tried to place it in Update and it stopped to work. InputField.isFocused become false when Input.GetKey(KeyCode.Return) or Input.GetKeyDown(KeyCode.Return) is true. OnGUI solution works well. I guess, event system uses OnGUI to update user input ( http://docs.unity3d.com/ScriptReference/Event.html ), so InputField looses focus before Update, but OnGUI tracks it.

Frothy
B
0

This still required me to hit enter twice to get it to fire.

I fixed it in this manner, by judging focus on the PREVIOUS update:

bool allowEnter;
void Update ()
{
    if (allowEnter && (usernameInput.text.Length > 0) && (Input.GetKey (KeyCode.Return) || Input.GetKey(KeyCode.KeypadEnter)))
    {
        OnSubmit ();
        allowEnter = false;
    } else allowEnter = usernameInput.isFocused || passwordInput.isFocused;
}
Blok answered 17/1, 2024 at 17:41 Comment(4)

its very helpful for me,many thanks!

Barriebarrientos

It worked for me . Also instead of putting code in update i putted in fixedupdate now i don't need to click twice

Calica

You can fix the issue of having to press enter twice easily by using Input.GetKeyDown(KeyCode.Return); instead //on input field enter if (allowEnter&& (message.text.Length > 0) && Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { //when enter is pressed } else { allowEnter = message.isFocused; }

Nought

To fix the issue of needing to click twice use Input.GetKeyDown(KeyCode.Return) instead

Nought
R
0

You can attach this to the InputField (change doSomething(...) to your code for submitting).

It also allows a Button to call validateAndSubmit() from onClick.

using UnityEngine;
using UnityEngine.UI;
  
/// <summary>Submits an InputField with the specified button.</summary>
//Prevents MonoBehaviour of same type (or subtype) to be added more than once to a GameObject.
[DisallowMultipleComponent]
//This automatically adds required components as dependencies.
[RequireComponent(typeof(InputField))]
public class SubmitWithButton : MonoBehaviour
{
	public string submitKey = "Submit";
	public bool trimWhitespace = true;
	//Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
	//Apropriate when initializing fields.
	void Start() {
		_inputField = GetComponent<InputField>();
		_inputField.onEndEdit.AddListener(fieldValue => {
			if (trimWhitespace)
				_inputField.text = fieldValue = fieldValue.Trim();
			if (Input.GetButton(submitKey))
				validateAndSubmit(fieldValue);
		});
	}
	InputField _inputField;
  
	bool isInvalid(string fieldValue) {
		// change to the validation you want
		return string.IsNullOrEmpty(fieldValue);
	}
	void validateAndSubmit(string fieldValue) {
		if (isInvalid(fieldValue))
			return;
		// change to whatever you want to run when user submits
		doSomething(_inputField); // or doSomething(fieldValue);
	}
	// to be called from a submit button onClick event
	public void validateAndSubmit() {
		validateAndSubmit(_inputField.text);
	}
}
Rhodie answered 17/1, 2024 at 17:42 Comment(0)
S
0

In the unity version 2017.2.0f3 in the InputField there is a filed where you can assign function to be called when user press the enter or the text field loses its focus:

105425-snap050.jpg

Sawyor answered 6/6, 2023 at 3:59 Comment(1)

To clarify, On End Edit is JUST for when the user presses enter (not loses focus), correct?

Leonerd
P
0

Yeah, but it’s kind of useless, since it hits the button whether you send “Return” or focus out…

Pinhead answered 6/6, 2023 at 2:11 Comment(0)
S
0

In Unity version 2017.4.26f1, the Menu.instance.addPlayer(_inputfield); code on line 34 is not running. the error I’m getting is:

error CS0117: ‘Menu’ does not contain a definition for ‘instance’

Anyone have any idea how to resolve this?

Silberman answered 17/1, 2024 at 17:42 Comment(1)

Sorry, I wasn't very clear on my answer before (this is a really old answer), you were supposed to change that line to whatever code you want it to run when user presses ENTER. I updated it now, replace doSomething(...) with a method you want to call.

Rhodie
W
0

I hooked up this event to the inputfield.EndEdit property in Inspector:

public void CustomOnSubmit()
{
    if (Input.GetKeyDown(KeyCode.Return))
      Debug.Log("Submit actions here");
    else
      Debug.Log("EndEdit, do not submit");
}
Wadley answered 17/1, 2024 at 17:43 Comment(0)
M
0

Don’t EVER use an update method to check for input from an input field in a game you intend on being efficient.

public InputField field;
void OnEnable()
{
    field.onEndEdit.AddListener(Enter);
}
void OnDisable()
{
    field.onEndEdit.RemoveAllListeners();
}
void Enter(string inputString)
{
    /// Action when enter is pressed here.
}

This is the industry standard way of handling an input field.
Pay attention to the fact that we remove listeners whenever possible.
Not necessarily OnDisable(), but when not in use, get rid of them.

I added this (very late) because students were unable to find answers to this question anywhere that met standard event systems logic.

Mammillate answered 17/1, 2024 at 17:42 Comment(1)

onEndEdit always triggers when the input field loses focus: If you press "enter" but also if you click outside, which most people probably don't want. There doesn't seem to be a way to just react to "enter" because even if you check for that key in "Update()" and also check inputField.isFocused, onEndEdit is still called first, so isFocused is always false.

Uzia
N
0

You can fix the issue of having to press enter twice easily by using
Input.GetKeyDown(KeyCode.Return); instead

//on input field enter
if (allowEnter&& (message.text.Length > 0) && Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
    //when enter is pressed
}
else
{
    allowEnter = message.isFocused;
}
Nought answered 17/1, 2024 at 17:44 Comment(0)
S
0

In case you stumble upon this decade-old post, I think the best solution would be this:

public InputField field;

private void OnEnable()
{
   field.onEndEdit.AddListener(OnEndEdit);
}

private void OnDisable()
{
   field.onEndEdit.RemoveListener(OnEndEdit);
}

private void OnEndEdit(string inputString)
{
   // Optional check if don't want users submitting an empty string.
   if (string.IsNullOrEmpty(inputString)) return;

   // Checks that OnEndEdit was triggered by a Return/Enter key press this frame,
   // rather than just unfocusing (clicking off) the input field.
   if (Input.GetKeyDown(KeyCode.Return))
   {
       // Logic to handle the input goes here (ie. use InputField.text somehow)
   }
}

Just wanted to spell out a more robust solution for folks and show that the script should really only remove its own listener, not all of them. You can also use TMP_InputField in place of InputField if you wish.

Scarab answered 23/1, 2024 at 2:46 Comment(1)

Thank you for this, exactly what I needed.

Uphold
T
0

I had a similar problem. I had 5 input fields and I wanted to be able to move smoothly from one to the other without having to use the mouse to select the next field. I tried the OnSubmit and OnEndEdit functions but could not trap the message. However, the OnValueChanged worked perfectly.

I decided that I would sacrifice the tab key and examined the last key pressed.

public int InputFocus = 0;

//Point the OnValueChanged of each InputField to the following function

public void TextEdited()
{
    bool tabPressed = Input.GetKeyDown(KeyCode.Tab); //Check required keypress
    if (tabPressed)
        ChangeInputFocus();
}

public void ChangeInputFocus()
{
    InputFocus = (InputFocus + 1) % 5;
    switch (InputFocus)
    {
        case 0:
            InputField2.Select();
            break;
        case 1:
            InputField3.Select();
            break;
        case 2:
            InputField4.Select();
            break;
        case 3:
            InputField5.Select();
            break;
        case 4:
            InputField1.Select();
            break;
    }
}

It is a simple solution - but it worked for my application. I guess it would also work in other cases too.

Tarshatarshish answered 18/1, 2024 at 16:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.