604

I have two radio button on change event i want change button How it is possible? My Code

<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>
Ashish Mehta
  • 7,226
  • 4
  • 25
  • 52
  • I believe `if($("input[name='bedStatus']:checked").val() == 'allot')` can be written `if($("input[name='bedStatus']").val() == 'allot')` – mplungjan Oct 31 '12 at 07:22

11 Answers11

1186

You can use this which refers to the current input element.

$('input[type=radio][name=bedStatus]').change(function() {
    if (this.value == 'allot') {
        // ...
    }
    else if (this.value == 'transfer') {
        // ...
    }
});

http://jsfiddle.net/4gZAT/

Note that you are comparing the value against allot in both if statements and :radio selector is deprecated.

In case that you are not using jQuery, you can use the document.querySelectorAll and HTMLElement.addEventListener methods:

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);
});
Ram
  • 143,282
  • 16
  • 168
  • 197
171

An adaptation of the above answer...

$('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

double-beep
  • 5,031
  • 17
  • 33
  • 41
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • 2
    what's the difference between using 'on' and the answer above? – okenshield Mar 11 '14 at 14:12
  • 3
    @okenshield `.on()` really has on gains in relation to the above, however, when taking into account dynamic selectors, it's surely the only way to go in jQuery 1.7+ – Ohgodwhy Mar 11 '14 at 21:43
  • 6
    @Ohgodwhy - `on` has gains when you provide a context for event delegation, or even for dynamic selectors as you said, but the way you wrote it, is exactly the same as the above answer. – Hugo Silva Jul 30 '14 at 05:05
46

A simpler and cleaner way would be to use a class with @Ohgodwhy's answer

<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;
    }            
});​
pedromendessk
  • 3,538
  • 2
  • 24
  • 36
20
$(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 Fiddle

Pingui
  • 1,312
  • 4
  • 15
  • 28
  • 21
    Instead of `$(this).is(":checked")` use `this.checked`. It's pure JS and so it's a lot faster. – Gh61 Jul 13 '16 at 09:13
  • and instead of `$('#allot').click` use `document.getElementById('allot').onclick` or `addEventListener` so it's without jquery and lot faster – syahid246 Jul 20 '22 at 14:51
14

Simple ES6 (javascript only) solution.

document.forms.demo.bedStatus.forEach(radio => {
  radio.addEventListener('change', () => {
    alert(`${document.forms.demo.bedStatus.value} Thai Gayo`);
  })
});
<form name="demo">
  <input type="radio" name="bedStatus" value="Allot" checked>Allot
  <input type="radio" name="bedStatus" value="Transfer">Transfer
</form>
Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
13

Use onchage function

 
 function my_function(val){
    alert(val);
 }
   
<input type="radio" name="bedStatus" value="allot" onchange="my_function('allot')" checked="checked">Allot
<input type="radio" name="bedStatus" value="transfer" onchange="my_function('transfer')">Transfer
Sandeep Sherpur
  • 2,418
  • 25
  • 27
7

If the radio buttons are added dynamically, you may wish to use this

$(document).on('change', 'input[type=radio][name=bedStatus]', function (event) {
    switch($(this).val()) {
      case 'allot' :
        alert("Allot Thai Gayo Bhai");
        break;
      case 'transfer' :
        alert("Transfer Thai Gayo");
        break;
    }     
});
StripyTiger
  • 877
  • 1
  • 14
  • 31
6
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);
  });
});
Piterden
  • 771
  • 5
  • 17
3
<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
$(document).ready(function () {
    $('input:radio[name=bedStatus]:checked').change(function () {
        if ($("input:radio[name='bedStatus']:checked").val() == 'allot') {
            alert("Allot Thai Gayo Bhai");
        }
        if ($("input:radio[name='bedStatus']:checked").val() == 'transfer') {
            alert("Transfer Thai Gayo");
        }
    });
});
Ram Samuj
  • 11
  • 1
1

Add the class "pnradio" to the radio buttons, then switch with .attr('id')

<input type="radio" id="sampleradio1" class="pnradio" />
<input type="radio" id="sampleradio2" class="pnradio" />
    $('.pnradio').click(function() {
          switch ($(this).attr('id')) {
            case 'sampleradio1':
              alert("xxx");
              break;
            case 'sampleradio2':
              alert("xxx");
              break;
          }
        });
GeraGamo
  • 226
  • 3
  • 6