-1

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>
Hon Wi Cong
  • 131
  • 9
  • 3
    Why would you! It cannot do anything as the javascript is running in the browser and therfore it is too late to run PHP code as that only runs on the server [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – RiggsFolly Dec 01 '21 at 17:55
  • Why wouldn't you just generate the dropdown using PHP? The use case for what you're proposing is not obvious – ADyson Dec 01 '21 at 19:53
  • Or just set the `selected` attribute, by doing the same thing in JS instead of PHP ...? – CBroe Dec 02 '21 at 08:28
  • Trying to use `elements.innerHTML` for this makes no sense to begin with. `innerHTML` is the content _between_ the tags. Attributes are not between the tags, they are part of the opening tag. – CBroe Dec 02 '21 at 08:30

1 Answers1

0

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) ?>");