Friday, March 11, 2016

How to capture value of a radio button in Java script?



Today I am answering a few questions newbies ask time and again.

Topic - JavaScript

How to show value of an variable?

var num = 5;
alert(num);


How to display value of an element?

alert(document.getElementById("txtName").value);


How to capture / read value of radio button?

alert(document.getElementById("isNew").checked);




I have written one example for demonstration of radio button use.
Please save this as an demo.html file and open in browser

<!DOCTYPE html>
<html>
<body>

<p>Please select gender:</p>

<form>
  <input type="radio" name="gender" value="Male"> I am boy<br>
  <input type="radio" name="gender" value="Female">I am girl<br>
  <br>
  <input type="button" onclick="go()" value="GO">
  <br><br>
  <input type="text" id="txtDisplay" size="50" value="Make selection">
</form>

<script>
function go() {
    var gender = document.forms[0];
    var txt = "";
     for (var i = 0; i < gender.length; i++ ){
        if (gender[i].checked) {
            txt =gender[i].value ;
        }
    }

    document.getElementById("txtDisplay").value = "You have selected gender as " + txt;
}
</script>

</body>
</html>

Please comment if you read this post.
Like it Share it so that someone else will also benefit.

No comments: