Dynamically created select input using javascript, not showing dropdown

谁说胖子不能爱 提交于 2021-01-29 10:39:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!