Add form fields dynamically with php - javascript

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);

Related

Get values from a dynamic drop-down list and show them in a dynamic text box

I have a table with dynamically generated rows, the first row is not dynamic and I want to show and print the values according to the choice made by the user from the dynamic dropdown list, I have jQuery and PHP code that only works in the first non-dynamic row and does not work in the rest of the new dynamic rows and I want to make the feature work In each new dynamic row that is generated, only the value associated with the user's selection appears (for example: the invoice system drop-down list contains the name of the product, and the price of the product appears in another text box when selecting any product from the drop-down list)
The problem is shown in the picture
php code:
`
<select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
jquery code:
$('.select_acount').on('change', function() {
$(this).closest('tr').find('.mount').val($(this).val());
});
Dynamic code generation using JaQuery"
var data = <?php echo json_encode($data); ?>;
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required></td><td class="td2"><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash" ></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
Since you are using jQuery, I would recommend using a delegated event handler approach and add your event to the table/container element of your dynamic rows, so your event listener declaration would look like this:
$('#dynamicAddRemove').on('change', '.select_acount', function() {
$(this).closest('tr').find('.mount').val($(this).val());
});
This way your event will fire for every newly added row. More information on event delegation: jQuery-event-delegation

Genereting 'n' html inputs based on database variable

My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```
Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.

Reselect first option of a select dropdown menu repeatedly after storing value

I have looked at the options for reselecting the first option of a select dropdown and incorporated the code in my code. It works the first time I press an "addRow" button, but not the 2nd or subsequent "addRow"s. the relevant code is
$("#selectBox option:first-child").attr("selected", "selected");
The full codes is as follows:
<?php
$db = mysqli_connect("localhost",$username,$password,$database);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql="SELECT part_id, part_code, part_descr FROM part";
$result = $db->query($sql);
if (!$result){
echo "no record found in the parts table";
}
$option = '<option value = "">select a part</option>';
while ($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['part_id'].'">'.$row['part_code'].' '.$row['part_descr'].$row['part_id'].'</option>';
}
?>
<html>
<head>
<title>Test Drop Down Menu</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body >
<form id="form2" name="form2" method="post" enctype="multipart/form-data">
<div id="itemRows">
Quantity: <input type="text" name="add_qty" size="4" />
Part: <select id="selectBox" name="selectBox"
data-placeholder="Choose a Part..."
style="width:350px;" class="chosen-select"
onchange="storePartId();"
>
<?php echo $option; ?>
</select>
<input type="hidden" name="add_part_id" id='add_part_id' />
<input type="hidden" name="add_part_descr" id="add_part_descr" />
<input onClick="addRow(this.form);" type="button" value="Add row" />
(not saved until "Add row" clicked)
</div>
<input type="submit" name="next" value="submit report">
</form>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">\n\
Quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'" required> \n\
Part: <input type="text" name="part_descr[]" value="'+frm.add_part_descr.value+'" required> \n\
<input type="hidden" name="part_id[]" value="'+frm.add_part_id.value+'" required> \n\
<input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_part_descr.value = '';
frm.add_part_id.value = '';
$("#selectBox option:first-child").attr("selected", "selected");
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
function storePartId() {
var selectBox = document.getElementById("selectBox");
selectedValue = selectBox.options[selectBox.selectedIndex].value;
selectedText = selectBox.options[selectBox.selectedIndex].text;
if (selectedValue !== null){
document.getElementById("add_part_id").value = selectedValue;
document.getElementById("add_part_descr").value = selectedText;
} else {
document.getElementById("add_part_id").value = null;
document.getElementById("add_part_descr").value = null;
}
}
</script>
</body>
</html>
I want the "selectBox" to show the text "select a part" after the "addRow" button has been clicked.It does the first time it is clicked but not subsequently. Any ideas?
You can set selectedIndex to 0 to select first option.
document.getElementById('selectBox').selectedIndex = 0

How do you assign variables or work with numbers in forms created by php loops?

I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>

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...

Categories