jquery 中的val(),可以取值也可赋值,表单元素中的radio和checkbox是比较常用的控件,下面说说对它们的取值和赋值的使用
1、取值
表单如下:
<div class="items"> @if (Model.Question.type == "单选") { <div><input type="radio" id="A" name="sin" value="A" /><label for="A"><span class="item">A</span>@Model.Question.A</label></div> <div><input type="radio" id="B" name="sin" value="B" /><label for="B"><span class="item">B</span>@Model.Question.B</label></div> <div><input type="radio" id="C" name="sin" value="C" /><label for="C"><span class="item">C</span>@Model.Question.C</label></div> <div><input type="radio" id="D" name="sin" value="D" /><label for="D"><span class="item">D</span>@Model.Question.D</label></div> } else if (Model.Question.type == "多选") { <div><input type="checkbox" id="A" name="mul" value="A" /><label for="A"><span class="item">A</span>@Model.Question.A</label></div> <div><input type="checkbox" id="B" name="mul" value="B" /><label for="B"><span class="item">B</span>@Model.Question.B</label></div> <div><input type="checkbox" id="C" name="mul" value="C" /><label for="C"><span class="item">C</span>@Model.Question.C</label></div> <div><input type="checkbox" id="D" name="mul" value="D" /><label for="D"><span class="item">D</span>@Model.Question.D</label></div> } else { <div><input type="radio" id="A" name="jul" value="@Model.Question.A" /><label for="A"><span class="item"></span>@Model.Question.A</label></div> <div><input type="radio" id="B" name="jul" value="@Model.Question.B" /><label for="B"><span class="item"></span>@Model.Question.B</label></div> } </div>
jquery代码:
$(".items input").click(function () { var answer = ""; if (type == "单选") { answer = $(":radio[name=sin]:checked").val(); alert(answer); } else if (type == "多选") { $(":checkbox[name=mul]:checked").each(function () { answer += $(this).val() + ","; }); } else { answer = $("input:radio[name=jul]:checked").val(); } $.post("/home/clickItem", { questionId: '@Model.Question.id', userAnswer: answer }, function (data) { if (data != "ok") { alert(data); location.href = "/home/login"; } }); });
radio 好取,只要取 :checked 选中的值,checkbox 可能是多选,需要循环取值
2、赋值
赋值可不能这样 $(":radio").val("B"),这种是不行的,使用数组的方式赋值,应该这样 $(":radio").val(["B"]) ,$(":checkbox").val(["A","C","D"]),
if (type == "单选") { $(":radio[name=sin]").val([useranswer]); } else if (type == "多选") { var arr = useranswer.substring(0, useranswer.length - 1).split(","); //useranswer="B,C,D"这种形式转成数组 $(":checkbox[name=mul]").val(arr); } else { answer = $(":radio[name=jul]").val([useranswer]); }