Michael David
Michael David

Reputation: 113

How to show an entire select element in a div using only Javascript

I'm writing a code for a project and I want to be able to show an entire select element in a div.

I can't type in the code in the result area because I am calling most of the code from a database. I have tried putting a container around the select element but it still doesn't work. The select element in my work is called from a database and there are many of them which is why I am using '$x' to make each of the select elements unique. I have searched stackoverflow and other forums online but can't find an answer relating to my problem.

//some code above here
    $x = 1;
while($row = $result->fetch_assoc()){
    $uidcheck = mysqli_num_rows($result);
     $catname = $row['name'];
     $catrefno = $row['refno'];
     echo '
  <label class="container"><input type="radio" name="catname[]" id="catname'.$x.'" value="'.$catname.'"> '.$catname.'
  <span class="checkmark"></span></label>
<div id="selectdiv'.$x.'"><select class="form-control itnames" name="itname[]" id="itname'.$x.'" required>
<option></option>';
$sql1 = "SELECT * FROM foodarea WHERE status!='deactive' and itcatname='$catname'";
$result1 = $conn->query($sql1);
$uidcheck1 = mysqli_num_rows($result1);
if ($uidcheck1 > 0){
while($row1 = $result1->fetch_assoc()){
    $uidcheck1 = mysqli_num_rows($result1);
     $itname = $row1['itname'];
     echo '<option>'.$itname.'</option>';
    }
}
echo '</select></div>
<script>document.getElementById("catname'.$x.'").onchange = function() {
    var itnames = document.getElementById("selectdiv'.$x.'").innerHTML;
    var selectarea = document.getElementById("selectarea");
    selectarea.innerHTML = !this.checked ? "none" : itnames;
};</script>';
$x++;
}
}
echo '<div id="selectarea"></div>'

I expect that when the radio buttons are clicked, the entire select element with id - "itname'.$x.'" is shown in the div with id - "selectarea". But it does not. Instead it shows the value first option or a javascript error. Please I am a beginner and would really appreciate the help.

Upvotes: 1

Views: 60

Answers (1)

tom
tom

Reputation: 10529

Mistake is maybe here

<div class="selectdiv'.$x.'">

should be an id

<div id="selectdiv'.$x.'">

Upvotes: 2

Related Questions