我有两个单选按钮 在改变事件我想改变按钮怎么可能? 我的代码

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer

脚本

<script>
    $(document).ready(function () {
        $('input:radio[name=bedStatus]:checked').change(function () {
            if ($("input[name='bedStatus']:checked").val() == 'allot') {
                alert("Allot Thai Gayo Bhai");
            }
            if ($("input[name='bedStatus']:checked").val() == 'transfer') {
                alert("Transfer Thai Gayo");
            }
        });
    });
</script>

当前回答

document.addEventListener('DOMContentLoaded', () => {
  const els = document.querySelectorAll('[name="bedStatus"]');

  const capitalize = (str) =>
    `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

  const handler = (e) => alert(
    `${capitalize(e.target.value)} Thai Gayo${e.target.value === 'allot' ? ' Bhai' : ''}`
  );

  els.forEach((el) => {
    el.addEventListener('change', handler);
  });
});

其他回答

<input type="radio" name="radio"  value="upi">upi
<input type="radio" name="radio"  value="bankAcc">Bank

<script type="text/javascript">
$(document).ready(function() {
 $('input[type=radio][name=radio]').change(function() {
   if (this.value == 'upi') {
    //write your logic here

    }
  else if (this.value == 'bankAcc') {
    //write your logic here
 }
 });
 </script>

使用onchage函数

函数my_function(val){ 警报(val); } <输入类型=“收音机” 名称=“床状态” 值=“分配” onchange=“my_function('分配')” checked=“checked”>分配 <输入类型=“收音机” 名称=“床状态” 值=“传输” onchange=“my_function('传输')”>传输

一种更简单、更清晰的方法是使用带有@Ohgodwhy答案的类

<input ... class="rButton">
<input ... class="rButton">

脚本

​$( ".rButton" ).change(function() {
    switch($(this).val()) {
        case 'allot' :
            alert("Allot Thai Gayo Bhai");
            break;
        case 'transfer' :
            alert("Transfer Thai Gayo");
            break;
    }            
});​
$(document).ready(function () {
    $('#allot').click(function () {
        if ($(this).is(':checked')) {
            alert("Allot Thai Gayo Bhai");
        }
    });

    $('#transfer').click(function () {
        if ($(this).is(':checked')) {
            alert("Transfer Thai Gayo");
        }
    });
});

JS小提琴

对上述答案的改编……

$('input[type=radio][name=bedStatus]').on('change', function() { switch ($(this).val()) { case 'allot': alert("Allot Thai Gayo Bhai"); break; case 'transfer': alert("Transfer Thai Gayo"); break; } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot <input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer

http://jsfiddle.net/xwYx9