Onchange function for dropdown in jquery ajax - javascript

I have a script with two dropdowns that it is dependent on. The third dropdown is a price, readOnly, which is dependent on subcategory. I have given onChange but there are some problems. I could not render the price value. I am new to ajax and really need some help. I got this example and changed it to fit my needs. I need to just take price from the onClick of subcategory.
Here is my code:
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" class="form-control item_name" />';
html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html += '<td><input type="text" name="item_sub_category_price[]" class="form-control item_sub_category_price" /></td>';
html +='<td><input type="text" name="nosessions[]" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span>Remove Service</button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.item_category', function(){
var category_id = $(this).find(':selected').data('foo');
var sub_category_id = $(this).data('sub_category_id');
// var sub_category_price = $(this).data('sub_category_price');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data){
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#item_sub_category'+sub_category_id).html(html);
}
})
});
$(document).on('change', '.sub_category_id', function(){
alert( this.value );
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_category').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_sub_category').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.item_sub_category_price').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item price '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.nosessions').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select no of sessions '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.packname').each(function(){
if($(this).val() == ''){
error += '<p>Select no of packname '+count+' Row</p> ';
return false;
}
});
var form_data = $(this).serialize();
if(error == ''){
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data){
if(data == 'ok'){
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}; else{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>

<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" id="item_name'+count+'" class="form-control item_name" />';
html += '<td><select name="item_category[]" id="item_category'+count+'" onchange="getsubCategory('+count+')" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" id="item_sub_category'+count+'" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html += '<td><input type="text" name="item_sub_category_price[]" id="item_sub_category_price'+count+'" class="form-control item_sub_category_price" /></td>';
html +='<td><input type="text" name="nosessions[]" id="nosessions'+count+'" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span>Remove Service</button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
});
function getsubCategory(id){
var itemCategory="item_category"+id;
var subcategory_id = "item_sub_category"+id;
var category_id= $("#"+itemCategory).val();
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data){
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#'+subcategory_id).html(html);
}
})
}
</script>
You can do the same for others

I assume that you need to get price of the sub-category using AJAX,
$(document).on('change', '.sub_category_id', function(){
var sub_category_id = $(this).val();
$.ajax({
url:"get_sub_category_price.php",
method:"POST",
data:{sub_category_id : sub_category_id},
success:function(data){
$('#item_sub_category'+sub_category_id).parent().next().find('. item_sub_category_price').val(data);
}
});
});
get_sub_category_price.php file should get the subcategory id and echo the price.

Related

Search function to include space

I am trying to build a search function that would allow me to search Word 1 Word 2 ... Word 'n'.
The code below allows me to search through table rows. Results are presented when there is a 1:1 match (Ignoring case). I would like to search using combinations separated by spaces.
Table data sample as below.
AAA_BBB_CCC_DDD.pdf
EEE_FFF_GGG_HHH.pdf
HTML
<script>
$(function(){
$(function(){
var requestUri = "<<URL>>/_api/web/GetFolderByServerRelativeUrl('<<Folder>>')/Files?$filter=(substringof(%27.pdf%27,Name)%20or%20substringof(%27.PDF%27,Name))&$top=1000";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="Table" style="width:100%"><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + [i+1] + '</td>';
tableContent += '<td>' + objItems[i].Name + '</td>';
tableContent += '<td>' + "<a target='iframe_j' href='<<URL>>" + objItems[i].ServerRelativeUrl + "'>" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
$('#TDGrid').append(tableContent);
}
});
});
</script>
<div id="div">
<input class="form-control mb-2" id="TDSearch" type="text" placeholder=" Search">
<table id='Table' class="table table-striped table-sm small">
<tr>
<td>
<div id="TDGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
Current search function
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
You can convert string to array and then make a function, which will check match for strings of that array.
Something like
$(document).ready(function() {
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
var valueArr = value.split(' ');
$("#TDGrid tr").filter(function() {
$(this).toggle(checkIfValuePresent($(this).text().toLowerCase(), valueArr));
});
});
});
function checkIfValuePresent(currRowText, valuesarr) {
let isfound = false;
for (let i = 0; i < valuesarr.length; i++) {
if (currRowText.indexOf(valuesArr[i] > -1)) {
isfound = true;
break;
}
}
return isfound;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='TDSearch'>
split on space, join all strings with | between them for a combined regex string search, case insensitive.
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle(new RegExp(value.replace(/\./g,'[.]').split(' ').join('|'),'gi').test($(this).text()))
});
});
});

jQuery shows "undefined" for values after unchecking checkbox

I am new to jQuery and AJAX and I was trying to set up a script that displays a MySQL table which can be updated. I included a checkbox to update various entries at the same time. It works fine but if I uncheck the checkbox, all values change to "undefined".
Here is my code:
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
var bezahlstatus = data[count].bezahlstatus;
var guest_amount = data[count].guest_amount;
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-email="'+data[count].email+'" data-guest_amount="'+data[count].guest_amount+'" data-date_reservation="'+data[count].date_reservation+'" data-menu_own="'+data[count].menu_own+'" data-bezahlstatus="'+data[count].bezahlstatus+'" class="check_box"></td>';
html += '<td>'+data[count].email+'</td>';
html += (guest_amount == "") ? "<td>0</td>" : "<td>"+guest_amount+"</td>";
html += '<td>'+data[count].date_reservation+'</td>';
html += '<td>'+data[count].menu_own+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? "<td>nicht bezahlt</td>" : "<td>"+data[count].bezahlstatus+"</td>";
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('click', '.check_box', function() {
var html = '';
var guest_amount = $(this).data('guest_amount');
var bezahlstatus = $(this).data('bezahlstatus');
if(this.checked)
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box" checked></td>';
html += '<td><input type="text" name="email[]" class="form-control" value="'+$(this).data("email")+'" /></td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td><select name="menu_own[]" id="menu_own_'+$(this).attr('id')+'" class="form-control"><option value="Hauptmenü 1">Hauptmenü 1</option><option value="Hauptmenü 2">Hauptmenü 2</option><option value="Hauptmenü 3">Hauptmenü 3</option></select></td>';
html += '<td><select name="bezahlstatus[]" id="bezahlstatus_'+$(this).attr('id')+'" class="form-control"><option value="">nicht bezahlt</option><option value="bezahlt">bezahlt</option></select></td><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" />';
}
else
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box"></td>';
html += '<td>'+$(this).data('email')+'</td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td>'+$(this).data('menu_own')+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? '<td>nicht bezahlt</td>' :
'<td>'+bezahlstatus+'</td>';
}
$(this).closest('tr').html(html);
$('#menu_own_'+$(this).attr('id')+'').val($(this).data('menu_own'));
$('#bezahlstatus_'+$(this).attr('id')+'').val($(this).data('bezahlstatus'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"update.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Der Eintrag wurde erfolgreich aktualisiert.');
fetch_data();
}
});
}
});
});
I tried to find the mistake in the code section where the checkbox is checked but I am unable to find it. Could someone please help me?
Thank you in advance!

How to add HTML form fields based on JSON response data

I have a HTML form for products which contains initially a fields group (for the product components) of 2 rows and can add rows using a button with an onClick event to a js function addRow(). the code is:
<?php
$arrayNumber = 0;
for($x = 1; $x < 3; $x++) { ?>
<tr id="editRow<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">
<td style="padding-left:20px;padding-right: 20px;">
<div class="form-group">
<select class="form-control" name="editRawName[]" id="editRawName<?php echo $x; ?>" onchange="getRawData(<?php echo $x; ?>)">
<option value="">~~SELECT~~</option>
<?php
$rawSql = "SELECT * FROM raw_material WHERE status = 1";
$rawData = $connect->query($rawSql);
while($row = $rawData->fetch_array()) {
echo "<option value='".$row['raw_id']."' id='changeRaw".$row['raw_id']."'>".$row['raw_name']."</option>";
} // /while
?>
</select>
</div>
</td>
<td style="padding-left:20px;">
<div class="form-group">
<input type="number" name="editQuantity[]" id="editQuantity<?php echo $x; ?>" autocomplete="off" class="form-control" min="1"/>
</div>
</td>
<td>
<button class="btn btn-default removeRawRowBtn" type="button" id="removeRawRowBtn" onclick="removeRawRow(<?php echo $x; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
<?php
$arrayNumber++;
} // /for?>
Now, to edit a product I use a js function editProduct() to fetch the selected product data and return it as a JSON response to fill the product form fields. The editProduct function code part to grab and fill product fields is:
function editProduct(productId = null) {
if(productId) {
$("#productId").remove();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$('.div-loading').removeClass('div-hide');
$('.div-result').addClass('div-hide');
$.ajax({
url: 'action.php',
type: 'post',
data: {productId: productId},
dataType: 'json',
success:function(response) {
$('.div-loading').addClass('div-hide');
$('.div-result').removeClass('div-hide');
$(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.product_id+'" />');
// product name
$("#editProductName").val(response.product_name);
// category name
$("#editCategoryName").val(response.categories_id);
// quantity
$("#editProductQuantity").val(response.quantity);
// product unit
$("#editProductUnit").val(response.product_unit);
// sales margin
$("#editSalesMargin").val(response.sales_margin);
// status
$("#editProductStatus").val(response.status);
// Get the product components count
var totalComponents = response.total_components;
// Loop for every component
// Set the fields id that will contains the data
// Fill the fields with data
for (var x = 0; x<totalComponents; x++){
var idrawn = "#editRawName"+x.toString();
var idrawq = "#editQuantity"+x.toString();
var resri = "raw_id_"+x.toString();
var resqu = "rp_quantity_"+x.toString();
$(idrawn).val(response[resri]);
$(idrawq).val(response[resqu]);
}
The problem is: In case of a product with a total components of more than 2, I need to add rows to be filled with the components data.
First, I tried to launch the addRow() function before the last for loop in the editProduct function like this (didn't work):
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ addRow(); }
}
Then, I tried to simulate the click of the Add Component button that launch the addRow function using the solution posted here: How to simulate a click with JavaScript? and change the above code like this:
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ eventFire(document.getElementById('addRowBtn'), 'click'); }
}
but still no luck.
The code of addRow function is:
function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#rawTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;
if(tableLength > 0) {
tableRow = $("#rawTable tbody tr:last").attr('id');
arrayNumber = $("#rawTable tbody tr:last").attr('class');
count = tableRow.substring(3);
count = Number(count) + 1;
arrayNumber = Number(arrayNumber) + 1;
} else {
// no table row
count = 1;
arrayNumber = 0;
}
$.ajax({
url: 'action1.php',
type: 'post',
dataType: 'json',
success:function(response) {
$("#addRowBtn").button("reset");
var tr = '<tr id="row'+count+'" class="'+arrayNumber+'">'+
'<td style="padding-left:20px;padding-right: 20px;">'+
'<div class="form-group">'+
'<select class="form-control" name="rawName[]" id="rawName'+count+'" onchange="getRawData('+count+')" >'+
'<option value="">~~SELECT~~</option>';
$.each(response, function(index, value) {
tr += '<option value="'+value[0]+'">'+value[1]+'</option>';
});
tr += '</select>'+
'</div>'+
'</td>'+
'<td style="padding-left:20px;">'+
'<div class="form-group">'+
'<input type="number" name="quantity[]" id="quantity'+count+'" autocomplete="off" class="form-control" min="1" />'+
'</div>'+
'</td>'+
'<td>'+
'<button class="btn btn-default removeRawRowBtn" type="button" onclick="removeRawRow('+count+')"><i class="glyphicon glyphicon-trash"></i></button>'+
'</td>'+
'</tr>';
if(tableLength > 0) {
$("#rawTable tbody tr:last").after(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+count+'" />';
} else {
$("#rawTable tbody").append(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+tableLength+'" />';
}
$("#rawTable").after(comp);
}
});}
I was wandering if there is a way to get the result that I need.

How to disable value in select option when it already selected by another select option

So, i have a simple form like this:
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
<script type="text/javascript">
var count = 0;
$(function(){
$('#add_field').click(function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv"><?php $noInv = $this->modelku->select_inv() ?> <?php foreach($noInv->result() as $inv){ ?> <option value="<?php echo $inv->no_inv ?>"><?php echo $inv->no_inv ?></option><?php } ?></select><br>' );
});
});
</script>
</div>
When i click the button the field will regenerate select option, and the value is from database
select_inv function:
public function select_inv()
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where("kondisi = 'Ada' ");
$query = $this->db->get();
return $query;
}
My Question: How can i disable value in select option when it already selected by another select option?
Try this if this is what you need.
i just created a sample dropdown and in my jquery i trigger the event change using the class of all select option then i will get the value of the select and id. after getting the value i check the val if it is empty or not if not empty then i will use the each function for all the select and get their id attribute so i can compare it with the id of the select and if their id is not the same then i will disabled the option with the same value of the selected dropdown.
and i use focus event for getting the previous value so i can reset whether the user change the value of the selected option.
$( document ).ready(function() {
$('body').on('click','#add_field',function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv select_alternate"> <option value="">select</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select><br></select><br>' );
});
var count =0;
var previous;
var selectedData = [];
$('body').on('click','.select_alternate',function(){
previous = this.value;
});
$('body').on('change','.select_alternate',function(){
var val = this.value;
var id = $(this).attr('id');
if(val != ''){
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + val + '"]').prop('disabled',true);
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
selectedData.splice($.inArray(val, selectedData),1);
}else{
selectedData.push(val);
}
});
}else{
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
</div>

Cloned elements' events corresponding to all elements in the form

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

Categories

Resources