阅读JS中的单选按钮选择

Reading in radio button selections in JS

本文关键字:单选按钮 选择 JS 阅读      更新时间:2023-09-26

我正试图获得一个弹出窗口来显示输入到表单中的内容。我已经设法让它显示输入到表格中的名称,但也希望它只使用JavaScript和HTML显示网站中给出的评级(单选按钮)。

<form>
<fieldset>
<legend><b>Details</b></legend>
<label>First Name </label><input id = "fname" type="text" autofocus="" placeholder="Enter first name" name = "fname"><br><br>
<label>Last Name </label><input type="text" placeholder="Enter last name"><br><br>
<label>Email </label><input type="email" placeholder="Enter valid email">  <button onclick="myFunction()">Help</button><br><br>
</fieldset>
<fieldset>
<legend><b>Rating</b></legend>
<label>Website Rating:</label>
 <input type="radio" name="Rating" value="1">* &#40;1 Star&#41;
 <input type="radio" name="Rating" value="2">* * &#40;2 Star&#41;
 <input type="radio" name="Rating" value="3">* * * &#40;3 Star&#41;
 <input type="radio" name="Rating" value="4">* * * * &#40;4 Star&#41;
 <input type="radio" name="Rating" value="5">* * * * * &#40;5 Star&#41;<br>
</fieldset>
<fieldset>
<legend><b>Comments</b></legend>
<label>Comments on the website:</label>
<textarea name="feedback1" rows="8" cols="70"></textarea><br>
</fieldset>
<fieldset>
<legend><b>Updates</b></legend>
Do you want to receive updates via Email?<br>
<input type="checkbox" name="updateYes" value="Yes">Yes 
<input type="checkbox" name="update" value="No" checked>No<br>
</fieldset>
<input type="reset" value="Reset">
<button onclick="myFunction2()" type = "submit">Submit</button>
</form>
<script>
function myFunction() {
    alert("Please enter a valid Email adress into the 'Email' field");
}
function myFunction2() {
    alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website ");
}
</script>
</body>
</html>

您可以使用querySelector进行以下操作:

var value = document.querySelector('input[name=Rating]:checked').value;
alert("Thank you for your feedback " + value + ", You have rated the website ");

示例:http://jsfiddle.net/bvaughn/kaqqsrc1/

您也可以使用getElementsByName:

var value;
var radios = document.getElementsByName("Rating");
for(var i = 0; i < radios.length; i++) {
    if(radios[i].checked) value = radios[i].value;
}

示例:http://jsfiddle.net/bvaughn/1qqqtafu/

通过循环选择单选按钮:

function myFunction2() {
  var checkedRadioButton, inputs, rating;
  inputs = document.getElementsByName("Rating");
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].checked) {
        checkedRadioButton = inputs[i];
        break;
    }
  }   
  if (checkedRadioButton) {
      rating = checkedRadioButton.value;
  }
  alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website " + rating);

}

https://jsfiddle.net/d5jo235p/