My question is simple, how can I execute a java script function, once an input radio is selected?
My question is simple, how can I execute a java script function, once an input radio is selected?
Follow an alternative using just 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's another relatively simpler alternative, 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><formname="form">
<input type="radio" name="radios" value="radio 1" />
<input type="radio" name="radios" value="radio 2" />
</form>
Just call the function using the change
event for the radio type field:
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><formaction="/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>