jQuery:如何取得Radio Button的值

2022/12/28閱讀時間約 2 分鐘
因為之前接到的案子有需要用到AJAX新增資料到後端
而裡面又有用到Radio Button的部分
所以需要取得選到的Radio Button的值
範例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radio Button</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
</head>
  <script>
    $(document).ready(function () {
      $("#btn_click").click(function () {
        console.log($("input[name='radio_button']:checked").val());
           });
      });
  </script>
<body>
<form>
<label><input type="radio" name="radio_button" value="1" checked>OPEN</label>
<label><input type="radio" name="radio_button" value="0">CLOSE</label>
<button type="button" id="btn_click">Click</button>
</form>
</body>
</html>
我這邊只用簡單的Click事件去取得選到的Radio Button
然後有個小技巧
用Label包住Radio Button的話 可以點選字就切換Radio Button
可以不用一定要點選到選項才能切換
使用者體驗感覺較佳喔!
參考資料:
林信嘉
林信嘉
留言0
查看全部
發表第一個留言支持創作者!