I've got a table:
And a button named "Aplicar Filtro" that filters the table by whatever I input in the input fields below the header.
The problem is that it's not doing anything and I don't know why, console isn't showing any errors.
Here is my code, pueblaTabla() is specifically the function that filters the table:
<?php
include '../definenachopc.php';
// include '../definegrupo2.php';
$conn = new mysqli($HOST, $USER, $PASS, $DB);
$orderBy = "idAuto";
$order = "desc";
?>
<!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>ABM</title>
<link rel="stylesheet" href="style.css">
<script src=".././jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="parte">
<button id="cmdFiltrar">Aplicar filtro</button>
</div>
<div class="parte">
<button id="cmdLimpiaFiltros">Limpiar filtros</button>
</div>
<div class="demo-content">
<div id="demo-order-list">
<?php
$sql = "SELECT * FROM AUTOS";
$result = $conn->query($sql);
$resultadoNumeroDeAutos = $result->num_rows;
?>
<table class="table-content">
<thead>
<tr>
<th onClick="orderColumn('idAuto','desc')">idAuto</th>
<th onClick="orderColumn('Marca','asc')">Marca</th>
<th onClick="orderColumn('Modelo','asc')">Modelo</th>
<th onClick="orderColumn('idTipoDeVehiculo','asc')">idTipoDeVehiculo</th>
<th onClick="orderColumn('FechaDeLanzamiento','asc')">FechaDeLanzamiento</th>
</tr>
<tr>
<td></td>
<td><input type="text" name="filtroMarca" id="filtroMarca"></td>
<td><input type="text" name="filtroModelo" id="filtroModelo"></td>
<td><select id="filtroidTipoDeVehiculo" name="filtroidTipoDeVehiculo">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></td>
<td><input type="text" name="filtroFechaDeLanzamiento" id="filtroFechaDeLanzamiento"></td>
</tr>
</thead>
<?php
$salidaJson = array("autos" => array());
while ($row = $result->fetch_assoc())
{
$salidaJson['autos'][] = array("idAuto" => $row['idAuto'],
"Marca" => $row['Marca'],
"Modelo" => $row['Modelo'],
"idTipoDeVehiculo" => $row['idTipoDeVehiculo'],
"FechaDeLanzamiento" => $row['FechaDeLanzamiento']);
}
$salidaJson = json_encode($salidaJson);
?>
<tbody id="tbDatos">
</tbody>
</table>
</div>
</div>
<h1>NĂºmero de autos: <?php echo $resultadoNumeroDeAutos; ?></h1>
<script>
var miTabla = $("tbody");
var listaDeAutos = <?php echo $salidaJson ?>;
console.log(listaDeAutos);
// carga la tabla
$(document).ready(function() {
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td><td>' + item.idTipoDeVehiculo + '</td><td>' + item.FechaDeLanzamiento + '</td></tr>';
miTabla.append(html);
});
})
function limpiarFiltros() {
$("#filtroMarca").val('');
$("#filtroModelo").val('');
$("#filtroidTipoDeVehiculo").val('');
$("#filtroFechaDeLanzamiento").val('');
};
function orderColumn(column_name,column_order) {
$.ajax({
url: "order-column.php",
data:'orderby='+column_name+'&order='+column_order,
type: "POST",
success: function(data){
$('#demo-order-list').html(data);
}
});
}
function pueblaTabla() {
$("#tbDatos").empty();
$.ajax({
type: "POST",
url: "",
data: {
fMarca: $("#filtroMarca").val(),
fModelo: $("#filtroModelo").val(),
fidTipoDeVehiculo: $("#filtroidTipoDeVehiculo").val(),
fFechaLan: $("#filtroFechaLan").val(),
},
success: function(data) {
$("#tbDatos").empty();
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td><td>' + item.idTipoDeVehiculo + '</td><td>' + item.FechaDeLanzamiento + '</td></tr>';
miTabla.append(html);
// /*Nuevo para abm*/
// var objTd = document.createElement("td");
// objTd.innerHTML = "<button>M</button>";
// objTd.onclick = function() {
// var cadenaDePaso = "?ID=" + argValor.ID;
// location.href = "./fichaAbm.php" + cadenaDePaso;
// }
// objTr.appendChild(objTd);
// var objTd = document.createElement("td");
// objTd.innerHTML = "<button>B</button>";
// objTd.onclick = function() {
// var cadenaDePaso = "?ID=" + argValor.ID;
// location.href = "./baja.php" + cadenaDePaso;
// }
// objTr.appendChild(objTd);
});
}
});
}
$("#cmdLimpiaFiltros").click(function() {
limpiarFiltros();
});
$( "#cmdFiltrar" ).click(function() {
pueblaTabla();
});
</script>
</body>
</html>
Add a failure function to the Ajax call...the do console.log...youll get why it's failing if it's the Ajax call
Related
My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.
May I ask for assistance regarding this matter? I checked every guide regarding this concern, and followed all guide, but no luck.
When the table is populated via AJAX call, all the data is in a single page only.
I tried adding the whole dataTable script into the tbody caller, but no luck.
These are the following codes.
This is my <?php include 'ajax-process/earnings_amendment_account-ajax-table.php'; ?>
<script>
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url:'table_body/earnings_amendment_account_table_body.php',
dataType:'json',
type:'get',
cache:true,
success:json,
});
function json(data){
$("#earnings_amendment_account_body").empty();
$(data).each(function(index,value) {
console.log(value);
var table = '<tr>' +
'<td>' + value.accountcode + '</td>'+
'<td>' + value.accounttitle + '</td>'+
'<td>' + value.accounttype + '</td>'+
'</tr>';
$('#earnings_amendment_account').append( table );});
}
}, 1000);
$('#earnings_amendment_account').dataTable();
});
</script>
This is my table in index.php
<table id="earnings_amendment_account" class="table table-bordered" style="table-layout: fixed; display: none">
<thead>
<th>Account Code</th>
<th>Account Title</th>
<th>Account Type</th>
</thead>
<tbody id="earnings_amendment_account_body">
</tbody>
</table>
This is my table_body/earnings_amendment_account_table_body.php
<?php
include '../backend/conn.php';
include '../backend/session.php';
$params=array();
$sql = "SELECT accountcode,accounttype,accounttitle,accounttype,postedby,dateposted,
approvedby,dateapproved FROM earningsamendmentaccount";
$query = sqlsrv_query($conn, $sql, $params, array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($query === false ) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; }
$dbdata = array();
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$dbdata[]=$row;
}
echo json_encode($dbdata);
?>
This is my dataTable.
// all of the function in this dataTable is still not included because I'm testing if everything works well when my dataTable body is being called via AJAX.
<script>
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({
"pagingType": "full_numbers"
});
$('#earnings_amendment_account').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = earnings_amendment_account_table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Posted By : ' : tr.data('key-1'),
'Date Posted : ' : tr.data('key-2'),
'Approved By : ' : tr.data('key-3'),
'Date Approved : ' : tr.data('key-4')
})).show();
tr.addClass('shown');
} });
</script>
The data is being passed on console. Showing 0 out of 0 Entries, but the data is on display in the page.
Top:
Bottom:
Thank you so much in advance.
here is i did basic example of datatabe, you need to follow this things if you are using datatable and do custom thing.
Index.php
<!DOCTYPE html>
<html leng="en">
<head>
<title>Display Emloyee </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="table-responsive">
<table class="table table-striped" id="tabl_user">
<thead>
<tr>
<th>Id</th>
<th>F Name</th>
<th>L Name</th>
<th>Gender</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function()
{
$('#tabl_user').DataTable( {
"processing": true,
"serverSide": true,
"lengthMenu": [5, 10, 25, 50, 100, 150],
"columnDefs" : [{orderable:false, targets:[1] }],
"ajax": "trylimited.php"
} );
});
</script>
</div>
</div>
</body>
</html>
trylimited.php
<?php
include "con.php";
$column = array('id', 'first_name', 'last_name', 'phone_no', 'mobile','city', 'zip');
$sIndexColumn = "id";
$sTable = "elision_user";
// Searching
$wherecondition = "";
if($_REQUEST['search']['value'] != "")
{
$wherecondition = "WHERE (";
for($i=0; $i<count($column); $i++)
{
$wherecondition .="".$column[$i]." LIKE '%".$_REQUEST['search']['value']."%' OR ";
}
$wherecondition = substr_replace($wherecondition, "", -3);
$wherecondition .=')';
}
$draw = $_REQUEST['draw'];
$start = $_REQUEST['start'];
$limit = $_REQUEST['length'];
$sql = "SELECT * FROM allinone";
$res = mysqli_query($con, $sql);
$sql1 = "SELECT * FROM elision_user";
$sql1.=" $wherecondition ORDER BY ".$column[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir']." limit $start, $limit";
$res1 = mysqli_query($con, $sql1);
$recordsTotal = mysqli_num_rows($res1);
$recordsFiltered = mysqli_num_rows($res);
$asd = array();
$final_array = array();
while( $row = mysqli_fetch_array($res1) ) {
$dataArray = array();
$dataArray[] = $row["id"];
$dataArray[] = $row["first_name"];
$dataArray[] = $row["last_name"];
$dataArray[] = $row["phone_no"];
$dataArray[] = $row["mobile"];
$dataArray[] = $row["city"];
$dataArray[] = $row["zip"];
$asd[]=$dataArray;
}
$final_array = array("draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $asd, "sql" => $sql1);
echo json_encode($final_array); exit;
?>
Hope this example will help you for your concern.
please vote positive if this example will helpfull
I am trying to provide a view where people will be able to create a list of categories and sub categories. Therefore I need to allow users to dynamically add Rows.
Each Row will allow user to add a category and then if they wish a Sub Category. For the first row I am able to use asp-items attributes to bind to a SelectList in my ViewBag, however when I add a new row via JS I cannot do it, I have tried 2 methods JS (both shown in the code):
1 - Storing the SelectList in a variable and looping through it
2 - Setting the asp-items to the SelectList
Does anyone know how I can populate my newly added rows? Also how would I bind the enetred in data to my Model; would it have to be done in the controller?
The code is as follows:
<script type="text/javascript">
$(document).ready(function () {
var categories = "#ViewBag.Categories";
var catOptions = '';
for (var i = 0; i < categories; i++) {
catOptions = catOptions + '<option value="' + categories[i].CategoryId + '">' + categories[i].Name + '</option>'
}
$(document).on("click", "#btnAddCat", function () {
var newCat =''+
'<tr class="categorieRows">' +
'<td colspan="2">' +
'<select>' +
catOptions +
'</select>' +
'</td>' +
'<td>' +
'<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>' +
'</td>' +
'</tr>';
$('#categoryTable').append(newCat);
});
$(document).on("click", "#btnAddSubCat", function () {
var newSubCat = '' +
'<tr class="categorieRows">' +
'<td></td>' +
'<td>' +
'<select asp-items="ViewBag.SubCategories"></select>' +
'</td>' +
'<td></td>' +
'</tr>';
$('#categoryTable').append(newSubCat);
});
});
</script>
#model IEnumerable<Categories>
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Surveys</h4>
<hr />
<table class="table table-striped" id="categoryTable">
<thead>
<tr>
<th>
Category
</th>
<th>
Sub Categories
</th>
<th>
<button type="button" id="btnAddCat" class="btn btn-xs btn-primary classAdd">Add Category</button>
</th>
</tr>
</thead>
<tbody>
<tr class="categorieRows">
<td colspan="2">
<select asp-items="ViewBag.Categories"></select>
</td>
<td>
<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>
</td>
</tr>
</tbody>
</table>
<div>
<a asp-action="Index">Back to List</a>
</div>
Used Ajax calls to retrieve Categories data:
<script>
$(document).ready(function () {
$(document).on("change", "#selectCategroy", function () {
var subCat = this;
$.ajax({
url: "ReturnJsonSubCategories/?categoryId=" + $(subCat).val(),
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
var categories = "";
$(result).each(function () {
categories = categories + '<option value="' + this.subCategoryId + '">' + this.name + '</option>'
});
var subCateList = $("#selectSubCategroy");
subCateList.empty();
subCateList.append(categories);
},
error: function (data) {
return "Error";
}
});
});
});
</script>
With the server side code looking like:
public JsonResult ReturnJsonSubCategories(int categoryId)
{
var jsonData = _context.SubCategories.Where(x => x.CategoryId == categoryId).ToList();
return Json(jsonData);
}
Similar with the last answer but a bit shorter
$(function () {
$('#CategoryId').change(function () {
$('#SubCategoryId').empty();
var url = '#Url.Content("~/")' + "api/CategoryApi/ListSubCategories";
$.getJSON(url, { categoryId: $('#CategoryId').val() })
.done(function (data) {
var subcategories = "";
$(data).each(function () {
subcategories += '<option value="' + this.CategoryId + '">' + this.Title + '</option>'
});
$('#SubCategoryId').append(subcategories);
})
});
});
and on server side
[HttpGet]
[Route("ListSubCategories")]
public IActionResult ListSubCategories(int categoryId)
{
var subCategories = _categorySvc.ListSubCategories(categoryId);
return Ok(subCategories);
}
I am adding rows dynamically with autofilled values from database. After adding it, it has to calculate total. Now it is calculating total only for 1st row. for 2nd row onwards it is not calculating anything. And also overall total is not happening.
Here is my code
html form
<table class="table table-bordered">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()" /></th>
<th>No</th>
<th>Item ID</th>
<th>Description</th>
<th>UOM</th>
<th>Price</th>
<th>Tax</th>
<th>Quantity</th>
<th>Discount</th>
<th>Amount</th>
</tr>
<tr>
<td><input type='checkbox' class='case' /></td>
<td><span id='snum'>1.</span></td>
<td><input type="text" class="form-control" id="productcode_1" name="productcode[]"></td>
<td><input type="text" class="form-control" id="description_1" name="description[]"></td>
<td><input type="text" class="form-control" id="uom_1" name="uom[]"></td>
<td><input type="text" class="form-control price" id="price_1" name="price[]"></td>
<td><input type="text" class="form-control tax" id="tax_1" name="tax[]"></td>
<td><input type="text" class="form-control quantity" id="quantity_1" name="quantity[]"></td>
<td><input type="text" class="form-control discount" id="discount_1" name="discount[]"></td>
<td><input type="text" class="form-control amount" id="amount_1" name="amount[]"></td>
<td><button type="button" class='btn btn-danger delete'>-</button></td>
<td><button type="button" class='btn btn-success addmore'>+ </button></td>
</tr>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th style="text-align:center;" class="total">0<b></b></th>
</tfoot>
</table>
javascript
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
check();
});
var i = $('table tr').length - 1;
$(".addmore").on('click', function() {
count = $('table tr').length - 1;
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + i + "'>" + count + ".</span></td>";
data += "<td><input class='form-control' type='text' id='productcode_" + i + "' name='productcode[]'/></td> <td><input class='form-control' type='text' id='description_" + i + "' name='description[]'/></td><td><input class='form-control' type='text' id='uom_" + i + "' name='uom[]'/></td><td><input class='form-control' type='text' id='price_" + i + "' name='price[]'/></td><td><input class='form-control' type='text' id='tax_" + i + "' name='tax[]'/></td><td><input class='form-control' type='text' id='quantity_" + i + "' name='quantity[]'/></td><td><input class='form-control' type='text' id='discount_" + i + "' name='discount[]'/></td><td><input class='form-control' type='text' id='amount_" + i + "' name='amount[]'/></td></tr>";
$('table').append(data);
row = i;
$('#productcode_' + i).autocomplete({
source: function(request, response) {
$.ajax({
url: 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'items_table',
row_num: row
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_
$('#description_' + id[1]).val(names[1]); $('#uom_' + id[1]).val(names[2]); $('#price_' + id[1]).val(names[3]); $('#tax' + id[1]).val(names[4]);
}
});
i++;
});
function select_all() {
$('input[class=case]:checkbox').each(function() {
if ($('input[class=check_all]:checkbox:checked').length == 0) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
$('body').delegate('.quantity,.price,.discount,.tax', 'keyup', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').valr price = tr.find('.price').val tax = tr.find('.tax').val
var dis = tr.find('.discount').valr amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt) * (tax / 100);
tr.find('.amount').val(tax1al();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = $(this).val() - 0;
t += tax1;
});
$('.total').html(t);
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
$('#' + id).html(key + 1);
});
}
$('#productcode_1').autocomplete({
source: function(request, response) {
$.ajax({
url: 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'items_table',
row_num: 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#description_1').val(names[1]);
$('#uom_1').val(names[2]);
$('#price_1').val(names[3]);
$('#tax_1').val(names[4]);
}
});
ajax.php
<?php
require_once '../connect.php';
if($_POST['type'] == 'items_table'){
$row_num = $_POST['row_num'];
$name = $_POST['name_startsWith'];
$query = "SELECT items.iid, items.description, items.uom, items.selling_price, items.tax_id, taxes.tax_id, taxes.name, taxes.rate FROM items INNER JOIN taxes ON items.tax_id=taxes.tax_id where items.iid LIKE '".strtoupper($name)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['iid'].'|'.$row['description'].'|'.$row['uom'].'|'.$row['selling_price'].'|'.$row['rate'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
?>
Only 1st row total is getting calculated. Not getting what is wrong
I got it resolved.Because of the class i have used
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var tax = tr.find('.tax').val();
var dis = tr.find('.discount').val();
var amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt * (tax / 100));
//alert(tax1);
tr.find('.tamount').val(tax1);
ttotal();
tr.find('.amount').val(amt);
total();
});
function total() {
var t = 0;
$('.amount').each(function(i, e) {
var amt = $(this).val() - 0;
t += amt;
});
$('.total').html(t);
}
function ttotal() {
var tt = 0;
$('.tamount').each(function(i, e) {
var tax = $(this).val() - 0;
tt += tax;
});
$('.ttotal').html(tt);
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
$('#' + id).html(key + 1);
});
}
I successfully cloned my table rows, which has values retrieved from database. However I have few issues with it.I used class for all the elements as clone will duplicate IDs.No the problem raises because it unable to target each element uniquely. WHat's the way to do make each element / row unique here?
How the functions work:
When first select box selected, item for that selected id would appear in the next column.Followed by price textbox and quantity textbox. WHen both are filled up, last textbox for total amount would automatically appear.
Issues with the cloning are:
* WHen select box selected from the first/original row, all cloned items are updated with the value.Same goes for amount textbox and vise-versa.
My script:
<script>
var harga;
var qty;
$("input[name^=harga]").on("keyup", function () {
alert($(this).attr("id"));
console.log($(this).val());
harga = $(this).val();
});
$(".qty").on("keyup", function () {
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$(".amount").val(amount);
});
$(document).ready(function () {
$(".sub_item").hide();
$('.gr').change(function () {
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['
agency_id
'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".sub_item").show();
$(".it_id").empty();
for (i = 0; i < data.length; i++) {
$(".it_id").append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$(".it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$("#more_items").on("click", function () {
alert("Hi");
$(".clone_this").clone(true, true).insertBefore("#last_e");
});
$(function () {
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function () {
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide1").show();
} else {
$("#hide1").hide();
}
});
$('#insurance').change(function () {
$("#hide2").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide2").show();
} else {
$("#hide2").hide();
}
});
$('#bon').change(function () {
$("#hide3").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide3").show();
} else {
$("#hide3").hide();
}
});
});
</script>
Form
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr>
<th>Group Item</th>
<th>Nama Item</th>
<th>Harga</th>
<th>Kuantiti</th>
<th>Amount</th>
</tr>
<tr class="clone_this">
<td>
<select name='group' style="width:80px;" class="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach ($group as $k => $v) {
$i = 0;
$i++;
?>
<option value="<?php echo $v['group_id'] ?>"><?php echo $v['group_name'] ?></option>
<?php
}
?>
</select>
</td>
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
</select>
</td>
<td><input type="text" name="harga_<?php echo $i; ?>[]" id="<?php echo $i; ?>" value="" class="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty[]' class='qty'/>
</td>
<td><input type="text" name="amount[]" class="amount" value=""/></td>
</tr>
<tr id="last_e">
<td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
You need find the relative elements to update so
$(document).ready(function () {
$('#submit_item').on('keyup', '.qty, .harga', function () {
var $tr= $(this).closest('tr');
$tr.find('.amount').val($tr.find('.harga').val() * $tr.find('.qty').val() || 0)
})
$(".sub_item").hide();
$('#submit_item').on('change', '.gr', function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});
Demo: Fiddle