【发布时间】:2016-11-07 23:03:11
【问题描述】:
提交表单时,我在获取单选按钮值时遇到问题。我认为提交表单时,它会得到用户所做的最终选择,但它似乎无法识别选择了哪一个。
初始加载时:这是在我的表单中
<div id="question1">
<label> Do you shop mostly on-line or at physical stores? </label>
<div class="radioButtons">
<span>
Mostly on-line stores
<input name="question1" value="on-line" type="radio">
</span>
<span>
mostly physical stores
<input name="question1" value="physical" type="radio">
</span>
<span>
About both equaly
<input name="question1" value="both" type="radio">
</span>
</div>
</div>
在我的提交处理程序中
$(".aboutmeQuestions").on("submit", function(e){
e.preventDefault();
var values = {};
var $inputs = $(".aboutmeQuestions :input").not(":submit");
$inputs.each(function(){
values[this.name] = {answer : $(this).val()};
});
//I thought the above would get the radio buttons but I think it got the last choice as the selected one no matter what was chosen. so I tried below because I thought that the checked attribute would change automatically.
$("input[type='radio']").each(function(){
console.log("this ",this);
if($(this).attr("checked")){
values[this.name] = {answer : $(this).val()};
}
})
在我的 EJS 中:
<div id="question1">
<label> <%=aboutUser.question1.question%> </label>
<div class = "radioButtons">
<span>Mostly on-line stores <input type="radio" name="<%=aboutUser.question1.name%>" value="on-line" <% if(aboutUser.question1.answer == "on-line"){%> checked <%}%>> </span>
<span>mostly physical stores <input type="radio" name="<%=aboutUser.question1.name%>" value="physical" <% if(aboutUser.question1.answer == "physical"){%> checked <%}%>> </span>
<span> About both equaly <input type="radio" name="<%=aboutUser.question1.name%>" value="both" <% if(aboutUser.question1.answer == "both"){%> checked <%}%> ></span>
</div>
</div>
我测试过了。在单击任何内容并按下提交按钮后,我得到了 values 对象,question5[answer]: maybe" question1[answer]: "both" 应该等于没有。无论我点击什么,它总是这样。我不喜欢这样,请帮我解决它。我不认为我必须使用更改方法。
Ps 我将这些数据保存到数据库中,并且输入应该填充答案,因此当我重新加载页面 <span>
About both equaly<input name="question1" value="both" checked="" type="radio">
</span> 时。它不应该被检查,因为我没有选择任何东西。
【问题讨论】:
标签: javascript jquery html forms ejs