How to confirm a radio button selection with an alert box
11,342
Solution 1
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);
Solution 2
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
Author by
Spartan Man
Updated on July 14, 2022Comments
-
Spartan Man almost 2 years
So i have this code:
<html> <head> <title>Form</title> <script type="text/javascript"> function showConfirmationDialog() { var textbox = document.getElementById('textbox'); var location = document.getElementById('location'); alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n'); } function formfocus() { document.getElementById('textbox').focus(); } window.onload = formfocus; var option; </script> </head> <body> Your name: <input type="text" name="FirstName" id="textbox" <br><br/> Your Address: <input type="text" name="address" id="location" <br></br><br></br> Choose your location: <form name="Radio" id="destination" action=""> Bristol: <input type="radio" name="selection" value="bristol" onClick="option=0"> London: <input type="radio" name="selection" value="london" onClick="option=1"> Birmingham: <input type="radio" name="selection" value="birmingham" onClick="option=2" /> </form> <br></br> Click: <input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br> </body> </html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
-
Tyler Crompton over 12 yearsHe'd probably want to use
confirm()
instead ofalert()
. -
Yevgeny Simkin over 12 yearssure... I was just answering his question about how to get the value... if he's looking for a confirmation, then you're absolutely right, he should use confirm. I edited my answer with that slight enhancement, thanks for the note. :)