function statequery (theabbrev,thestate) {
if (abbrev.value.length > 0) {
enabledataentry();
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
var x = 0;
var statearray = JSON.parse(this.responseText);
if (statearray.length > 0){
stateabbrev.innerHTML=statearray[x].abbrev;
statename.innerHTML=statearray[x].statename;
pci.value=statearray[x].pci;
pop.value=statearray[x].pop;
radiobuttons = document.getElementsByName('stateradio');
for (var x=0; x < radiobuttons.length; x++){
if (radiobuttons[x].id === statearray.region) {
radiobuttons[x].checked=true;
break;
}
}
}
}
xhttp.open("GET", "statesearch.php?abbrev="+theabbrev, true);
xhttp.send();
}
}
所以这是我上面的 javascript 尝试选择正确的单选按钮。我这样做的原因是因为单选按钮列表是使用 php 查询动态创建的。
<?php foreach ($result as $row){ ?>
<input type="radio" id="<?php echo $row['region'];?>" disabled name="stateradio"/>
<label for="<?php echo $row['region'];?>">
<?php echo $row['region'];?></label><br />
<?php } ?>
这是生成单选按钮列表的 php。但是我无法让它实际选择正确的按钮。控制台中没有错误,所以发生了一些事情,但不是我想要的方式。有人知道如何让它工作吗?
''' 函数状态查询(theabbrev,thestate){
if (abbrev.value.length > 0) {
enabledataentry();
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
var x = 0;
var statearray = JSON.parse(this.responseText);
if (statearray.length > 0){
stateabbrev.innerHTML=statearray[x].abbrev;
statename.innerHTML=statearray[x].statename;
pci.value=statearray[x].pci;
pop.value=statearray[x].pop;
var regionval = statearray[x].region;
for (x=0; x < document.getElementsByName('stateradio').length; x++){
if (document.getElementsByName('stateradio').item(x).value==regionval){
document.getElementsByName('stateradio').item(x).checked=true;
}
}
}
}
xhttp.open("GET", "statesearch.php?abbrev="+theabbrev, true);
xhttp.send();
}
}
'''
我找到了我的 for 循环设置错误的解决方案,我还创建了一个包含 statearray.region 值的新变量来帮助我的代码。