Issue in populating dynamic data to dropdown column using ajax - javascript

I am trying to populate and append a column For Example:Id with the below column data dynamically using jquery and ajax.
The data will be populated via rest webservice. But the data is not getting populated.
The code snippet is as below.
The code which is pasted may not work properly due to lack of dynamic data from a webservice.
So the issue lies in populating/appending the data into the column in the header.
$(document).ready(function() {
// DO GET
$.ajax({
type: "GET",
url: "api/customer/all",
success: function(result) {
$.each(result, function(i, customer) {
var customerRow = "<tr><td><input type='checkbox' name='record'></td><td>" +
customer.id + "</td><td>" +
customer.name.toUpperCase() + "</td><td>" +
customer.age + "</td><td>" +
customer.address.street + "</td><td>" +
customer.address.postcode + "</td></tr>";
$('#IdProof').append('<option value="' + customer.id + '">' + customer.age + '</option>');
$('#customerTable tbody').append(customerRow);
});
},
error: function(e) {
alert("ERROR: ", e);
console.log("ERROR: ", e);
}
});
$('#select-all').click(function(event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
$('#reboot').click(function() {
$('#customerTable').find('tr').each(function(i) {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var $tds = $(this).find('td'),
Id = $tds.eq(1).text(),
name = $tds.eq(2).text(),
age = $tds.eq(3).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + Id +
'\nname: ' + name +
'\nage: ' + age);
}
});
});
$(function() {
$("#inputFilter").on("keyup", function() {
$("#select-all").hide();
var value = $(this).val().toLowerCase();
$("#customerTable > tbody > tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
})
<!DOCTYPE HTML>
<html>
<head>
<title>Spring Boot - DELETE-UPDATE AJAX Example</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.2.1/jquery.min.js"></script>
<script src="/js/jqueryScript.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="#{/css/main.css}" />
</head>
<body>
<div class="container">
<h2>Filter Table</h2>
<div class="row col-md-7 ">
<div style="margin-bottom: 20px; padding: 10px; background-color: green; color: white;">
<p>
Type some text to search the table for <strong>Id</strong>, <strong>Name</strong>,
<strong>Age</strong>, <strong>Street</strong>, <strong>PostCode</strong>:
</p>
<input class="form-control" id="inputFilter" type="text" placeholder="Search.." />
</div>
<table id="customerTable" class="table table-bordered table-hover table-responsive ">
<thead>
<tr>
<th><input type="checkbox" name="select-all" id="select-all" /></th>
<th>
<select name="IdProof" id="id" class="form-control">
<option value="">Id</option>
</select>
</th>
<th>
<select name="Name" id="name" class="form-control">
<option value="">Name</option>
</select>
</th>
<th>
<select name="Age" id="age" class="form-control">
<option value="">Age</option>
</select>
</th>
<th>
<select name="Street" id="street" class="form-control">
<option value="">Street</option>
</select>
</th>
<th>
<select name="Postcode" id="postcode" class="form-control">
<option value="">Postcode</option>
</select>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="reboot">Reboot</button>
<button id="logs">Logs</button>
</div>
</div>
</body>
</html>

Try to fix your code like this. I think problem is in your concatination. Make all the concatenations like these
var customerRow = "<tr><td><input type='checkbox' name='record'></td><td>" +
customer.id + "'</td><td>'" +
customer.name.toUpperCase() + "'</td><td>'" +
customer.age + "'</td><td>'" +
customer.address.street + "'</td><td>'" +
customer.address.postcode + "'</td></tr>'";

Related

sum td value in table with jquery

I have a table in my program, which adds the values to that row
How can I add the third value of each row?
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
I want to add items within the item's price and show it somewhere for example a div tag or span tag.
In this example, the third child of each scroll row should be added together and sum them together
Updated code by writing 'sum' logic in separate function.
function calculateSum() {
//Calculate sum of price
var sum = 0;
$('.table tbody tr').each(function() {
var item_price = parseInt($(this).find('td:nth-child(3)').html());
//Check for NaN & add.
sum += item_price?item_price:0;
});
//Display to div
$("#total").text(sum);
}
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
calculateSum(); //Perform sum after removing row.
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
calculateSum(); //Perform sum after adding row.
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="total"></div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
below code help you to add logic for sum.
$(document).ready(function() {
var totle = 0;
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
totle += parseInt(item_price);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
alert("Totle price is : " + totle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can create a div with totalprice and then please add some jQuery code as mentioned below.
var totalprice = item_price;
var currentprice = $("#totalprice").text();
totalprice = (parseInt(currentprice) + parseInt(item_price)) ;
$("#totalprice").html(totalprice);
Add it in add button.
$(".add-row").click(function () {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
var totalprice = item_price;
var currentprice = $("#totalprice").text();
totalprice = (parseInt(currentprice) + parseInt(item_price)) ;
$("#totalprice").html(totalprice);
});
$("table").on("click", "#del", function () {
$("table tbody").find('tr td').each(function () {
$("table").on("click", "#del", function () {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function () {
var ids = [];
$('.table tbody tr').each(function () {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
<div class="col-md-3">
<b>Total Price is : </b><span id = "totalprice">0</span>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>

Calculate total sum of dynamically added items to a table

I would like to calculate the line total for each item using the itemPrice* Qty fields, the line amount is to be auto populated in the linePrice textbox. After which the grand total is then auto populated to the priceTotal field by summing up all the line prices.
I am having a challenge getting each Qty and itemPrice textbox value into my JavaScript function since the name(s) is/are Qty0, Qty1, Qty2... and itemPrice0, itemPrice1,.. depending on the added row, and also getting the final calculations into the respective textboxes.
Below is my code.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$(document).ready(function() {
$(document).on("keyup", ".Qty", calculateTot);
$("button").click(function() {
addrow('tb')
});
});
function calculateTot() {
var sum = 0;
var price = document.getElementById('itemPrice').value;
var qtyPur = parseFloat(this.value);
$(".Qty").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
linePR = price * qtyPur;
}
});
$("#linePrice").val(linePR.toFixed(2));
calculateSum();
}
function calculateSum() {
var sum = 0;
$(".linePrice").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#priceTotal").val(sum.toFixed(2));
}
$(document).ready(function() {
var i = 1,
j = 1;
$("#add_row").click(function() {
if (i < 10) {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
$('#tab_add').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
j++;
$('#delete_row').show();
} else {
alert("You can only add upto a maximum of 10 items")
$('#add_row').hide();
}
});
$("#delete_row").click(function() {
if (i > 1) {
var r = confirm('Do you want to delete this item?');
if (r == true) {
$("#addr" + (i - 1)).html('');
i--;
$('#add_row').show();
}
} else {
alert("Entry cannot be deleted")
$('#delete_row').hide();
}
});
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<table class="table table-bordered table-hover" id="tab_add">
<tbody>
<tr>
<td colspan="2"><b>Customer Name</b></td>
<td colspan="1">
<select name="Per_Name[]" class="form-control">
<option value="">Select Customer</option>
<option value="2000001">John Doe</option>
<option value="2000002">Jane Doe</option>
<option value="2000003">Tom Harry</option>
<option value="2000004">Steve Jobs</option>
</select>
</td>
</tr>
<tr id='addr0'>
<td><b>1</b></td>
<td><b>Select Item</b></td>
<td colspan="1">
<select name="Sub_Name[]" class="form-control">
<option value="">Select Item</option>
<option value="1000001">Item A</option>
<option value="1000002">Item B</option>
<option value="1000003">Item C</option>
<option value="1000004">Item D</option>
</select>
</td>
<td><input type="text" name="itemPrice0" id="itemPrice0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" class="Qty form-control" onkeypress="return isNumberKey(event)" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
<th>
<span class="glyphicon glyphicon-plus"></span>
<span class="glyphicon glyphicon-minus"></span>
</th>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<tr id="finRow">
<td colspan="2" width="75%"><b>TOTAL</b></td>
<td><input type="text" name="priceTotal" id="priceTotal" class="row-total form-control" disabled></td>
</tr>
</table>
In order to reduce the amount of DOM traversal that you have to do to accomplish this, I suggest adding data-* attributes to your elements so that you can get the index and use that to reference the other elements directly.
<td><input type="text" name="itemPrice0" id="itemPrice0" data-index="0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" data-index="0" class="Qty form-control" onkeypress="if(!isNumberKey(event)){return false;}" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" data-index="0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
Then in your $("#add_row").click(function() { function we add data-index='"+j+"' when creating the new elements ...
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
Finally, change your keyup handler to ...
$("#tab_add").on("keyup", ".Qty", function(e){
var qtyPur = parseFloat(this.value);
if (!isNaN(this.value) && this.value.length != 0) {
// this is where use use the data-index attribute to dynamically generate the target element ids
$("#linePrice"+$(this).data('index')).val(
parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
);
}
calculateSum()
});
See Demo
This part of code will calculate linePrice of each row:
$("tr").each(function() {
if ($(this).children("td").length) {
$($($(this).children("td")[5]).children("input")[0]).val(
(($($($(this).children("td")[4]).children("input")[0]).val()) ? Number($($($(this).children("td")[4]).children("input")[0]).val()) : 0) *
(($($($(this).children("td")[3]).children("input")[0]).val()) ? Number($($($(this).children("td")[3]).children("input")[0]).val()) : 0)
)
}
});
function grosschanged_total1(a) {
var str = a;
var res = str.split("_");
//alert(res[2]);
var result = res[2];
var rate = parseFloat(document.getElementById("Gridview1_txtgross_" + result).value) * parseFloat(document.getElementById("Gridview1_txtrate_" + result).value);
var scale77 = 2;
// rate = roundNumberV2(rate, scale77);
var gresult = 0.00;
if(isNaN(rate)){
gresult= document.getElementById("Gridview1_txttotal_" + result).value = "";
} else{
gresult= document.getElementById("Gridview1_txttotal_" + result).value = parseFloat(Math.round(rate * 100) / 100).toFixed(2);
}
//GridView1_txtinvamt_0
var gfresult = parseFloat(gresult);
var ggresult = 0.00;
ggresult = gfresult + ggresult;
// $("[id*=lblGrandTotal]").html(ggresult);
//GridView1_txtdelinvnum_0 + GridView1_txtinvamt_0 = GridView1_txtgrosspt_0
// Calculate();
grosschanged_total1(a);
}
function Numerics(text) {
var regexp = /^[0-9]*$/;
if (text.value.search(regexp) == -1) {
text.value = text.value.substring(0, (text.value.length - 1));
alert('Numerics only allowed');
if (text.value.search(regexp) == -1)
text.value = "";
text.focus();
return false;
}
else
return true;
}

dynamic form not submitting when display goes from none to block

I have created a script that sends a form that sends a form, a form that is dynamic depending on users choices.
The form in the html side looks fine, the code in the jQuery side executes fine until the actual form submits, and nothing in the console log tells me there is anything wrong at all.
The only thing I can think of is that this form starts being a display:none; in the css and then becomes available ones the person clicks a button saying add new payments.
Here is the html side of things:
<div class="section-9">
<form action="#" id="addform" method="post">
<div class="row">
<div class="col-sm-12">
<div class="table-responsive" id="addsection">
<table class="table table-responsive table-hover table-striped">
<thead>
<th>Number</th>
<th>Price</th>
<th class="text-center">Installments</th>
<th>Contact Name</th>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" id="addnumber" value="" placeholder="Enter CPO Number"></td>
<td><input type="text" class="form-control" id="addprice" value="" placeholder="Enter CPO Number"></td>
<td class="text-center">Installments</td>
<td><input type="text" class="form-control" id="addcontactname" value="" placeholder="Enter Contact Name"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-sm-12" id="addformajax"></div>
<div class="col-sm-12 margin-top-15">
<p><button class="btn btn-danger btn-block" type="button">SUBMIT</button></p>
</div>
</div>
</form>
</div>
No need to show css as its only display none in the section-9 class.
$('#addnew').on('click', function(e) {
e.preventDefault();
$('.section-9').show();
//do the click button for cpo installments
$('.addi').on('click', function(event) {
event.preventDefault();
var installmentAmount = '<p><select class="form-control" id="installment-ammount"><option value="0">Please Select How Many Installments Are Required</option>';
for (var i = 1; i <= 60; i++) {
if (i === 1) {
installmentAmount += '<option value="' + i + '">' + i + ' Month</option>';
} else {
installmentAmount += '<option value="' + i + '">' + i + ' Months</option>';
}
}
installmentAmount += '</select></p><div class="showinstallmentdates margin-top-20"></div>';
$('#addformajax').html(installmentAmount);
$('#installment-ammount').bind('input', function() {
var buildDateForms = '<p class="red padding-top-20"><i class="fa fa-star"></i> <em>If all amounts are left empty the price will be distributed evenly across all dates</em></p>';
var howManyInstallments = $(this).val();
var addingIdNames = '';
for (var hmi = 1; hmi <= howManyInstallments; hmi++) {
buildDateForms += '<div class="form-group row"><div class="col-xs-6"><input type="text" class="form-control" id="adddate-' + hmi + '" placeholder="Enter Date To Be Paid" value=""></div><div class="col-xs-6"><input type="text" class="form-control" id="addprice-' + hmi + '" placeholder="Amount To Be Paid" value=""></div></div>';
if (hmi == 1) {
addingIdNames += '#adddate-' + hmi;
} else {
addingIdNames += ', #adddate-' + hmi;
}
}
buildDateForms += '<input type="hidden" value="' + howManyInstallments + '" name="totalinstallments" id="totalinstallments">';
buildDateForms += '<script>jQuery(document).ready(function($){ $("';
buildDateForms += addingIdNames;
buildDateForms += '").datepicker({});});<\/script>';
if (howManyInstallments != 0) {
$('.showinstallmentdates').html(buildDateForms);
} else {
$('.showinstallmentdates').html('');
}
});
});
$("#addform").on('submit', function() {
$.ajax({
url: "/Applications/Controllers/Quotes/ajax-add-sin.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(sinData) {
$('body').html(sinData);
}
});
});
});
Granted I am not amazing at jQuery as its not what I use a lot and I am sure a wiz would be able to chop this down to be more efficient and streamline but according to the console I have no issues, and the html looks good also when its all displayed so I can not see a reason why the form is not submitted.
Thanks
Add id to button
<button id="btn-add-form" class="btn btn-danger btn-block" type="button">SUBMIT</button>
Put script to document.ready function
Change ajax function to
$("#btn-add-form").on('click', function () {
$.ajax({
url: "/Applications/Controllers/Quotes/ajax-add-sin.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (sinData) {
$('body').html(sinData);
}
});
});
complete code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#addnew').on('click', function (e) {
e.preventDefault();
$('.section-9').show();
//do the click button for cpo installments
$('.addi').on('click', function (event) {
event.preventDefault();
var installmentAmount = '<p><select class="form-control" id="installment-ammount"><option value="0">Please Select How Many Installments Are Required</option>';
for (var i = 1; i <= 60; i++) {
if (i === 1) {
installmentAmount += '<option value="' + i + '">' + i + ' Month</option>';
} else {
installmentAmount += '<option value="' + i + '">' + i + ' Months</option>';
}
}
installmentAmount += '</select></p><div class="showinstallmentdates margin-top-20"></div>';
$('#addformajax').html(installmentAmount);
$('#installment-ammount').bind('input', function () {
var buildDateForms = '<p class="red padding-top-20"><i class="fa fa-star"></i> <em>If all amounts are left empty the price will be distributed evenly across all dates</em></p>';
var howManyInstallments = $(this).val();
var addingIdNames = '';
for (var hmi = 1; hmi <= howManyInstallments; hmi++) {
buildDateForms += '<div class="form-group row"><div class="col-xs-6"><input type="text" class="form-control" id="adddate-' + hmi + '" placeholder="Enter Date To Be Paid" value=""></div><div class="col-xs-6"><input type="text" class="form-control" id="addprice-' + hmi + '" placeholder="Amount To Be Paid" value=""></div></div>';
if (hmi == 1) {
addingIdNames += '#adddate-' + hmi;
} else {
addingIdNames += ', #adddate-' + hmi;
}
}
buildDateForms += '<input type="hidden" value="' + howManyInstallments + '" name="totalinstallments" id="totalinstallments">';
buildDateForms += '<script>jQuery(document).ready(function($){ $("';
buildDateForms += addingIdNames;
buildDateForms += '").datepicker({});});<\/script>';
if (howManyInstallments != 0) {
$('.showinstallmentdates').html(buildDateForms);
} else {
$('.showinstallmentdates').html('');
}
});
});
});
$("#btn-add-form").on('click', function () {
$.ajax({
url: "/Applications/Controllers/Quotes/ajax-add-sin.php",
type: "POST",
data: $('#addform').serialize(),
contentType: false,
cache: false,
processData: false,
success: function (sinData) {
$('body').html(sinData);
}
});
});
});
</script>
</head>
<body>
<div class="section-9">
<form id="addform" method="post">
<div class="row">
<div class="col-sm-12">
<div class="table-responsive" id="addsection">
<table class="table table-responsive table-hover table-striped">
<thead>
<th>Number</th>
<th>Price</th>
<th class="text-center">Installments</th>
<th>Contact Name</th>
</thead>
<tbody>
<tr>
<td><input name="addnumber" type="text" class="form-control" id="addnumber" value="" placeholder="Enter CPO Number"></td>
<td><input name="addprice" type="text" class="form-control" id="addprice" value="" placeholder="Enter CPO Number"></td>
<td class="text-center">Installments</td>
<td><input name="addcontactname" type="text" class="form-control" id="addcontactname" value="" placeholder="Enter Contact Name"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-sm-12" id="addformajax"></div>
<div class="col-sm-12 margin-top-15">
<p><button id="btn-add-form" class="btn btn-danger btn-block" type="button">SUBMIT</button></p>
</div>
</div>
</form>
</body>
</html>

Show all names found in table when click display button

I need to show all names found in table #tb and display as list using jQuery when the user clicks the display button.
My code is below. I can add successfully, but how can I take data from column name and show as list?
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function () {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function () {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
});
</script>
<style>
.editing {
background: yellow;
}
</style>
</head>
<body>
<div>
ID
<input type="text" id="txt1" /><br />
Name
<input type="text" id="txt2" /><br />
Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select><br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
</div>
</body>
</html>
Try this:
https://jsfiddle.net/ionutmihai1995/euk6xkzp/
$('#btndis').click(function(){
$('ul').empty();
$("#tb").find('tr').each(function(i,el){
var $tds = $(this).find('td');
//for name
$('ul').append("<li>"+$tds.eq(1).text()+"</li>");
});
});
Please check below code.
$("#btndis").on('click',function(){
$("body").append("<ul id='listNames''></ul>");
$('#tb td:nth-child(2)').each(function() {
$("#listNames").append("<li>"+$(this).text()+"</li>")
});
})
Please refer code on this Link. https://jsfiddle.net/gq5f5ux2/2/
On click of the display button iterate loop through all the tr>td-second child to get all the names and then append a UL and LI in the body to display list all the names.
Add a class for colum called "name" and then you can iterate over and select the text in the element
<td class="name">John</td>
Then in JQuery:
$(document).ready(function() {
$('#tb').find('tr').each(function() {
var name = $(this).find('.name').text();
$('#result').append('<p>'+name+'</p>');
});
});
Working example
check this JsFiddle Demo
HTML
<div>
ID
<input type="text" id="txt1" />
<br /> Name
<input type="text" id="txt2" />
<br /> Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select>
<br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
<ul id="ulNames">
</ul>
</div>
JS
$(function() {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function() {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function() {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
$('#btndis').on('click', function() {
//gets table
var oTable = document.getElementById('tb');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
// get your cell info here
var cellVal = oCells.item(1).innerHTML;
$('#ulNames').append('<li>' + cellVal + '</li>');
}
});
});
CSS
.editing {
background: yellow;
}
$("#btndis").click(function() {
$("body").append("ul");
for(var i = 1; i <= $("tr > td").length; i++) {
$("ul").append("li").addClass("li.li-"+i);
$("li.li-"+i).append($("td:nth-child("+i+")").text());
}
}
Explanation :
First, we create the ul to store data. Then, we iterate each tr child (td) with a for loop, we create a li and store data into it. It will be displayed in a list, as asked.

Add and remove row dynamically from jquery from given content

I tried follows code from refer various site but stuck on add/remove dynamic row.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<form>
Name: <input type="text" id="name" value=""></input></br>
Gender : <input type="radio" name="sex" value="male">M &nbsp
<input type="radio" name="sex" value="female">F</br>
Resident: <input type="checkbox" name="resident" value="Yes">Yes &nbsp
<input type="checkbox" name="resident" value="No">No
</br>
Edu : <select name="selectbox" id="selectbox">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</br>
<input type="submit" id="button" value="Submit">
</form>
<table width="400" border="1" id="empinfo" cellpadding="2" cellspacing="2">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Resident</th>
<th>Edu</th>
<th>Action</th>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#button").click(function(){
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
});
});
</script>
</html>
I created one html form and posting data, I have to show submitted
information in table on same page and in action column need to show edit and delete button. if I press edit then information need to open on same page and when I submit it will affect on table. If I press delete button then rows need to remove. All this operation only by using Javascript and Jquery.
Please help me to solve this problem.
Here is the modified code:
$(document).ready(function() {
$("#button").click(function(e){
e.preventDefault();
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
var education = $("#selectbox").val();
var content = '<td>' + name + '</td>' +
'<td>' + gender + '</td>' +
'<td>' + resident + '</td>' +
'<td>' + education + '</td>' +
'<td><button class="edit-row">Edit</button><button class="delete-row">Delete</button></td>';
if ($(this).hasClass('save-edit')) {
$('.editing').html(content);
$("#button").removeClass('save-edit').val('Submit');
} else {
var rowContent = '<tr class="employee-row">' + content + '</tr>';
$('#empinfo').append(rowContent);
}
});
$('body').on('click', '.edit-row', function (e) {
$('.editing').removeClass('editing');
$(this).closest('.employee-row').addClass('editing');
$("#button").addClass('save-edit').val('Save');
});
$('body').on('click', '.delete-row', function (e) {
$(this).closest('.employee-row').remove();
});
});
and jsfiddle:
https://jsfiddle.net/s6wty7vv/2/
This is a working solution:
HTML: Same as what you have updated.
Javascript:
$(document).ready(function() {
$("#button").click(function(e){
e.preventDefault();
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
var education = $("#selectbox").val();
var rowContent = '<tr>' +
'<td>' + name + '</td>' +
'<td>' + gender + '</td>' +
'<td>' + resident + '</td>' +
'<td>' + education + '</td>' +
'<td></td>' +
'</tr>';
$('#empinfo').append(rowContent);
});
});
See the working code: https://jsfiddle.net/s6wty7vv/1/
This will however not persist unless you remove the prevent default and add a form submit and tie it up to a backend, or retain the prevent default and add an ajax call to persist this data in the backend as required.
I think this is what you're looking for:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<form>
Name:
<input type="text" id="name" value=""></input>
</br>
Gender :
<input type="radio" name="sex" value="male">M &nbsp
<input type="radio" name="sex" value="female">F</br>
Resident:
<input type="checkbox" name="resident" value="Yes">Yes &nbsp
<input type="checkbox" name="resident" value="No">No
</br>
Edu :
<select name="selectbox" id="selectbox">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</br>
<input type="submit" id="button" value="Submit">
</form>
<table width="400" border="1" id="empinfo" cellpadding="2" cellspacing="2">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Resident</th>
<th>Edu</th>
<th>Action</th>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident = $('input:checkbox:checked').val();
var edu = $('#selectbox').val();
var rowToAdd = $('<tr>');
rowToAdd.html('<td></td><td></td><td></td><td></td><td></td>');
rowToAdd.find('td:nth-child(1)').html(name);
rowToAdd.find('td:nth-child(2)').html(gender);
rowToAdd.find('td:nth-child(3)').html(resident);
rowToAdd.find('td:nth-child(4)').html(edu);
$('#empinfo').append(rowToAdd);
});
});
</script>
</html>

Categories

Resources