我正在尝试将一些值从 json 字符串加载到各种输入/字段。我的解决方案适用于文本输入和文本字段,但我无法让它与单选按钮和复选框一起使用。你能帮我这个吗?
在HTML中,我有一些字段,如下所示:
<textarea rows="3" name="testfield"></textarea>
<input type="text" name="testinput">
<label><input class="radio" type="radio" name="testrad" value="one" checked><span>1</span></label>
<label><input class="radio" type="radio" name="testrad" value="two" ><span>2</span></label>
<label><input class="radio" type="radio" name="testrad2" value="one" checked><span>1</span></label>
<label><input class="radio" type="radio" name="testrad2" value="two" ><span>2</span></label>
<label><input class="radio" type="radio" name="testrad2" value="three" ><span>2</span></label>
使用 AJAX 调用,我得到 json 字符串,如下所示:
{"testfield":"Value of testfield", "testinput":"Value of testinput","testrad":"two","testrad2":"three"}
这是JS代码:
$.ajax({
type: "POST",
url: "test.php",
success: function (echo) {
var data = JSON.parse(echo);
for (key in data) {
var field = $("[name=" + key);
if (field.attr("type") == "radio" || field.attr("type") == "checkbox") {
if ( field.val() == data[key]) {
field.prop("checked", true)
}
}else {
$("[name=" + key).val(data[key]);
}
}
}
});
以下是您正在寻找的演示:
var key = 'testrad2';
var val = 'three'; // lets say three from response
var field = $("[name=" + key);
field.each(function(){
if($(this).val() == val) {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="3" name="testfield"></textarea>
<input type="text" name="testinput">
<label><input class="radio" type="radio" name="testrad" value="one" checked><span>1</span></label>
<label><input class="radio" type="radio" name="testrad" value="two" ><span>2</span></label>
<label><input class="radio" type="radio" name="testrad2" value="one" checked><span>1</span></label>
<label><input class="radio" type="radio" name="testrad2" value="two" ><span>2</span></label>
<label><input class="radio" type="radio" name="testrad2" value="three" ><span>2</span></label>