单选按钮选择值;选择3个选项

时间:2016-10-16 15:24:56

标签: javascript html radio-button alert getelementbyid

仅使用HTML和JavaScript,我试图获得名字,姓氏详细信息,然后从三个单选按钮中选择喜欢的颜色。我可以得到名字和姓氏,但不能做单选按钮吗?

HTML文件:

<html>

<title>Task 3</title>

<head>
    <script type="text/javascript" src="script.js"></script>
</head>

<body>

    <form name="formDetails">
        First Name:<input type="text" id="firstName"><br>
        Last Name:<input type="text" id="lastName"><br>
        <p>Favourite Colour:</p>
        <input type="radio" name="colour" value="Red">Red<br>
        <input type="radio" name="colour" value="Blue">Blue<br>
        <input type="radio" name="colour" value="Green">Green<br>
        <input type="button" onclick="display()" value="Submit">
    </form>

</body>

JavaScript文件:

function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;

alert(firstName + " " + lastName);
}

我不知道如何实现单选按钮?我见过一些人使用jQuery,但我想在这里坚持使用JavaScript,因为我相当新。

感谢。

2 个答案:

答案 0 :(得分:0)

JS:

var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);

答案 1 :(得分:0)

步骤:

  • 为名为check_in的所有输入标签添加一个类。

  • 使用javascript查找此类的所有标签

  • 遍历每个标记以确定检查了哪些标记。如果选中了标记,请将其添加到名为results的变量中。

  • 最后从输入框中获取名字和姓氏,并将这些值添加到名为results的变量

    &#13;
    &#13;
    function display() {
      results = {}
      var firstName = document.getElementById("firstName").value;
      var lastName = document.getElementById("lastName").value;
      var all_input = document.getElementsByClassName('check_in');
      for (var i = 0; i < all_input.length; ++i) {
        if (all_input[i].checked == true) {
          results['option'] = all_input[i].value;
        }
      }
      results['firstname'] = firstName;
      results['lastname'] = lastName;
      console.log(results);
      alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
    }
    &#13;
    margin:50px auto auto;
    &#13;
    <html>
    
    <title>Task 3</title>
    
    <head>
      <script type="text/javascript" src="script.js"></script>
    </head>
    
    <body>
    
      <form name="formDetails">
        First Name:
        <input type="text" id="firstName">
        <br>Last Name:
        <input type="text" id="lastName">
        <br>
        <p>Favourite Colour:</p>
        <input type="radio" name="colour" value="Red" class="check_in">Red
        <br>
        <input type="radio" name="colour" value="Blue" class="check_in">Blue
        <br>
        <input type="radio" name="colour" value="Green" class="check_in">Green
        <br>
        <input type="button" onclick="display()" value="Submit">
      </form>
    
    </body>
    &#13;
    &#13;
    &#13;