October 22, 2024
Chicago 12, Melborne City, USA
PHP

How would I get my javascript to choose the correct radio button in a php dynamically generated radio button list?


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();
      
  }
}

So this is my javascript above trying to select the correct radio button. The reason I have it this way is because the radio button list is dynamically created with a php query.

<?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 } ?>

This is the php that generates the radio button list. However I can’t get it to actually select the right button. There’s no errors in the console so something is happening but not the way I want it to. Anyone know how to get this working?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video