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.
$("#content input:text, #content textarea").eq(0).focus()
Here what you need:
$(function(){
$('form[name=form2]').find(':text, textarea').filter(":visible:enabled").first().focus();
})
An example here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With