Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเลือก Radio Button โดย Default ใน JavaScript

เลือก radio button โดย default ต้องตั้ง checked = true ถ้า checked เป็น true จะ autofocus อัตโนมัติ

ตัวอย่าง: มี radio buttons เท่านั้น ไม่มีอันไหน autofocus

ตัวอย่าง (ไม่มี default)

<html> 
    <form id="radiobuttons" name="radiobutton"> 
        <input id="rad1" value="a" type="radio" name="check"/>male 
        <input id="rad2" value="b" type="radio" name="check"/>female 
        <input id="rad3" value="c" type="radio" name="check"/>other 
    </form> 
    <body> </body> 
</html>

รันโค้ดได้ radio buttons ไม่มีอันไหน autofocus

ผลลัพธ์

วิธีเลือก Radio Button โดย Default ใน JavaScript

เพื่อ autofocus ต้อง checked เริ่มต้น ใช้ pure JavaScript

ตัวอย่าง (มี default)

<html> 
    <form id="radiobuttons" name="radiobutton"> 
        <input id="rad1" value="a" type="radio" name="check"/>male 
        <input id="rad2" value="b" type="radio" name="check"/>female 
        <input id="rad3" value="c" type="radio" name="check"/>other 
    </form> 
    <body> 
        <script> 
            radiobtn = document.getElementById("rad1"); 
            radiobtn.checked = true; 
        </script> 
    </body> 
</html>

หลังรัน radio button แรกถูกเลือก

ผลลัพธ์

วิธีเลือก Radio Button โดย Default ใน JavaScript