Devdit
 

jQuery ดึงค่าจาก RadioButton ของ HTML ทำอย่างไร

667

สอนเขียน jQuery ดึงค่าจาก RadioButton ของ HTML โดยใช้ event change หรือ click ร่วมกับคำสั่ง val เพื่อดึงค่าของ input type radio ที่ผู้ใช้งานเลือก พร้อมแสดงผลลัพธ์ด้วยคำสั่ง console.log สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง jQuery ดึงค่าจาก RadioButton ของ HTML ทำอย่างไร

<input type="radio" value="jquery" class="radioBtn"> jQuery<br/>
<input type="radio" value="javascript" class="radioBtn"> JavaScript<br/>
<script>
   $(".radioBtn").change(function(){
       let v = $(this).val();
       console.log( "คุณเลือก "+v );
   });
</script>

ผลลัพธ์

คุณเลือก jquery

คำอธิบาย

jQuery ดึงค่าจาก RadioButton ของ HTML ตัวอย่างกำหนด class=radioBtn ให้กับ RadioButton ทั้งหมด เมื่อผู้ใช้งานกดเลือก radio ตัวใดก็ตาม event change ก็จะทำงานทำให้โปรแกรมวิ่งเข้าไปทำงานในฟังก์ชัน เวลาดึงค่าแนะนำใช้คำสั่ง $(this).val() หมายความว่าให้ดึงค่า radio จากตัวที่ถูกเลือก (this คือ ตัว radio ที่ถูกเลือก) เพราะ radio จะมีมากกว่า 1 ตัว

แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ