Skip to content Skip to sidebar Skip to footer

Selection Radio Button

Am a bit stuck on where to go from here. I would like my radio button(s) to return the value of the selected button. But right now, its only return the value of the first item. How

Solution 1:

<script>
    function myFunction() {
        var x = document.getElementsByName('os');
        var rate_value;
        for(var i = 0; i < x.length; i++){
            if(x[i].checked){
                rate_value = x[i].value;
                break;
            }
        }
        document.getElementById("demo").innerHTML = rate_value;

    }
</script>


Solution 2:

Try this : iterate all radio button with name="os" and then check which one has checked attribute true.

NOTE - ids must be unique always hence use different id for different radio button.

function myFunction() {
    var radiobutton = document.getElementsByName("os");
    var x = '';
    for(var i=0;i<radiobutton.length;i++)
    {
       if(radiobutton[i].checked)
         x = radiobutton[i].value;
    }
    document.getElementById("demo").innerHTML = x;
}

Solution 3:

First of: An element Id should be unqiue id='myRadio' in a while loop wont be unique.

i would suggest using class (instead of id) and jQuery (for-css like selectors in javascript):

function getSelectedRadioValue() {
  alert($('.myRadio:checked').first().val());
}
<html>

<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <input type='radio' name='os' value="1" class='myRadio'>1
  <input type='radio' name='os' value="2" class='myRadio'>2
  <input type='radio' name='os' value="3" class='myRadio'>3

  <p>Click the "Try it" button to display the value of the radio button.</p>
  <button onclick="getSelectedRadioValue()">Try it</button>
  <p id="demo"></p>

</body>

</html>

ajax Example

Ajax is a synchronious server calls and they return data you can use in jquery on your website. For example:

function sendMessage() {

  $.post("your url to serverside script you want to execute.php"
  , { 'Index': 'Data Found in $_Post'} //in execute.php $_POST['Index'] will now contain: 'Data Found in $_Post'
  , function(data) {
    //in data will be the stuff you echo-ed in your php script (if you used json_encode($data) in php this will be automatically detected and converted to a javascript object.
    $("$body").html(data); //for instance we get html from the AJAX call (execute.php) and insert in the #body div
  }).fail(function(){
    alert('The server returned an error'); //ofcourse server returns an error, because URL used in this example does not exist
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body">

</div>

<button onclick="sendMessage()">execute AJAX call</button>

Post a Comment for "Selection Radio Button"