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>
the best is to transmit it in json, on an MVC architecture its must pass from the controller to the view, if we do this on a single page its must give:
let data = JSON.parse("<?= empty($row) ? "[]" : json_encode($row) ?>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.