Question

I have two simple groups of radio button, like this:

Yes<input type="radio" name="first" value="yes"> No<input type="radio" name="first" value="no"><br>
Yes<input type="radio" name="second" value="yes"> No<input type="radio" name="second" value="no">
<h4 class="result"></h4>

And I will set them into like this:

  • If both of groups have "No" value, then the result in h4 is "Low"
  • If both of groups have "Yes" value, then the result is "High"
  • If both of groups have different value which is "yes" and "no" the result will be "Medium"

And so, I want to make it into jQuery with change event, how can I do that?

Was it helpful?

Solution

First, fix your markup by closing the input tags. Then:

$(function () {
    $('input[type="radio"]').on("change", function () {

        var firstChecked = $('input[type="radio"][name="first"]:checked').val();
        var secondChecked = $('input[type="radio"][name="second"]:checked').val();

        if (typeof firstChecked == "undefined" || typeof secondChecked == "undefined") return;

        var result = firstChecked == "yes" && secondChecked == "yes" ? "High" : firstChecked == "no" && secondChecked == "no" ? "Low" : "Medium";

        $('.result').text(result);
    });
});

Demo: http://jsfiddle.net/5dzHn/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top