使用JavaScript提交时获取单选按钮值
我这里有一个非常基本的HTML,我将最终变成一个iframe,它基本上只是一个简单的小部件,在用户端获得分数,然后我希望它将数据发送回我的rails后端。现在,我想知道当用户检查按钮并点击submit时如何获得分数使用JavaScript提交时获取单选按钮值,javascript,html,ruby-on-rails,Javascript,Html,Ruby On Rails,我这里有一个非常基本的HTML,我将最终变成一个iframe,它基本上只是一个简单的小部件,在用户端获得分数,然后我希望它将数据发送回我的rails后端。现在,我想知道当用户检查按钮并点击submit时如何获得分数 <html> <head> </head> <body> <h1 style="text-align:center">Net Promoter Score!</h1> <form id="NPSfo
<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>
净推广分数!
1.
2.
3.
4.
5.
6.
7.
8.
9
10
var分数
当用户点击提交时,我如何获得分数
感谢您严格使用Ruby on Rails 由于所有单选按钮元素都使用相同的
名称
属性,因此只有选定的值才会发布到服务器
因此,当您提交表单时,您应该能够使用params
集合使用相应的name
值访问“scores”:
params[:scores]
你可以
使用Javascript
如果要在提交
时使用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>
函数getScore(){
//获取所选分数(假设选择了一个)
var score=document.querySelector('input[name=“scores”]:checked')。值;
警报(选择了分数+’);
}
您可以在下面看到:
如果您想使用jquery获得值,可以执行以下操作
$('input[name=mysubmit]').on('click', function(e){
e.preventDefault();
console.log($('input[name=scores]:checked').val());
});
是否要提交表单并使用ajax发送数据??或者只是想直接做表单帖子??