Jquery autocomplete with dynamic input fields not working - javascript

I have created multiple dynamic input fields but I want to add jquery autocomplete with all the input fields but problem is this is only working with only first input field not with every dynamically added input fields. I have tried many SO answers but none of them are working for me or May be I could not understand.
Someone will help me with this problem.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic add/remove input fields in PHP Jquery AJAX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="card text-center" style="margin-bottom:50px;">
<h1>Dynamic Add/Remove input fields in PHP Jquery AJAX</h1>
</div>
<div class="container">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group">
<form name="add_name" id="add_name">
<table class="table table-bordered table-hover" id="dynamic_field">
<tr>
<td>
<div class="ui-widget">
<td><input type="text" name="uname" placeholder="Enter your Name" class="form-control name_list" /></td>
</div>
<td><input type="text" name="name[]" id="automplete-2" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
<td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>
</tr>
</table>
<input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
<?php
$js_array = json_encode($name);
echo "var availableTutorials = ". $js_array . ";\n";
?>
$("#automplete-2").autocomplete({
source: availableTutorials,
autoFocus: true
});
var i = 1;
$("#add").click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="automplete-2" name="name[]" placeholder="Enter your Name" class="form-control name_list"/></td><td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("#submit").on('click',function(){
var formdata = $("#add_name").serialize();
$.ajax({
url :"action.php",
type :"POST",
data :formdata,
cache :false,
success:function(result){
alert(result);
$("#add_name")[0].reset();
}
});
});
});
</script>

So finally I read the code again and i find this solution and it's working now.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dynamic add/remove input fields in PHP Jquery AJAX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="card text-center" style="margin-bottom:50px;">
<h1>Dynamic Add/Remove input fields in PHP Jquery AJAX</h1>
</div>
<div class="container">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group">
<form name="add_name" id="add_name">
<table class="table table-bordered table-hover" id="dynamic_field">
<tr>
<td>
<div class="ui-widget">
<td><input type="text" name="uname" placeholder="Enter your Name" class="form-control name_list" /></td>
</div>
<td><input type="text" name="name[]" id="automplete-2" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
<td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>
</tr>
</table>
<input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var i = 1;
$("#add").click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="automplete-2" name="name[]" placeholder="Enter your Name" class="form-control name_list"/></td><td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
$('#dynamic_field').find('input[name^="name"]').autocomplete({
source: availableTutorials
});
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$("#submit").on('click',function(){
var formdata = $("#add_name").serialize();
$.ajax({
url :"action.php",
type :"POST",
data :formdata,
cache :false,
success:function(result){
alert(result);
$("#add_name")[0].reset();
}
});
});
<?php
$js_array = json_encode($name);
echo "var availableTutorials = ". $js_array . ";\n";
?>
// $("#dynamic_field").autocomplete({
// source: availableTutorials,
// autoFocus: true
// });
$("input[name^='name']").autocomplete({
source: availableTutorials
});
});
</script>

Related

How to remove Jodi Elements like '11','22','33' upto 100 from dynamic html table using checkbox & Javascript?

I have this table with some dependent information that uses Javascript and there is an Add and check button to insert elements dynamically in the table and a delete button for each row to delete. When I click the "add and check" button, a set of rows gets added to the table.
Here is what I have:
Javascript and HTML Code...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="robots" content="index,follow" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="contanier">
<div class="row">
<div class="col-sm-6" style="padding:20px; border-right:1px solid #000;">
<div class="form-group">
<label for="email">First Number</label>
<input type="number" name="number1" class="form-control" id="number1" min="1">
</div>
<div class="form-group">
<label for="pwd">Second Number</label>
<input type="number" name="number2" class="form-control" id="number2" min="1" >
</div>
<div class="form-group">
<label for="pwd">Amount</label>
<input type="number" name="amount" class="form-control" id="amount" min="1" >
</div>
<button type="button" id="addbtn" class="btn btn-primary">Add and Check</button>
</div>
<div class="col-sm-6">
<h4 class="text-center">Result</h4>
<div id="main_box">
<div>
<input type="checkbox" name="style" value="classical" onchange="add()">
<label>Remove Doublets</label></div>
<table id="result" class="table table-striped">
<tbody class="tbody">
<tr>
<th>Number</th><th>Amount</th><th>Action</th>
</tr>
</tbody>
</table>
<h3>Total Amount:<span id="totl">0</span></h3>
<form action="" method="post" >
<div id="inputs">
</div>
<input type="hidden" name="user_id" value="22">
<input type="hidden" name="game_id" value="111">
<input type="submit" name="save_data" class=" btn btn-danger" value="SAVE" >
</form>
</div>
</div>
</div>
</div>
<script>
var indx=1;
var total_amount = 0;
$("#addbtn").click(function(){
var number = jQuery('#number1').val();
var number2 = jQuery('#number2').val();;
var amount = parseInt(jQuery('#amount').val());
if(number!="" && number2!="" && amount!="")
{
const arr_num_first = Array.from(String(number));
const arr_num_second = Array.from(String(number2));
for (let numOf_f_array of arr_num_first)
{
for (let numOf_s_array of arr_num_second)
{
total_amount = total_amount+amount;
var new_number = numOf_f_array+""+numOf_s_array;
$('.tbody').append("<tr class='input"+indx+"' ><td>"+new_number+"</td><td>"+amount+"</td><td><button class='dlt' data-am='"+amount+"' data-c='input"+indx+"'>X</button></td><tr>");
$('#inputs').append("<input type='hidden' name='num[]' value='"+new_number+"' class='input"+indx+"' >");
$('#inputs').append("<input type='hidden' name='amount[]' value='"+amount+"' class='input"+indx+"' >");
indx++;
}
}
$('#totl').html(total_amount);
}else{ alert('Fill all fields')}
});
$( "#main_box" ).on( "click",".dlt", function() {
var classname = $(this).attr('data-c');
var dlt_amount = parseInt($(this).attr('data-am'));
var new_total = total_amount-dlt_amount;
total_amount = new_total;
$('#totl').html(new_total);
$('.'+classname).remove();
});
</script>
</body>
</html>

JQuery - can not set data to firebase

for some reason, i cannot set data to firebase realtime database.
the function works as intended, values are stored in the vars, and no error is presented...the data just won't upload to the firebase realtime database.
the js code:
$(document).ready(function(){
document.getElementById('submitEmplyee').onclick = function()
{
idNumberVal = document.getElementById('IDNum').value;
nameVal = document.getElementById('Name').value;
addressVal = document.getElementById('Address').value;
telephoneVal = document.getElementById('telephone').value;
//Ready();
firebase.database().ref('employe/' + nameVal).set({
EmplyeeID: idNumberVal,
NameOfEmp: nameVal,
AddressOfEmp: addressVal,
TelephoneOfEmp: telephoneVal
});
//alert("New HighScore !!!");
}
the sources:
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-app.js"></script>
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-auth.js"></script>
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="logic.js"></script>
full HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>David Frucht CRUD app</title>
</head>
<body>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<h1>Emplyee Information</h1>
<button id="newEmployeBtn" class="btn btn-primary btn-block">New Emplyee</button><br /><br />
<form id="newForm">
<div class="form-group row">
<label for="IDNum" class="col-sm-2 col-form-label">ID Number</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="IDNum" placeholder="ID Number">
</div>
</div>
<div class="form-group row">
<label for="Name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Name" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="Address" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Address" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone Number</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="telephone" placeholder="Telephone Number">
</div>
</div>
<button id="submitEmplyee" type="submit" class="btn btn-primary">Add to DB</button>
</form>
<table id="emplyesTable" class="table table-bordered table-hover">
<thead>
<th>Emplyee ID</th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
<!-- <th>DB ID</th>
<th>Controls</th>-->
</thead>
<tbody id="employeBody"></tbody>
</table>
</div>
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-app.js"></script>
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-auth.js"></script>
<script src = "https://www.gstatic.com/firebasejs/8.2.4/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="logic.js"></script>
</body>
I didn't test your code, but the cause of your problem is most probably the fact that your form is submitted before the Firebase set() method is triggered.
As a matter of fact, you declare your button as follows:
<button id="submitEmplyee" type="submit" class="btn btn-primary">Add to DB</button>
As detailed in the W3 specification on button types, "the missing value default is the Submit Button state" and "if the type attribute is in the Submit Button state, the element is specifically a submit button".
So, if you add a button type to your button, as follows, it should solve your problem.
<button id="submitEmplyee" type="button" class="btn btn-primary">Add to DB</button>

best approach in adding a comma to a number like 123,456.78 in jquery

found this solution in this solution
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
in this link add commas to a number in jQuery
I am trying to apply it in my project. it works in one column but it doesn't work in price and sub total
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
var tot = totNumber.toFixed(2);
tot = commaSeparateNumber(totNumber);
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
subtotal += parseFloat($(this).val());
});
$('#subtotal').val(commaSeparateNumber(subtotal));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>
Thank you so much in advance!
The problem is that parseFloat fails to correctly parse the value from the total cost textbox because it contains one or more ,. You need to remove the , from the string before parsing to float. You can remove any ,'s by calling .replace(/,/g,'') on the textbox value in the calculateSubTotal function.
It seems that for some values the function commaSeparateNumber doesn't work as expected. I removed it from the snippet below and replaced it with toLocaleString() which takes parameters for locale and minimum/maximum fraction digits .toLocalString("en-US", { maximumFractionDigits: 2}). Set the locale to one you know uses , to separate thousands. If you know that won't be an issue you can pass undefined for the locale.
Your snippet has been updated below:
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
// .toLocaleString
var tot = totNumber.toLocaleString("en-US", { maximumFractionDigits: 2});
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
// replace ',' here
subtotal += parseFloat($(this).val().replace(/,/g,''));
});
// toLocaleString
$('#subtotal').val(subtotal.toLocaleString("en-US", { maximumFractionDigits: 2}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>

popup taking first entry of the table every time

I am having table with 6 fields and there is update button in the last field, onclick of that one popup appears but popup is taking only first entry of the in the table every time even if pressing the second or third entry's update button.
Here is my JSP Code `
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Report</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-2"></div>
<div class="col-sm-8">
<div class="panel panel-primary">
<div class="panel-heading">Details of Students</div>
<div class="panel-body">
<button id="newbtn" type="button"
class="form-control btn btn-success">Add New Student</button>
<button id="shwbtn" type="button"
class="form-control btn btn-success">show</button>
<div style="margin-top: 40px;">
<table class="table table-bordered" id="updatedetailsFrm">
<thead>
<tr style="background-color: #E0E0E1;">
<th>Sr.No.</th>
<th>Name</th>
<th>Surname</th>
<th>Contact No</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<s:if test="noData==true">
<s:iterator value="beanList">
<tr>
<td><s:property value="srNo" /></td>
<td><s:property value="name" /></td>
<td><s:property value="surname" /></td>
<td><s:property value="contactno" /></td>
<td><s:property value="email" /></td>
<td>
<a href="#popupLogin" data-rel="popup"
data-position-to="window" id="updateBtnfirst"
class="ui-btn ui-corner-all ui-shadow" data-transition="pop">Update</a>
<div data-role="popup" id="popupLogin" data-theme="a"
class="ui-corner-all">
<form id="updatedetailsFrm" method="post">
<div style="padding: 10px 20px;">
<h3>Update Your Data</h3>
<input id="name" placeholder="Name" type="text" name="name"
value='<s:property value="name"/>'>
<input id="surname" placeholder="Surname" type="text"
name="surname" value='<s:property value="surname"/>'>
<input id="contactno" placeholder="Contact No" type="text"
name="contactno" value='<s:property value="contactno"/>'>
<input id="email" class="disabled" placeholder="Email" type="text"
name="email" value='<s:property value="email"/>'>
<button value="update" type="button" id="updateBtn">Update</button>
</div>
</form>
</div>
<button class="btn btn-danger" id="deleteBtn">Delete</button>
</td>
</tr>
</s:iterator>
</s:if>
</table>
<s:else>
<div style="color: red;">No Data Found.</div>
</s:else>
</div>
</div>
</div>
</div>
<div class="col-sm-2"></div>
<script>
$("#updateBtn").click(function() {
var id = document.forms["updatedetailsFrm"]["email"].value;
var userName = document.forms["updatedetailsFrm"]["name"].value;
var surName = document.forms["updatedetailsFrm"]["surname"].value;
var contactNo = document.forms["updatedetailsFrm"]["contactno"].value;
window.location = "updatedetails.action?email="+id+"&name="+userName+"&surname="+surName+"&contactno="+contactNo;
})
// $('#updateBtnfirst').click(function() {
// document.getElementById("email").disabled = true;
// })
$('#newbtn').click(function() {
window.location.href = "insert.jsp";
})
$('#shwbtn').click(function() {
window.location = "report";
})
$("#deleteBtn").click(function() {
var id = $(this).closest("tr").find('td:eq(4)').text();
window.location.href = "deleterecord.action?&email=" + id;
})
</script>
</body>
</html>
`
So, my question is, popup should bring the row wise details in popup, in particular row.
Your iterator generates all of your rows with the same ID's over and over again. Update your iterator to generate unique ID's for each form in each row. I would then remove the ID from the update button and use a class instead so it's easy to bind your click event and use an HTML "data" attribute to hold the form ID value. Then when an update button is clicked, your JavaScript will be able to grab the data attribute value and then target the correct form via unique ID.
Example update button:
<button value="update" type="button" class="updateBtn" data-form-id="updatedetailsFrm-1">Update</button>
Example form ID:
<form id="updatedetailsFrm-1" method="post">
With duplicate ID's, you'll only ever retrieve the first instance of what you're trying to target in the DOM. There are other ID's in your iterator you'll want to look at too. ID's should be unique.

Dynamic Invoice Forms fields and posting to a database

I am building a form to create invoices. At the moment it has the form fields of:
Product Name, QTY.
I have a "add more" button which adds another row of the above form fields.
It then submits as an array to another php page. What i am having problems with is matching each associated form field with each other because when i save it in the database i need the correct Product Name, QTY to be on the same row in the table obviously. Just not sure how to match them.
Currently my code on the form field page is:
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
On the name.php page where the form submits to. What is the best way to get each product and associated qty from the array and put them into the database row. Keeping in mind this is dynamic.
On name.php when i print out $_POST i currently have this array structure:
Array
(
[product_name] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
)
[qty] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[submit] => Submit
)
Im guessing I need to count the keys and then match them in the other dimension of the array. Just not sure if that is the best way or even how to do that.
You could use this
$productName = $_POST['productName'];
$qty = $_POST['qty']
foreach($productName as $key => $productName) {
$productQty = $qty[$key];
//Use your ORM (or whatever) to inster into DB
//$productName and $productQty
}
EDIT
Or, even better, you could user PHP's array_combine:
$productName = $_POST['productName'];
$qty = $_POST['qty']
$arryWithTotals = array_combine($productName, $qty);
foreach($arrayWithTotals as $productName => $productQty) {
//insert into DB
}
If you wish you can use like these way.
<html>
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><?php
session_start();
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])) {
echo $_SESSION["message"];
unset($_SESSION["message"]);
}
?></td>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
PHP
====
$data = $_POST['product_name'];
$data2 = $_POST['qty'];
$product_name = "'" . implode("','", array_values($data)) . "'";
$qty = "'" . implode("','", array_values($data2)) . "'";
$conn = mysql_connect("localhost", "root", "") or die("unable to connect Mysql");
mysql_select_db("Your DB Name called here") or die("unable to connect DB");
$query = "INSERT INTO `Your DB Name called here`.`Your Table Name called here` (`id`, `product_name`,`qty` ) VALUES (NULL, '$product_name', '$qty')";
if (mysql_query($query)) {
$_SESSION["message"] = "Successfully submitted";
}
header("location:your page name.php");

Categories

Resources