如何从javascript设置html无线电值? 我试试这段代码
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$.getJSON("getquestion.php",function(result)
{
//set radio value
//$("#choice").html(result.test_choice_a);
//$("#choice").val(result.test_choice_a);
//$("#choice").html(result.test_choice_b);
//$("#choice").val(result.test_choice_b);
//$("#choice").html(result.test_choice_c);
//$("#choice").val(result.test_choice_c);
//$("#choice").html(result.test_choice_d);
//$("#choice").val(result.test_choice_d);
document.testform.choice[0].value = result.test_choice_a;
document.testform.choice[1].value = result.test_choice_b;
document.testform.choice[2].value = result.test_choice_c;
document.testform.choice[3].value = result.test_choice_d;
}
</script>
<input type="radio" name="choice" id="choice" ><br>
<input type="radio" name="choice" id="choice"><br>
<input type="radio" name="choice" id="choice"><br>
<input type="radio" name="choice" id="choice"><br>
但它不起作用。
我该怎么设置?请帮帮我。
答案 0 :(得分:1)
可能内容尚未加载,但仍将您的ajax调用放入$(document).ready()
$(document).ready(function(){
$.getJSON("getquestion.php",function(result)
{
//set radio value
//$("#choice").html(result.test_choice_a);
//$("#choice").val(result.test_choice_a);
//$("#choice").html(result.test_choice_b);
//$("#choice").val(result.test_choice_b);
//$("#choice").html(result.test_choice_c);
//$("#choice").val(result.test_choice_c);
//$("#choice").html(result.test_choice_d);
//$("#choice").val(result.test_choice_d);
document.testform.choice[0].value = result.test_choice_a;
document.testform.choice[1].value = result.test_choice_b;
document.testform.choice[2].value = result.test_choice_c;
document.testform.choice[3].value = result.test_choice_d;
});
});
元素ID也应该是唯一的。
答案 1 :(得分:0)
你不能给很多元素提供id
$(document).ready(function () {
$.getJSON("getquestion.php", function (result) {
$("#choice_1").val(result.test_choice_a);
$("#choice_2").val(result.test_choice_b);
$("#choice_3").val(result.test_choice_c);
$("#choice_4").val(result.test_choice_d);
});
});
答案 2 :(得分:0)
您需要为每个电台提供唯一的ID。
<script type="text/javascript">
$.getJSON("getquestion.php",function(result) {
//set radio value
$("#choice_1").val(result.test_choice_a);
$("#choice_2").val(result.test_choice_b);
$("#choice_3").val(result.test_choice_c);
$("#choice_4").val(result.test_choice_d);
}
</script>
<input type="radio" name="choice" id="choice_1" ><br>
<input type="radio" name="choice" id="choice_2"><br>
<input type="radio" name="choice" id="choice_3"><br>
<input type="radio" name="choice" id="choice_4"><br>