问题
I have created a select input field with dropdown using javascript so user can add multiple entries but the javascript does not pull in the php function used to create the select dropdown values. I am unable to see why the dropdown does not work. The dropdown does work correctly if i create the input field using php.
Javascript
<script>
var count = 0;
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<label for="category" class="col-sm-4 control-label">Business Category:</label>';
html += '<div class="col-sm-8">';
html += '<select name="category" class="form-control">';
html += '<option value=""></option><?php categoryDropDown($categories); ?>';
html += '</select>';
html += '<button type="button" name="remove" class="w3-button w3-red w3-round w3-tiny remove" title="Remove this category"></button>';
html += '</div>';
$('#category').append(html) ;
count++;
});
$(document).on('click', '.remove', function(){
$(this).closest('div').remove();
count--;
});
});</script>
PHP Function
$categories = $db->select("categories", "deleted = 0 ORDER BY name");
function categoryDropDown($categories)
{
foreach($categories as $p)
{
$output3 .= '<option value="' . $p['id'] . '">' . stripslashes($p['name']) . '</option>';
}
return $output3 ;
}
回答1:
Try putting the PHP variable inside a Javascript variable and then append that JS variable like below:
<script>
var count = 0;
$(document).ready(function(){
$(document).on('click', '.add', function(){
var options = '<?php echo categoryDropDown($categories); ?>';
var html = '';
html += '<label for="category" class="col-sm-4 control-label">Business Category:</label>';
html += '<div class="col-sm-8">';
html += '<select name="category" class="form-control">';
html += '<option value=""></option>';
html += options;
html += '</select>';
html += '<button type="button" name="remove" class="w3-button w3-red w3-round w3-tiny remove" title="Remove this category"></button>';
html += '</div>';
$('#category').append(html) ;
count++;
});
$(document).on('click', '.remove', function(){
$(this).closest('div').remove();
count--;
});
});
</script>
回答2:
Just echo
the result. You forgot! :-P
<?php categoryDropDown($categories); ?>
to
<?= categoryDropDown($categories); ?>
来源:https://stackoverflow.com/questions/50948170/dynamically-created-select-input-using-javascript-not-showing-dropdown