JQuery: 如何找到不包括按钮的第一个可见输入/选择/文本区?

我尽力了

$(":input:not(input[type=button],input[type=submit],button):visible:first")

但什么都没发现。

我错在哪里?

UPD: 我在 $(document) . load ()上执行此命令

<script type="text/javascript">
$(window).load(function () {
var aspForm  = $("form#aspnetForm");
var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
firstInput.focus();
});
</script>

在调试中我可以看到 firstInput 是空的。

UPD2: 我在运行 Sharepoint 的 ASP.NET 页面中。

到目前为止,我发现对于某些元素,它确实能找到它们(对于固定的元素) ,而对于某些元素则没有

133363 次浏览

The JQuery code is fine. You must execute in the ready handler not in the window load event.

<script type="text/javascript">
$(function(){
var aspForm  = $("form#aspnetForm");
var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
firstInput.focus();
});
</script>

Update

I tried with the example of Karim79(thanks for the example) and it works fine: http://jsfiddle.net/2sMfU/

Why not just target the ones you want (demo)?

$('form').find('input[type=text],textarea,select').filter(':visible:first');

Edit

Or use jQuery :input selector to filter form descendants.

$('form').find('*').filter(':input:visible:first');

This is my summary of the above and works perfectly for me. Thanks for the info!

<script language='javascript' type='text/javascript'>
$(document).ready(function () {
var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
if (firstInput != null) {
firstInput.focus();
}
});
</script>

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
$(parent).find('input, textarea, select')
.not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
.filter(':enabled:visible:first')
.focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('form#aspnetForm');

Element:

var el = $('form#aspnetForm');
focusFirst(el);

You may try below code...

$(document).ready(function(){
$('form').find('input[type=text],textarea,select').filter(':visible:first').focus();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<form>
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
    

<input type="submit" />
</form>

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')