I have an array which store some data. I want to create a option
list by using javascript for loops. But I meet a problem, how do I insert the php code into the open tag? For example,
<option value="none">Please select your state</option>
<option value="Johor" <?php if($row['state'] === 'Johor') echo 'selected="selected"';?>>Johor</option>
<option value="Kedah" <?php if($row['state'] === 'Kedah') echo 'selected="selected"';?>>Kedah</option>
As you can see, there is php code included inside open tag. Below is the code that I am using.
function php_dropdown_state(){
let select = document.getElementById("state");
let options = ["Johor", "Kedah"];
for(let i = 0; i < options.length; i++) {
let opt = options[i];
let elements = document.createElement("option");
elements.innerHTML = "<?php if($row['state'] === '" + opt + "') echo 'selected=" + "selected" + "';?>";
elements.textContent = opt;
elements.value = opt;
select.appendChild(elements);
}
}
But this code will give me this result.
<option value="Johor">Johor</option>
<option value="Kedah">Kedah</option>