I'm hugely struggling with a javascript form creation loop based on a database. The difficulty lays in the array which is multidimensional.
The array from the database:
Array (
[0] => Array (
[Diplome] => Master
[Institut] => IAE
)
[1] => Array (
[Diplome] => Licence
[Institut] => Université
)
)
Javascript trial:
<?php $array = "array from db above"; ?>
<script type="text/javascript">
var arr = <?php echo json_encode($tr, JSON_PRETTY_PRINT) ?>;
var length = arr.length;
function createForm(){
for (i in arr) {
form = document.getElementById("formed");
var x = arr[i].Diplome;
var y = arr[i].Institut;
var input = document.createElement('input');
input.setAttribute('value', x)
var input2 = document.createElement('input');
input2.setAttribute('value', y)
form.appendChild(input);
form.appendChild(input2);
}
}
</script>
Expected result:
<form id="formed">
<div>
<input type="text" name="diploma" placeholder="Diplôme" value="Master">
<input type="text" name="institut" placeholder="Institut" value="IAE">
</div>
<div>
<input type="text" name="diploma" placeholder="Diplôme" value="Master">
<input type="text" name="institut" placeholder="Institut" value="IAE">
</div>
</form>
Any idea ? Thanks a lot from France !
var arr = <?php echo json_encode($tr, JSON_PRETTY_PRINT) ?>;
is returning a string
. So you need to JSON.parse(arr)
to iterate over it using your createForm
function.
// This is what the return value of json_encode in PHP will look like var arr = `[ { "Diplome": "Master", "Institut": "IAE" }, { "Diplome": "Licence", "Institut": "Universit\é" } ]`; var arr = JSON.parse(arr) var length = arr.length; function createForm(){ for (i in arr) { form = document.getElementById("formed"); var x = arr[i].Diplome; var y = arr[i].Institut; var input = document.createElement('input'); input.setAttribute('value', x) var input2 = document.createElement('input'); input2.setAttribute('value', y) form.appendChild(input); form.appendChild(input2); } } createForm()
<form id="formed"></form>
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.