简体   繁体   中英

Add form fields dynamically with php

Referring to this post. Add form fields dynamically populated dropdown list with php I have used his code but will modify it to fit my needs since I pretty much nothing about javascript. I have everything working except when you press the + button it never creates more input boxes. Any help would be great.

This my php file

<?php
session_start();
require_once("dbconfig.php");
?>
<html>
<head>
<script type="text/javascript" src="addfish.js"></script>
</head>
<form id="form1" name="form1" method="post" action="results.php">
 <div id="itemRows">
    <select name="species">
            <option value="">Select Species</option>';
            <?php $stmt = $dbc->prepare("SELECT species FROM fish");
            $stmt->execute();

while($speciesq = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo "<option value=\"" . $speciesq['species'] ."\">" . $speciesq['species'] ."</option>";
}
?> 
</select>
    Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />     
    </div></form>


</html>

My addfish.js file

var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
;
function addRow(frm) {
    rowNum ++;
    $.post("getlist.php", function(data) {
        var frm = document.getElementById('form1')
        for (var i=0; i<data.length; i++) {
            ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
        } 
        var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.speciesnumber1.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.speciesweight.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
        jQuery('#itemRows').append(row);
        frm.add_qty.value = '';
        frm.add_name.value = '';
    }, "json");
}
function removeRow(rnum) {
    jQuery('#rowNum'+rnum).remove();
}

This is my getlist.php

<?php
session_start();
include("dbconfig.php");
$stmt = $dbc->prepare("SELECT species FROM fish");
$stmt->execute();
$result = array();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
   $result[] = array(
    'value' => $rows['species'],
    );
}
echo json_encode($result);
?>

Your code is using jQuery, but I don't see where you include this library. Try to put this code before include addfish.js in header :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

If you need to add rows with this fields dynamically I suggest you make a row which is the original row:

<div class="rows" data-rows="1">
    <div class="row row-first">
       <select name="row[0][select_name]">
          <option value="1">Some value</option>
       </select>

       <input type="text" name="row[0][text_name]" />
    </div>
</div>

and the javascript

<script type="text/javascript">
    $('#add_row').on('click', function(){
        var row = $('.row-first').clone(); // Clone the first row
        var rows = parseInt($('.rows').attr('data-rows'));
        rows++;
        $('.rows').attr('data-rows', rows);

        row.removeClass('row-first'); // Prevent multiple rows cloning

        $(row).find('[name]').each(function(){
              var name = $(this).attr('name');
              name = name.replace(/\[[0-9+]\]/, '[' + rows + ']');
              $(this).attr('name', name);
              $(this).val("").change(); // Null the select
        });

       $('.rows').append(row);
    });
</script>

So what you do is clone the first row and remove the class, which you search. Increment the rows count and replace all names in you row with the new row number eg row[0][name] becomes row[1][name], and append the row.

Also when you edit the rows you MUST put set the data-rows to the exact number. You can do it like count($myRows) . And when you write the remove row function DO NOT REMOVE the first row.

Hope it hepls.

// You can use this 

var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+$($(frm).find('input[name="speciesnumber1"]')[0]).val()+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
            jQuery('#itemRows').append(row);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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