I was getting values in due to for each it was repeating same values
----------------------------------------------
<script type="text/javascript">
$(document).ready(function(){
var i=0;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select name='job_id"+i+"' class='form-control'><option value=''>Select the Job</option><?php
$mysql="select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id."'";
$result1 = mysql_query($mysql) or die(mysql_error());
while($roww = mysql_fetch_array($result1)){
$sql="select * from `ca_job_type` where `jtype_id`= '".$roww['job_type']."'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$row1['jtype_id'].' selected>'.$roww['job_id'].'-'.$row1['job_type_name'].'</option>';
} ?></select></td><td><input name='sac_hsc_code"+i+"' type='text' placeholder='description' class='form-control input-md' /> </td><td><input id='i"+i+"' type='text' placeholder='SAC/HSC Code' class='form-control input-md' ></td><td><select id='employee"+i+"' name='tax_id"+i+"' class='form-control'><option value=''>Please select</option><?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?></select></td><td class='appendData'></td><td><input name='amount"+i+"' type='text' class='form-control amt' id='amount"+i+"' class='form-control input-md' style='text-align: right;' ></td><td><input name='store"+i+"' type='hidden' id='store"+i+"' class='form-control input-md' style='text-align: right;' ></td>"
);
$("#employee"+i).change(function() {
var length = i;
var tax_id = $(this).find(":selected").val();
var dataString = 'tax_id='+ tax_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getEmployee.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
var employee = [employeeData];
----------I think I was getting the error because of this forEach ---------------------------
employeeData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.tax_type+'</td>';
data+= '<td align="right">'+item.tax_Percent+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
}
}
});
});
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
Same value was repeating in all places. I attached a screenshot for reference. Please help if anybody knows. Thanks in advance
try using following way using for loop
for(var i = 0 ;i <employeeData.length;i++){
$('.appendData').append('<tr><td colspan="4"></td><td align="right">'+employeeData[i].tax_type+'</td><td align="right">'+employeeData[i].tax_Percent+'</td></tr>')
}
If you are sure that your var employeeData has the good value, you can try this maybe :
// new empty data value
var data = "";
// you add one row each time you loop
$.each(employeeData, function(item) {
data += '<tr>';
data += '<td colspan="4"> </td>';
data += '<td align="right">'+item.tax_type+'</td>';
data += '<td align="right">'+item.tax_Percent+'</td>';
data +='</tr>';
});
// when it's over, you append your data where you want.
$('.appendData').append(data);
// An other idea could be to create a "container" div and do :
$('#mycontainer').html(data);
Is it what you are looking for?
Related
i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});
I'm trying to get the id from append table and use it in arithmetic.
Here's the modal where i append the table and its in php
<tbody>
<tr class="item-row" id="item-row" onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' id='productUse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='productMsrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;' id='cost'><textarea rows='4' cols='10' name='Dealerphp' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td</td></tr>";
}
?>
</tbody>
here's the append javascript.
<script type="text/javascript">
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea class="productid" id="prc" value="'+ value +'</textarea></td><td class="item-name"><textarea class="productuse" id="productuse" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea class="description" id="description" value= "' + value2 +' </textarea></td><td class="item-name"><textarea class="msrp" id="msrp" value= "' + value3 + ' </textarea> </td><td class="item-name"><textarea class="cost" name="cost" id="'+ value4 + ' </textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty"></textarea></td><td class="item-name"><textarea id="price" class="price" name="price" disabled></textarea></td></tr>');
console.log(value4);
}));
});
});
</script>
and here's the arithmetic javascript to get the id, multiply to the column of qty and get the total.
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("₱" ,"") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
got it
function update_price() {
var row = $(this).parents('tr');
var a , w = 0;
var a = row.find('.cost').val().replace(/\,/g,'');
var w = row.find('.qty').val().replace(/\,/g,'');
var price = Number(a) * Number(w);
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
I have to append data one by one by clicking button
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><select id='myselect" + i + "' name='job_id[]" + i + "' class='form-control'><option value=''>Select the Job</option><?php
$mysql = "select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id.
"'"; $result1 = mysql_query($mysql) or die(mysql_error());
while ($roww = mysql_fetch_array($result1)) {
$sql = "select * from `ca_job_type` where `jtype_id`= '".$roww['job_type'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$roww['job_id'].
' selected>'.$roww['job_id'].
'-'.$row1['job_type_name'].
'</option>';
} ? > < /select></td > < td > < input name = 'invoice_description[]"+i+"'
type = 'text'
placeholder = 'invoice_description'
class = 'form-control input-md'
id = 'invoice_description' / > < /td><td><input name='sac_hsc_code[]"+i+"' type='text' placeholder='sac_hsc_code' class='form-control input-md'id='sac_hsc_code' / > < /td><td><select id='employee' name='tax_id[]"+i+"' class='form-control'><option value=''>Please select</option > <?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?> < /select></td > < td > < input name = 'amount[]"+i+"'
type = 'text'
placeholder = 'amount'
class = 'form-control input-md' / > < /td>"
);
Above source which I have posted was multiple input type up to that working but after selecting drop-down of id='myselect' for first list it was showing the values if press (+) button above value get cleared and showing last data alone but I need the values of first row and second row.
$(document).ready(function() {
$('#myselect' + i).change(function() {
var job_id = $(this).find(":selected").val();
var dataString = 'job_id=' + job_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getjob.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
$('.appendData').empty();
if (employeeData) {
$("#dvPassport").show();
$("#dvPassport1").hide();
var myselect = [employeeData];
employeeData.forEach(function(item) {
var data = '<tr>';
data += '<td>' + item.job_id + '</td>';
data += '<td>' + item.disburse_Date + '</td>';
data += '<td align="right">' + item.approved_amount + '</td>';
data += '</tr>';
$('.appendData').append(data);
});
} else {
$("#dvPassport").hide();
$("#dvPassport1").show();
} //else
}
});
});
});
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
Please click here to get clear view
In the above picture if I have selected dropdown two values showing and I am pressing the + button and selecting second drop-down first values getting cleared and showing second value what I have selected in the last dropdown. but I need the values of the first drop-down and second drop down.Please help me if anyone faces this problem .Thanks in advance.
i am not quit sure what you are trying to achieve but you forgot some ticks in for the value in the dropdowns, which might solve your problem
change
echo '<option value='.$roww['job_id'].' selected>'.$roww['job_id'].
to
echo '<option value="'.$roww['job_id'].'" selected>'.$roww['job_id'].
and
echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>';
to
echo '<option value="'.$rows['tax_id'].'" selected>'.$rows['tax_type'].'</option>';
beside that
you should really consider formating your code well, it is very hard to read and understand and therefore very hard to debug
try to divorce your source, try to not mix php, html and javascript. it is possible to use it that way, but it also is a huge error source and very hard to maintain
use the mysqli functions instead of mysql -> MySQL Improved Extension
I need to fill all matching records in a table after inserting id in textbox. But currently I am getting only one record.
php
<?php
$id=$_POST['userID'];
$db_host = 'jo\SQL2005';
$db_username = 'jo';
$db_password = '123321';
$db_name = 'db_test2';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
echo json_encode($json);
exit;
?>
javaScript
function getname()
{
var id=$("#userID").val(); // get the id from textbox
$.ajax({
type:"post",
dataType:"json",
data:"userID="+id,
url:"address_json_data.php",
success:function(json)
{
$("table.imagetable").
append("<tr><td>" + json.user_id + "</td><td>" +
json.street + "</td></tr>");
}
});
}
html
<input name="userID" id="userID" onChange="getname()" type="text" />
<table border='1'class="imagetable">
<tr><th>id</th><th>email</th></tr>
</table>
Any Help Very Thanks
replace this code:
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
with this:
$query=mssql_query("select * from address where user_id='$id'");
while($result=mssql_fetch_assoc($query))
{
$json[]= array(
'id'=>$result['id'],
'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],
'Phone_number'=>$result['Phone_number']
);
}
And in your javascript:
success:function(json)
{
var str = '';
for(var x in json)
{
str += "<tr>";
str += "<td>" + json[x].user_id + "</td>";
str += "<td>" +json[x].street + "</td></tr>";
}
$("table.imagetable").append(str);
}
Good day!
I'm doing a Dynamic table which you can add/remove row, and I'm using select2 to search Items on the database via ajax and its working well at the moment, then I want to add another button ("add new item") to my select2's input box. It was also working but when I add another row, the previous rows will have 2 (add new item) buttons on it, and when I add another row something weird is happening on my input box then.
Without adding new rows
After adding new rows
Here is my code:
$(document).ready(function() {
addRow();
});
addRow.js
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
function addRow(){
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemId"+rowArrayId+"' name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemId"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
$(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
Please Help me find solution for this one, been trying to solve this on my own but I cant get it working. Any suggestions, answers and comments would really be appreciated. Thank you very much and have a good day!
In my case I just added this function
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
}