I am trying to make a form to register a product details. Everytime user click the 'Add' button, I wanted to add more input fields for the user to key in their products.
The code looks like this.
<form id="myform">
<label>Product Name</label>
<input type="text" name="productname0" value=">
<?= !empty($data["error_productname0"]) ? "<p class=\"help is-danger\">". $data["error_productname0"] ."</p>": ""; ?>
</form>
<script>
$("button.add").click(function(){
let inputNumber = $("#myform").children("input").length;
$("#myform").append(returnNewInput(inputNumber));
});
function returnNewInput(n) {
return `<input type="text" name="productname${n}" value="">
<?= !empty($data["error_productname${n}"]) ? "<p class="help is-danger">$data["error_productname${n}"]</p>": ""; ?>`;
}
</script>
But I had problem using the inputNumber variable. I cannot pass it into the returnNewInput function. The error says,
Notice: Undefined variable: n
Is it impossible to implement PHP code such as empty, isset etc in Javascript code? I thought PHP code is just a chunk of string in Javascript.