我已经使用javascript使用下拉菜单创建了一个选择输入字段,因此用户可以添加多个条目,但是javascript无法提取用于创建选择下拉列表值的php函数。我看不到为什么下拉菜单不起作用。如果我使用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函数
$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 ;
}
答案 0 :(得分:0)
尝试将PHP变量放入Javascript变量内,然后附加该JS变量,如下所示:
<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>
答案 1 :(得分:0)
仅echo
个结果。你忘了! :-P
<?php categoryDropDown($categories); ?>
到
<?= categoryDropDown($categories); ?>