使用JavaScript获取提交单选按钮值

Spa*_*nce 2 html javascript ruby-on-rails

我在这里有这个非常基本的HTML,我最终会变成一个iframe,它基本上只是一个简单的小部件,在用户端获得分数,然后我希望它将数据发送回我的rails后端.现在,我正试图找出当用户检查按钮并点击提交时如何获得分数.

<html>
<head>
</head>
<body>
  <h1 style="text-align:center">Net Promoter Score!</h1>
  <form id="NPSform"; style= "text-align:center">

    <input type="radio" name="scores" id="1" value="1"> 1
    <input type="radio" name="scores" id="2" value="2"> 2
    <input type="radio" name="scores" id="3" value="3"> 3
    <input type="radio" name="scores" id="4" value="4"> 4
    <input type="radio" name="scores" id="5" value="5"> 5
    <input type="radio" name="scores" id="6" value="6"> 6
    <input type="radio" name="scores" id="7" value="7"> 7
    <input type="radio" name="scores" id="8" value="8"> 8
    <input type="radio" name="scores" id="9" value="9"> 9
    <input type="radio" name="scores" id="10" value="10"> 10
    <input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>


<script>

var scores


</script>
</html>
Run Code Online (Sandbox Code Playgroud)

如何在用户点击提交时获得分数?

谢谢

Rio*_*ams 5

严格使用Ruby on Rails

由于所有单选按钮元素都使用相同的name属性,因此只有选定的值将发布到服务器.

因此,当您提交表单时,您应该能够name使用params集合使用相应的"得分"值来访问该值:

params[:scores]
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关使用Ruby on Rails参数的更多信息.

使用Javascript

如果您想<form>在提交时使用Javascript检索所选值,则可以创建一个事件监听器来监听submit要触发的事件,然后获取所选值:

<!-- Notice the getScore() function will be called when the form is submitted -->
<form id="NPSform" ... onsubmit='getScore();'>
  <!-- Elements omitted for brevity -->      
  <input type="submit" name="mysubmit" value="Submit"/>
</form>
<script>
   function getScore(){
       // Get the selected score (assuming one was selected)
       var score = document.querySelector('input[name="scores"]:checked').value;
       alert(score + ' was selected!');
   }
</script>
Run Code Online (Sandbox Code Playgroud)

您可以在此处看到此示例,如下所示:

在此输入图像描述