![](/img/trans.png)
[英]How do I set the focus to the first input element in an HTML form independent from the id?
[英]how to set focus to first editable input element in form
動態創建的表單包含輸入元素。 第一個元素可能被禁用或只讀。 我累了下面的代碼將焦點設置為first elemnt,它接受數據以啟用快速數據輸入鍵盤。 但是,如果形成拳頭元素是禁用或只讀,則不設置焦點。 如何將焦點設置為接受數據的第一個元素?
<form style='margin: 30px' id="Form" class='form-fields' method='post' target='_blank'
action='Report/Render'>
...
<input id='_submit' type='submit' value='Show report' class='button blue bigrounded' />
</form>
<script type="text/javascript">
$(function () {
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea');
elements[0].focus();
elements[0].select();
});
</script>
更新
還有隱藏的輸入字段,抱歉。 答案提供了設置焦點隱藏元素。 包含函數的Answr沒有找到任何元素。
這是更新測試用例:
$(function () {
$("#form :input:not([readonly='readonly']):not([disabled='disabled'])").first()
.focus();
});
如何將焦點設置為vist visible,enabled和not readonly元素?
更新3
我嘗試了添加輸入元素的Row W代碼。 現在它將焦點放在第二個元素上。 測試用例顯示在Rob W的答案修訂版5中
使用以下代碼:
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea').filter(function(){
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
});
elements.focus().select();
如果您只想選擇第一個元素,則以下代碼更有效:
$('#Form').find(':text,:radio,:checkbox,select,textarea').each(function(){
if(!this.readOnly && !this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none") {
this.focus(); //Dom method
this.select(); //Dom method
return false;
}
});
更新:如果您希望元素具有相同的順序,請使用:
var elements = $("#form").find("*").filter(function(){
if(/^select|textarea|input$/i.test(this.tagName)) { //not-null
//Optionally, filter the same elements as above
if(/^input$/i.test(this.tagName) && !/^checkbox|radio|text$/i.test(this.type)){
// Not the right input element
return false;
}
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
}
return false;
});
使用jQuery的:not()
選擇器:
$("#myForm :input:not([readonly='readonly']):not([disabled='disabled']):reallyvisible").first()
.focus();
這是一個工作小提琴 。
編輯:
為了滿足您在評論中發布的新要求,您必須擴展:visible
選擇器以檢查父可見性(未經測試):
jQuery.extend(
jQuery.expr[ ":" ],
{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.