如何使用警告框确认单选按钮的选择

How to confirm a radio button selection with an alert box

本文关键字:单选按钮 选择 确认 何使用 警告      更新时间:2023-09-26

所以我有这个代码:

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

…这段代码基本上代表了一个供用户填写的表单,并在最后从单选按钮提供的三个选项中选择一个。我想知道的是,如何从用户需要选择的单选按钮中获得选择,在他们按下submit后显示在警告框中。

像这样…

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

您需要遍历选择无线电以获得选中的值:

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