简体   繁体   中英

How to confirm a radio button selection with an alert box

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">

&nbsp;&nbsp;&nbsp; London: 

<input type="radio"  name="selection" value="london" onClick="option=1">

&nbsp;&nbsp;&nbsp; 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.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM