用 jQuery Focus Form 的第一個輸入欄位

Focus 是將游標設定於輸入框內, 但是要怎麼將 Forcus 設在 Form 的第一個 Input 或 Textarea 上?

有以下兩種寫法:

單行處理

取自: jQuery: Focus on First Form Element

  • // 將第一個 form 的 第一個 input type="text" 設 focus()
  • $("input[type='text']:first", document.forms[0]).focus();
  • // 若此 form 或 div .. 等, 有設 id 的話, 亦可寫成下面這行
  • $("input[type='text']:first", "#id-form").focus();

完整如下:

$(document).ready(function() {
    // focus on the first text input field in the first field on the page
    $("input[type='text']:first", document.forms[0]).focus();
});

寫成 Function 來快速呼叫

寫成 Function 來使用, 可自動判斷是 input/textarea 等來設定為第一個 focus, 將下述 function 放入一個 javascript file 中.(使用前記得引入此 function 即可)

取自: Focus first Form field with jQuery

// Focus first element
$.fn.focus_first = function() {
    var elem = $('input:visible', this).get(0);
    var select = $('select:visible', this).get(0);
    if (select && elem) {
        if (select.offsetTop < elem.offsetTop) {
          elem = select;
        }
    }
    var textarea = $('textarea:visible', this).get(0);
    if (textarea && elem) {
        if (textarea.offsetTop < elem.offsetTop) {
            elem = textarea;
        }
    }
 
    if (elem) {
        elem.focus();
    }
    return this;
}

使用方法:(記得上述 function 要先載入)

$(window).load(function() {
    $('form').focus_first();
);

其它相關網頁

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈用 jQuery Focus Form 的第一個輸入欄位〉中有 2 則留言

Tsung 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料