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

时间:2011-11-09 21:04:01

标签: javascript html alert

所以我有这段代码:

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

...此代码基本上代表用户填写的表单,最后选择通过单选按钮提供的三个选项之一。我想知道的是,如何从用户需要选择的一个单选按钮中选择,在按下提交后显示在警告框内。

2 个答案:

答案 0 :(得分:1)

像这样......

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

答案 1 :(得分:0)

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

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