Dropdown populated with database data that adds on button click - javascript

I am confused how to populate my dropdown that adds on button click with database values . I used jQuery to do the adding function of dropdown on button click. but it seems like i cant populate the options of the select tag inside my jQuery with database values. Please help me out...
This is my php page
<?php include("connect.php");
$smt = $conn->prepare('select CompanyName From Company');
$smt->execute();
$data = $smt->fetchAll();
?>
<div class="form-group" id='TextBoxesGroup'>
<label for="layer" class="col-sm-3 control-label">Layer</label>
<div id="TextBoxDiv1" class="col-sm-6">
<select class="form-control" id='textbox1' name="company" placeholder="Company" >
<?php foreach ($data as $row): ?>
<option><?=$row["CompanyName"]?></option>
<?php endforeach ?>
</select>
</div><hr/>
</div>
<div class="form-group" >
<div class="col-md-9 text-right">
<input type='button' class="btn btn-default" value='Add +' id='addButton'>
</div>
</div>
The jQuery code used to add dropdown on button click is:
EDIT:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 Layers allowed");
return false;
}
var companies = [<?php echo "'".join("','",$data)."'";?>];
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div class="form-group" id="TextBoxesGroup"><label class="col-sm-3 control-label">Layer '+ counter + ' : </label>' +' <div id="TextBoxDiv1" class="col-sm-6"><select class="form-control" name="textbox' + counter + '" id="textbox' + counter + '" name="company" placeholder="Company">');
$.each(companies, function(key, value){
newTextBoxDiv.append('<option>'+value+'</option>');
});
newTextBoxDiv.append('</select> </div></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
But the output shows like this:
Thanks

Well, you need to echo out the value of $row['companyName'] (the one inside your foreach loop)
Another implementation would be... say you have an array of values in your PHP.
$data = array("company A", "company B", "company C");
And the javascript...
<script>
var companies = [ <?php echo "'". join("','", $data) . "'";?> ];
//This generates : ['company A', 'company B', 'company c'];
function insertOptions()
{
$.each(companies, function(key, value){
$("#IDofSelectTag").append("<option>"+value+"</option>");
});
}
</script>

Related

adding multiple inputfield using javascript in php not working

i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />

Populate multiple form fields from foreach statement

I'm trying to populate multiple form fields from a generated button in a foreach statement. I don't have a vast knowledge of JS so I don't know if I'm just not thinking of a certain function or not.
I have the following code and I'm able to get title to populate in the form but I have no clue where to start for populating content as well based of the same button. ex: one button will load a specific title and content value while another edit button will load another specific title and content value.
//Announcement table select
$sql = "SELECT * FROM `announcements` ORDER BY `startDate` DESC"; //I want to see all existing announcements from database
$announcement = $dbConnect->query($sql);//execute query
$a = 0;
?>
<script type="text/javascript">
function changeText(title, content){
document.getElementById('title').value = title.id;
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].');" value="Edit">';
echo '<p id="'.$y[$a].'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
</div>
</div>
</div> <!--m4 ends here-->
<div class="col m8 s8"> <!--m8 starts here-->
<div class="titleboxmargin grey" style="width:100%;">
<div class="bar yellow"></div>
<img class="boxicon" src="../images/announcementsicon.svg">
<h3 class="title">Announcements</h3>
</div>
<div class="col yellow-light"> <!--Announcement Form Starts-->
<form action="includes/postAnnouncement.php" method="post">
<ul class="yellow-form">
<li class="textfield-container">
<label for="text" class="textlabelblack">Title:</label>
<input id="title" name= "title" type="text" placeholder="Title of My Announcement">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Start Date:</label>
<input type="date" id="startDate" name="startDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">End Date:</label>
<input type="date" id="endDate" name="endDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Announcement:</label>
<textarea id="content" name="content" rows="7"></textarea>
</li>
<li class="textfield-container">
<div class="leftsidebutton">
<input type="submit" class="button" style="width:auto; padding:5px; border:0;" name="register" value="Submit the form"/><!--Action: Attempts to Redirect to postAnnouncement.php-->
</div>
</li>
</ul>
</form>
The following code works
Edit:
<script type="text/javascript">
function changeText(title, content){
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
document.getElementById('title').value = document.getElementById(title).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$tile = $row["announcementID"] * 2;
$cont = $row["announcementID"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$tile.'" data-content="'.$row["title"].'" type=button class=test onclick="changeText(id, '.$cont.');" value="Edit">';
echo '<p id="'.$cont.'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
You could add a second parameter to your onclick handler:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, content){
document.getElementById('title').value = elem.id;
/*
* Here we get the value of the hidden content by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = document.getElementById(content).value;
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].'); startDate('.$y[$a].'); " value="Edit">';
echo '<p style="display:hidden;" id="'.$y[$a].'" ></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
EDIT:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, contentID){
var contentElem = document.getElementById(contentID);
document.getElementById('title').value = elem.getAttribute('data-title');
/*
* Get the value of the hidden content's data attribute by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = contentElem.getAttribute('data-content');
}
</script>
<?php
// Let's get $index as well
foreach ($announcement as $index => $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
// Not sure if I'm escaping quotes correctly on this line:
echo '<input id="title'.$index.'" data-title="'.$x[$a].'" type=button class=test onclick="changeText(this, \"content'.$index.'\"); startDate('.$y[$a].'); " value="Edit">';
// Generate a unique id that we can reference
// and add `data-content` attribute
echo '<p style="display:hidden;" id="content'.$index.'" data-content="'.$y[$a].'"></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
I am not sure what your title and content values are, but I suspect they are not valid HTML element IDs. I think it would be better to avoid using the DOM as a data store and instead create a JSON representation of your announcement table in your script. My PHP is a little rusty, but it should be something similar to:
<script>
var rows = <?php echo json_encode($announcement); ?>;
</script>
Hopefully this will produce something like the following:
var rows = [
{
"title": "Title One",
"content": "Content One"
},
{
"title": "Title Two",
"content": "Content Two"
}
];
This way, our changeText function need only accept a row index as parameter:
function changeText (index) {
document.getElementById('title').value = rows[index].title;
document.getElementById('content').value = rows[index].content;
}
All that is left is to pass the row index where we call changeText:
<?php foreach ($announcement as $index => $row) { ?>
<!-- echo your HTML markup here. -->
<button onclick="changeText(<?php echo $index; ?>);">Edit</button>
<?php } ?>

Updating multiple field with javascript

I have next form :
<?php
echo "<form action=\"test.php\" method=\"post\">";
$rez = mysqli_query($kon, "SELECT * FROM shops");
while($red = mysqli_fetch_assoc($rez)){
$niz = array(
array($red["id"],$red["naam"])
);
echo "<div class=\"col-xs-12 col-sm-12\">
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces();\"/>
</div>
</div>
<div class=\"col-sm-10 col-xs-8\">
Informacije
</div>
</div>
<div class=\"footer\" style=\"position: fixed;bottom: 0;width: 100%;left:0;\">
<span class=\"glyphicon glyphicon-chevron-left\"></span> Niets toevoegen
<button class=\"col-xs-6 col-sm-6 btn btn-danger\" type=\"submit\" name=\"btnNaruci\" id=\"btnNaruci\">
Leg in winkelmand <span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span>
</button>
</div>";
}
echo "</form>";
?>
I want to update this hidden field for every result. I have now 5 results but if i increase quantity, the hidden field get value only if i increase quantity of first result.
I have onChange by the quantity input field and then in javascript i get the value of that field and add it to the value of the hidden field, but the value of the hidden field is changed only for the first result in while loop..
Thanks in advance...
I would need the body of your proces() function to say for sure, but I think you reference your input field by id, all 5 input fields have the same id. Only first gets updated and that's the problem. Either give different ids (by adding count) or reference by class. That would work, however having same id for multiple fields is not a good idea.
Post the body of the function and I can give more detailed help.
Ok, so they do have the same id. You could go by class to update them like this:
var quan = document.getElementById("quan").value;
var hiddenfields = document.getElementsByClassName('hidd');
for (var i = 0; i < hiddenfields.length; ++i) {
var item = hiddenfields[i];
item.value = quan;
}
Or if it's ok tu use JQuery:
var quan = $("#quan").val();
$( ".hidd" ).val(quan);
Based on your comment:
I see. I think simplest would be to do the following:
In your php code add id (concat as string), and add it to the call of your updating function
This might not compile, but gives you the idea:
$i = 1;
while($red = mysqli_fetch_assoc($rez)){
// ...
echo "<div class=\"col-xs-12 col-sm-12\">
// ...
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd".$i."\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan".$i."\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces('quan".$i."', 'txtHidd".$i."');\"/>
</div>
</div>
// ...
</div>";
$i++;
In javascript the updating function would use the parameter
function proces(quanID, hiddenID) {
var quan = document.getElementById(quanID).value;
document.getElementById(hiddenID).value = quan;
}
EDIT AGAIN
I found that the /" at the id fields were in wrong position.
Updated sample code. Basically your html output is supposed to look like this (I didn't include name, as it doesn't matter, now we are only looking at id-s):
...
<input class="hidd" type="hidden" name="xxxxx" id="txtHidd1" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan1" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan1', 'txtHidd1');"/>
</div>
</div>
...
...
<input class="hidd" type="hidden" name="xxxxxx" id="txtHidd2" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan2" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan2', 'txtHidd2');"/>
</div>
</div>
...
Looking at the id-s and the call of the function. If it's like that, the javascript update part will work perfectly.
That is my test.php page
<?php
session_start();
include("config.php");
global $kon;
ob_start();
print_r($_POST["txtHidd"]);
foreach ($_POST["txtHidd"] as $id => $id_prod) {
foreach ($id_prod as $kolicina) {
echo "<br />Id : {$id} and quantity : {$kolicina}<br />";
}
}
ob_flush();
?>
And result tha i get when i hit a post is next :
Array ( [17] => Array ( [kolicina] => ) [18] => Array ( [kolicina] => ) [19] => Array ( [kolicina] => ) [20] => Array ( [kolicina] => ) )
Id : 17 and quantity :
Id : 18 and quantity :
Id : 19 and quantity :
Id : 20 and quantity :

Ajax script breaking at callback

I have this script which works once but I can't seem to replicate it inside the same document.
The JQuery:
$("document").ready(function() {
//This first instance works
if($("#add-menu").length) {
$("#add-menu").change(function() {
var datum = 'shortname=' + $(this).val() + '&table=projects';
$.post('proj_query.php', datum, response);
function response(data) {
var jSON = $.parseJSON(data);
$("label:contains('Title:') + input:first").val(jSON.title);
$("label:contains('Medium:') + input:first").val(jSON.medium);
$("label:contains('Dimmensions:') + input:first").val(jSON.description);
$("label:contains('Work Blurb:') + textarea:first").val(jSON.blurb);
}
});
}
//This one doesn't work
if($("#id-blurb").length) {
$("#id-blurb a").click(function() {
if($("#edit-menu").val().length) {
var datum = 'shortname=' + $("#edit-menu").val() + '&table=projects';
$.post('proj_query.php', datum, responseB);
function responseB(data) {
var jSON = $.parseJSON(data);
$("#id-blurb textarea").val(jSON.blurb);
}
}
});
}
});
When I test by running alerts, I get alerts right up until I add the callback function (the one called 'responseB'). Then it stops generating them. So it seems it's finding the document, and it seems to be accepting the data, but that's about it. After that nothing happens.
proj_query.php looks like this:
<?php
require_once ('../functions/functions.php');
connectDB('../functions/login.php');
require_once("session.php");
if(isset($_POST['shortname'])) {
$shortname = $_POST['shortname'];
$table = $_POST['table'];
$query = "SELECT title, medium, description, blurb FROM $table WHERE shortname='$shortname'";
$result = mysql_query($query);
$results = mysql_fetch_array($result, MYSQL_ASSOC);
print_r(json_encode($results));
}
?>
The HTML is this (but you may not need that):
<div id="change" class="grid_4">
<h3>Edit a Project</h3>
<form method="post" action="index.php" name="editform" onsubmit="return validateEdit(this);">
<input type="hidden" name="edit" value="yes" />
<div class="field_container"><label>Project Name:</label>
<select id="edit-menu" name="shortname">
<option value="">Select a Project...</option>
<?php //For creating the dropdown menu
$query = "SELECT * FROM projects ORDER BY title ASC";
$result = mysql_query($query);
if (!$result) die ("Server says: <br/>Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++) {
$results[] = mysql_fetch_array($result, MYSQL_ASSOC);
$option = $results[$i]['title'];
$value = $results[$i]['shortname'];
echo "<option value=\"$value\">" . $option . "</option>\n";
}
?>
</select>
</div>
<div class="field_container"><label>Title:</label><input type="text" name="title" maxlength="128"/></div>
<div class="field_container"><label>Date:</label><input type="date" name="date" /></div>
<div class="field_container"><label>Medium:</label><input type="text" name="medium" maxlength="256"/></div>
<div class="field_container"><label>Dimmensions:</label><input type="text" name="description" maxlength="64"/></div>
<div class="field_container"><label>Area:</label><input type="text" name="area" maxlength="16"/></div>
<div class="field_container"><label>Video Number:</label><input type="text" name="video" maxlength="64"/></div>
<div class="field_container"><label>New Shortname:</label><input type="text" name="new_shortname" maxlength="16"/></div>
<div class="field_container" id="id-blurb"><label><a title="Click for old content">Work Blurb:</a></label><textarea class="blurb" name="blurb" rows="5" ></textarea></div>
<input class="submit" type="submit" value="Edit Project" />
</form>
</div>
Banging my head on this one...

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 e.g. 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);

Categories