Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery focus on first text box or textarea when page loads

Tags:

jquery

I am attempting to write a JQuery to focus on the first visible, enabled text box or textarea in the second form when a page loads. In the example below, focus on input text2 in form2.

The solution proposed in jQuery Dynamically focus on the first INPUT or Textarea does not work for me.

Please note that we have multiple pages in our application. In some pages the first field of the form is a text box and in other pages the first field is a textarea. I want to write one JQuery method which will do the job for all the pages regardless of whether the first field is a text box or a textarea. In the example below, the solution should work if we swap the textarea1 and text2 fields around.

<div id="header">
  <form name="form1">
    <input type="text" name="text1">
  </form>
</div>
<div id="content">
  <form name="form2">
    <input type="checkbox" name="chc" value="test"><br>
    <input type="hidden" name="hide">
    <input type="text" name="text2"><br>
    <textarea name="textarea1"></textarea><br>
    <input type="text" name="text3">
  </form>
</div>

This is what I have tried so far...

// throws the error - $("#content input:text, #content textarea").first is not a function
$("#content input:text, #content textarea").first().focus();

// focuses on the textarea even if a text box is the first element in the form
$("#content textarea, #content[type='text']:visible:enabled:first").focus();

// focuses on the last text box in the page!
$("#content :input[type='text'], :textarea:visible:enabled:first").focus();

// focuses on the first text box even if a textarea is the first element in the form
$("#content :input[type='text']:visible:enabled:first, :textarea:visible:enabled:first").focus();

// focuses on the checkbox as it is the first input element
$('#content :input:visible:enabled:first').focus();

Thank you.

like image 246
neo108 Avatar asked Feb 16 '12 02:02

neo108


2 Answers

$("#content input:text, #content textarea").eq(0).focus()
like image 148
Adam Merrifield Avatar answered Nov 15 '22 01:11

Adam Merrifield


Here what you need:

​$(function(){
  $('form[name=form2]').find(':text, textarea').filter(":visible:enabled").first().focus();
})​

An example here

like image 37
Rafael Verger Avatar answered Nov 15 '22 01:11

Rafael Verger