Como usar o rádio no evento de mudança?

Tenho dois botões de rádio. no evento de mudança eu quero mudar botão Como é possível? O Meu Código

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

Script

<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>

Este programa só funciona com o botão de rádio Allot seleccione apenas

Author: Saurabh Bayani, 2012-10-31

7 answers

Pode usar this que se refere ao elemento actual input.

$('input[type=radio][name=bedStatus]').change(function() {
    if (this.value == 'allot') {
        alert("Allot Thai Gayo Bhai");
    }
    else if (this.value == 'transfer') {
        alert("Transfer Thai Gayo");
    }
});

Http://jsfiddle.net/4gZAT/

Lembre-se que está a comparar o valor com allot tanto nas declarações if como no selector :radio está desactualizado.

No caso de não estar a utilizar jQuery, pode utilizar os métodos document.querySelectorAll e HTMLElement.addEventListener:

var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');

function changeHandler(event) {
   if ( this.value === 'allot' ) {
     console.log('value', 'allot');
   } else if ( this.value === 'transfer' ) {
      console.log('value', 'transfer');
   }  
}

Array.prototype.forEach.call(radios, function(radio) {
   radio.addEventListener('change', changeHandler);
});
 674
Author: undefined, 2018-07-08 12:12:09
Uma adaptação da resposta acima...
$('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;
     }
});

Http://jsfiddle.net/xwYx9/

 102
Author: Ohgodwhy, 2015-09-21 06:59:00

Uma maneira mais simples e mais limpa seria usar uma classe com a resposta de @Ohgodwhy

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

Script

​$( ".rButton" ).change(function() {
    switch($(this).val()) {
        case 'allot' :
            alert("Allot Thai Gayo Bhai");
            break;
        case 'transfer' :
            alert("Transfer Thai Gayo");
            break;
    }            
});​
 24
Author: RageAgainstTheMachine, 2015-09-17 09:48:05
$(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");
        }
    });
});

Violino JS

 15
Author: bromelio, 2014-08-08 13:27:18

Utilizar onchage Função

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot" onchange="my_function('allot')">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer" onchange="my_function('transfer')">Transfer

<script>
 function my_function(val){
    alert(val);
 }
</script>
 2
Author: sandeep kumar, 2018-01-29 05:30:47
<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>
 1
Author: Gupta Nambula, 2017-11-23 06:03:13
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);
  });
});
 1
Author: Piterden, 2018-04-23 10:15:54