Set focus on textbox after postback

I have a search page with 3 TextBoxes that users can filter a search with.

I have put the focus on the TextBox that contains text. If more than one contains text just focus on last TextBox.

private void SetFocusOnTextBox(ControlCollection ctrlCollection)
{
    foreach (Control ctrl in ctrlCollection)
    {
        if (ctrl.GetType() == typeof(TextBox))
        {
            if (((TextBox)ctrl).Text != string.Empty)
            {
                SetFocus(ctrl);
            }
        }
    }
}

After the code runs and a user searches, the focus comes to the beginning of the TextBox, not the end where it would be presumed. How to put insert marked at the end of that TextBox?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think the answer is here: Use JavaScript to place cursor at end of text in text input element.

Taken from the linked solution: You have to add onfocus="this.value = this.value" to the three controls in the markup file. This is not so easy in ASP.NET as it should be, but one solution is to add the attribute in the code behind file.

protected void Page_Init(object sender, EventArgs e)
{
    // MoveCursorToEndOnFocus is called in Page_Init and not Page_Load to avoid
    // filling the ViewState with unnecessary data.
    // TODO: Call MoveCursorToEndOnFocus here.
}

private void MoveCursorToEndOnFocus(ControlCollection controlCollection)
{
    foreach (TextBox textBox in controlCollection
        .Where(control => control.GetType() == typeof(TextBox)))
    {
        textBox.Attributes.Add("onchange", "this.value = this.value");
    }
}

Method 2

Shouldn’t it be

if (((TextBox)ctrl).Text == string.Empty)

to advance to the bottommost empty textbox? If it is if (((TextBox)ctrl).Text != string.Empty), it will set focus (eventually) to the bottommost nonempty textbox.

As for advancing your cursor to the last character, try this:

function cursorToEnd( elem )
{
  elem.focus();
  elem.value+='x';
  elem.value=elem.value.replace(/x$/,"");   
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x