如何使用包含php的javascript添加表单元素?

时间:2014-02-16 16:56:40

标签: javascript php

这是我的代码:

Category:
<select name='category'>
<?php
    $query = "SELECT * FROM `categories`";
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_row($result)) {
    echo "<option name={$row[0]} value={$row[1]}>{$row[1]}</option>";
}} ?>
</select> <br><br>

Quantity:
<input type='text' name='quantity' onkeypress="return isNumberKey(event)"><br><br>

Price:
<input type='text' name='price' onkeypress="return isNumberKey(event)"><br><br>
<a href='#' onclick="addformfield()">Insert another item</a>
<input type='submit' value='Submit'>

当用户点击插入另一个项目时,我想再次使用Javascript添加类别,数量和价格。

请帮忙。

1 个答案:

答案 0 :(得分:0)

只需一个快速解决方案,无需AJAX请求。

<?php
$categories = array();
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_row($result)) {
        $categories[$row[0]] = $row[1];
    }
}
?>

<div id="groups"></div>
<a href='#' id="insert-another-item">Insert another item</a>

<script>    
var categories = <?= json_encode($categories) ?>,
    groupId = 0;

$(function() {
    insertGroup();
    $('#insert-another-item').on('click', function() {
        insertGroup();
        return false;
    });     
}); 

function insertGroup() {
    group = '<div class="group">' 
              + '<select name="groups[' + groupId + '][category]"></select>'
              + '<input type="text" name="groups[' + groupId + '][quantity]">'
              + '<input type="text" name="groups[' + groupId + '][price]">'
          + '</div>';

    $('#groups').append(group);

    $.each(categories, function(key, value) {
        $('select[name="groups[' + groupId + '][category]"]').append('<option value="' + key + '">' + value + '</option>');
    });

    groupId++;
}