How to perform a Js function when selecting a radio input

Asked

Viewed 3,119 times

2

My question is simple, how can I run a java Script function, as soon as a radio input is selected ?

2 answers

4


Follows a alternative using only javascript

var rad = document.form.radios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
  rad[i].onclick = function() {
    qualquerFuncao(this);
  }
};

function qualquerFuncao(e) {
  console.log(e.value);
}
<form name="form">
  <input type="radio" name="radios" value="radio 1" />
  <input type="radio" name="radios" value="radio 2" />
</form>

Here is another alternative, relatively simpler, using jquery

$(document).ready(function() {
  $('input:radio[name="radios"]').change(function() {
    if ($("input[name='radios']:checked")) {
      qualquerFuncao($(this).val());
    } else {
      //...
    }

  });
});

function qualquerFuncao(e) {
  console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form">
  <input type="radio" name="radios" value="radio 1" />
  <input type="radio" name="radios" value="radio 2" />
</form>

1

Simply call the function using the event change to the radio type camp:

jQuery(function($){
   $(':radio').change(function(){
      alert ("Codigo função");
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/action_page.php">
  <input type="radio" id="gender" name="gender" value="male"> Male<br>
  <input type="radio" id="gender" name="gender" value="female"> Female<br>
  <input type="radio" id="gender" name="gender" value="other"> Other<br><br>
  <input type="submit">
</form> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.