简体   繁体   English

将HTML选择框附加到使用MYSQL查询结果填充的页面

[英]Appending html select box to page that is populated with MYSQL query results

Normally when creating dynamically populated drop-downs I'd use a simple foreach loop as below to get the data: 通常,在创建动态填充的下拉菜单时,我将使用以下简单的foreach循环来获取数据:

<select name="region" id="region" tabindex="1">
   <option value="">Select a Course</option>
   <?php foreach ( $courses as $course ) : ?>
   <option value="<?php echo $course->coursename; ?>"><?php echo $course->coursename; ?></option>
   <?php endforeach; ?>
</select>

*where $courses = select("SELECT * FROM courses"); 

etc etc

What I'm not sure is possible is to use this in anything like its current form inside a javascript function such as the one below that I've been using on some forms to append additional input fields per the requirements of the user. 我不确定是否可以在javascript函数内以当前形式使用该函数,例如下面我在某些表单上一直使用的函数,以根据用户需求附加其他输入字段。 This works fine for a text input, for example (and as below I can use it if I type out each input option manually) but I'm not at all sure as to the best way to recreate the PHP/mySQL example above where javascript doesn't get in the way. 例如,这对于文本输入来说效果很好(并且如下所示,如果我手动键入每个输入选项,我可以使用它),但是我不确定在上面使用javascript重新创建PHP / mySQL示例的最佳方法不会妨碍您。 I've tried to look into whether this could easily be done with AJAX but have not been able to find any examples of what I'm trying to do. 我试图研究使用AJAX是否可以轻松完成此操作,但是还无法找到我正在尝试执行的操作的任何示例。

<script type="text/javascript">
var count = 0;
$(function(){
    $('p#add_field').click(function(){
        count += 1;
        $('#container').append(
                '<h4>Link #' + count + '</h4>&nbsp' 
                +'<select id="field_' + count + '" name="fields[]">' + '<option>Select a Course</option>'+'</select>');

    });
});
</script>

Many thanks for any advice about the best way to do this. 非常感谢您提供有关最佳方法的建议。

Update - I eventually managed to answer my own question - solution as per the code below. 更新-我最终设法回答了自己的问题-根据以下代码的解决方案。

<script type="text/javascript">
var count = 0;
$(function(){
    $('p#add_field').click(function(){
        count += 1;
        $('#container2').append(
                '<strong>Golf Course ' + count + '</strong>&nbsp&nbsp&nbsp' 
                +'<select id="field_' + count + '" name="fields[]">' + "<?php foreach ( $courses as $course ) { $name = $course->coursename; ?>"+"<?php echo '<option value=\''.htmlspecialchars($name).'\'>'.$name.'</option>'; ?>"+"<?php } ?>"+'</select><br />')

    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM