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>functionmyFunction() {
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 - id
s must be unique always hence use different id
for different radio button.
functionmyFunction() {
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):
functiongetSelectedRadioValue() {
alert($('.myRadio:checked').first().val());
}
<html><head><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head><body><inputtype='radio'name='os'value="1"class='myRadio'>1
<inputtype='radio'name='os'value="2"class='myRadio'>2
<inputtype='radio'name='os'value="3"class='myRadio'>3
<p>Click the "Try it" button to display the value of the radio button.</p><buttononclick="getSelectedRadioValue()">Try it</button><pid="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:
functionsendMessage() {
$.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
});
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="body"></div><buttononclick="sendMessage()">execute AJAX call</button>
Post a Comment for "Selection Radio Button"