Submit inputField when Enter is clicked

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

void Update()
{
    if (Input.GetKeyUp(KeyCode.Return)) { TapYourSubmitFunction(); }
}

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

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;
}

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);
	}
}

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

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.

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();
}

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

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?

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");
}

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;
}

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.

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.