คุณสมบัติ autofocus ของ HTML DOM Input Search เกี่ยวข้องกับแอตทริบิวต์ autofocus ขององค์ประกอบ HTML <input> คุณสมบัตินี้ใช้สำหรับตั้งค่าหรือส่งคืนว่าช่องค้นหา input ควรโฟกัสอัตโนมัติเมื่อโหลดหน้าหรือไม่
ไวยากรณ์
ไวยากรณ์สำหรับการตั้งค่าคุณสมบัติ autofocus:
searchObject.autofocus = true|false
ที่นี่ true แทนว่าช่องค้นหาควรได้รับโฟกัส และ false แทนตรงข้าม ตั้งค่าเป็น false โดยค่าเริ่มต้น
ตัวอย่าง
มาดูตัวอย่างของคุณสมบัติ autofocus ของ Input search:
<!DOCTYPE html> <html> <body> <h1>Input search autofocus property</h1> <form> FRUITS: <input type="search" id="SEARCH1" name="fruits" autofocus> </form> <p>ดึงค่าแอตทริบิวต์ autofocus ของช่องค้นหาด้านบนโดยคลิกปุ่มด้านล่าง</p> <button type="button" onclick="FocusVal()">CHECK FOCUS</button> <p id="Sample"></p> <script> function FocusVal() { var R = document.getElementById("SEARCH1").autofocus; document.getElementById("Sample").innerHTML = "The search field has autofocus property set to "+R; } </script> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:

เมื่อคลิกปุ่ม CHECK FOCUS:

ในตัวอย่างข้างต้น:
เราสร้างองค์ประกอบ <input> ที่มี type=”search” id=”SEARCH1” name=”fruits” และแอตทริบิวต์ autofocus ตั้งเป็น true ช่องค้นหาอยู่ในฟอร์ม:
<form> FRUITS: <input type="search" id="SEARCH1" name="fruits" autofocus> </form>
เราสร้างปุ่ม CHECK FOCUS ที่จะเรียกใช้เมธอด FocusVal() เมื่อผู้ใช้คลิก:
<button type="button" onclick="FocusVal()">CHECK FOCUS</button>
เมธอด FocusVal() ดึงองค์ประกอบ input type search โดยใช้ getElementById() และดึงคุณสมบัติ autofocus คุณสมบัติ autofocus คืนค่า true และ false ขึ้นอยู่กับค่าแอตทริบิวต์ autofocus ของช่องค้นหา ค่านี้กำหนดให้ตัวแปร f และแสดงในย่อหน้าที่มี id “Sample” โดยใช้ innerHTML:
function FocusVal(){ var f = document.getElementById("SEARCH1").autofocus; document.getElementById("Sample").innerHTML = "The search field autofocus property is set to: "+f; }