I have created a page, it has a select box which is used for filtering the results in a table below it. The select box is using ajax to filter results.The table which is loaded after ajax call has a button in one column, on its click a div should be added in the page. The onclick for this button was working fine when the table was static with static button to add div, now the table is being loaded through ajax the button doesn't work, it doesn't add the div that it was adding before. Can someone point out the problem please, I am a beginner in jquery and ajax
here is my code:
(function ( $ ) {
$(document).ready(function(){
var itemsArr = [];
$(".btn-add").on("click",function() {
var $row = $(this).closest("tr"); // Find the row
var $text = $row.find(".this-name").text(); // Find the text
// Let's test it out
$('#col2').append('<div class="item"><p>'+$text+'</p>X</div>');
itemsArr.push($text);
//alert(itemsArr);
console.log("added");
$("#items").val(JSON.stringify(itemsArr));
});
function getAll(){
$.ajax
({
url: 'http://asp4.walnut-labs.com/getproducts.php',
data: 'action=showAll',
contentType :'application/json',
cache: false,
success: function(r)
{
$("#col1").html(r);
}
});
}
getAll();
// function to get all records from table
// code to get all records from table via select box
$("#brands").change(function()
{
var id = $(this).find(":selected").val();
var dataString = 'action='+ id;
$.ajax
({
url: 'http://asp4.walnut-labs.com/getproducts.php',
data: dataString,
contentType :'application/json',
cache: false,
success: function(r)
{
$("#col1").html(r);
}
});
});
});
$(document).on('click','.delete-button', function(e){
e.preventDefault();
//alert('yes');
$(this).closest('.item').remove();
});
}( jQuery ));
HTML is :
<tbody>
<tr bgcolor="#238efb" color="white">
<td style="text-align: center; color: #fff;"><strong>ID</strong></td>
<td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Item Code</strong></td>
<td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Item Name</strong></td>
<td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Brand</strong></td>
<td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Button</strong></td>
</tr>
<?php
while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
$id = $row['id'];
$name = $row['code'];
$level = $row['name'];
$number = $row['brand'];
?><tr>
<td class="this-id" style="text-align: center;"><?php echo $id;?></td>
<td class="this-name" style="text-align: left; padding-left: 15px;"><?php echo $name;?></td>
<td style="text-align: left; padding-left: 15px;"><?php echo $level;?></td>
<td style="text-align: left; padding-left: 15px;"><?php echo $number;?></td>
<td style="text-align: left; padding-left: 15px;"><button class="btn-add">Add Item</button></td>
</tr><?php
}
mysql_close($con);
?>
</tbody>
</table>
For selectbox that triggers AJAX:
<div class="searchbar">
<select name="brands" id="brands">
<option value="showAll" selected="selected">Show All Products</option>
<?php $querybrand = "SELECT DISTINCT brand FROM q1h27_data ";
$commentsbrand = mysql_query($querybrand);
while($row = mysql_fetch_array($commentsbrand, MYSQL_ASSOC))
{
//print_r($row['brand']);?>
<option value="<?php echo $row['brand']; ?>"><?php echo $row['brand']; ?></option>
<?php } ?>
</select>
</div>
Use the following:
$(document).ready(function(){
var itemsArr = [];
$(document).on('click','.btn-add',function() {
// code goes here.....
});
}
Related
im adding data in the db and at the same time it is shown to the same page through ajax when add button is clicked. now i want to show data in ascending order adn as well as in descending order also. data is shown on add click but when i clicked ascending button, data is not shown. same is the thing with descending button.
add.php file
<section class="my-5">
<div class="py-5">
<h2 class="text-center">Information</h2>
</div>
<div class="w-50 m-auto">
<form method="POST" onsubmit="event.preventDefault();onSubmit();">
<div class="form-group">
<label>Title</label>
<input type="text" name="title" id="title" autocomplete="off" class="form-control" required="">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" name="description" id="description" autocomplete="off" class="form-control" required="">
</div>
<br>
<button type="submit" class="btn btn-success" id="fetch" name="dataadd" onclick="addRecord();">Add</button>
</div>
</form>
</div>
</section>
<section align="center">
<form>
<button type="submit" class="btn btn-success" name="ascd" onclick="ascdRecord();">Ascending</button>
<button type="submit" class="btn btn-success" name="desc" onclick="descRecord();">Descending</button>
</form>
</section>
<br>
<br>
<div align="center">
<h2 id="records">Show All Data</h2>
</div>
</div>
The javascript functions
<script type="text/javascript">
function addRecord()
{
var title = $('#title').val();
var description = $('#description').val();
$.ajax({
url: "data.php",
type: "POST",
data: {
title: title,
description: description
},
success: function(data, status)
{
readRecords();
}
});
}
function readRecords()
{
var readrecord = "readrecord";
$.ajax({
url: "data.php",
type: "POST",
data: {readrecord: readrecord},
success: function(data, status)
{
$('#records').html(data);
}
});
}
function DeleteUser(deleteid)
{
var conf = confirm("you want to delete ?");
if (conf==true) {
$.ajax({
url: "data.php",
type: "POST",
data: {deleteid: deleteid},
success: function(data, status)
{
readRecords();
}
});
}
}
function ascdRecord()
{
$("#ascd").click(function(){
$.ajax({
url: "data.php",
type: "POST",
dataType: "html",
success: function(data)
{
$('#records').html(data);
}
});
});
}
</script>
data.php file
if(isset($_POST['ascd']))
{
echo "<div class='result'>";
$data = '<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
';
$fetch_query = "select * from app.add order by title";
$fetch_run = mysqli_query($con, $fetch_query);
if(mysqli_num_rows($fetch_run) > 0)
{
while($row = mysqli_fetch_array($fetch_run))
{
$data .= '<tr style="border: 1px solid black; padding: 8px; text-align: center">
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
<td>
<button onclick="DeleteUser('.$row['id'].')">Delete</button>
</td>
</tr>';
}
}
$data .= '</table>';
echo $data;
echo "</div>";
}
if(isset($_POST['readrecord']))
{
echo "<div class='result'>";
$data = '<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
';
$fetch_query = "select * from app.add";
$fetch_run = mysqli_query($con, $fetch_query);
if(mysqli_num_rows($fetch_run) > 0)
{
while($row = mysqli_fetch_array($fetch_run))
{
$data .= '<tr style="border: 1px solid black; padding: 8px; text-align: center">
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
<td>
<button onclick="DeleteUser('.$row['id'].')">Delete</button>
</td>
</tr>';
}
}
$data .= '</table>';
echo $data;
echo "</div>";
}
if(isset($_POST['title']) && isset($_POST['description']))
{
$insert_query = "insert into app.add (title, description) values('$title','$description')";
$query_run = mysqli_query($con, $insert_query);
}
You can modify each function to send a new parameter - I chose task but that it not important. The value is changed for each request type as you will see in the javascript. The PHP code can look for and then fork logic based upon this single POST variable.
FYI: Blindly extracting variables in PHP using extract opens the door to various attacks - only use that with caution once you have sanitised the POST array ~ perhaps using filter_input_array as a start and a whitelist of acceptable names/types.
function addRecord(){
var title = $('#title').val();
var description = $('#description').val();
$.ajax({
url: "data.php",
type: "POST",
data: {
task:'add',
title:title,
description:description
},
success: function(data, status)
{
readRecords();
}
});
}
function readRecords(){
$.ajax({
url: "data.php",
type: "POST",
data: {
task:'read'
},
success: function(data, status)
{
$('#records').html(data);
}
});
}
function DeleteUser(deleteid){
if( !confirm("you want to delete?") )return false;
$.ajax({
url: "data.php",
type: "POST",
data: {
task:'delete',
deleteid:deleteid
},
success: function(data, status)
{
readRecords();
}
});
}
function ascdRecord(e){
$.ajax({
url: "data.php",
type: "POST",
data:{
task:'ascd'
},
dataType: "html",
success: function(data)
{
$('#records').html(data);
}
});
}
/* presume similar for dscdRecord */
function descRecord(e){
$.ajax({
url: "data.php",
type: "POST",
data:{
task:'dscd'
},
dataType: "html",
success: function(data)
{
$('#records').html(data);
}
});
}
Data.php
if( isset( $_POST['task'] ) ){
switch( $_POST['task'] ){
case 'add':
if(isset(
$_POST['title'],
$_POST['description']
)){
# this is prone to SQL injection - you should use a `Prepared statement`
/*
$insert_query = "insert into app.add () values('$title','$description')";
$query_run = mysqli_query($con, $insert_query);
*/
$sql='insert into `app`.`add` ( `title`, `description` ) values (?,?)';
$stmt=$con->prepare($sql);
$stmt->bind_param('ss',$_POST['title'],$_POST['description']);
$stmt->execute();
$stmt->close();
}
break;
case 'delete':
break;
case 'read':
$data = '
<div class="result">
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>';
$fetch_query = "select * from app.add";
$fetch_run = mysqli_query($con, $fetch_query);
if(mysqli_num_rows($fetch_run) > 0)
{
while($row = mysqli_fetch_array($fetch_run))
{
$data .= '
<tr style="border: 1px solid black; padding: 8px; text-align: center">
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
<td>
<button onclick="DeleteUser('.$row['id'].')">Delete</button>
</td>
</tr>';
}
}
$data .= '
</table>
</div>';
header('Content-Type: text/html');
exit( $data );
break;
case 'ascd':
$data = '
<div class="result">
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>';
$fetch_query = "select * from app.add order by title";
$fetch_run = mysqli_query($con, $fetch_query);
if(mysqli_num_rows($fetch_run) > 0)
{
while($row = mysqli_fetch_array($fetch_run))
{
$data .= '
<tr style="border: 1px solid black; padding: 8px; text-align: center">
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['title'].'</td>
<td style="border: 1px solid black; padding: 8px; text-align: center">'.$row['description'].'</td>
<td>
<button onclick="DeleteUser('.$row['id'].')">Delete</button>
</td>
</tr>';
}
}
$data .= '
</table>
</div>';
header('Content-Type: text/html');
exit($data);
break;
case 'dscd':
break;
}
}
I have two tables in my webpage, each being populated with a php while loop.
My first table gets all its data outputted but my second while loop only outputs as many fields as the first one.
My second while loop is not nested within the other one, they are both independent from each other.
When i check the console I see that my second while loops seems to have outputted my data but when I click on my button to display the entire column, only 3 values appear instead of all of them
This is what is shown when I click on TEAM TASK
https://imgur.com/4FCu1dX
This is what is shown when I click on MY TASK
https://imgur.com/q1F6sgx
I also noticed that whether I click on MYTASK or TEAM TASK their are two rows from MYTASK that are always shown.
I Initially had both while loops within the same table but then moved them to each fill there own table but this issue still occurs.
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-my" onclick="myTasks()"><p id="myTasks">MY TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableMY)){ $task1234=$row8[1];
?>
<tr id="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
<table border='0' style="float:left; width:20%; height: 500px; border-radius: 5px; display: block;" bgcolor="#2B4353">
<thead>
<tr>
<td bgcolor="#2B4353" border="0" valign="top" align="right">
<div class="messages-header-team" onclick="teamTasks()"><p id="teamTasks">TEAM TASKS</p></div></td>
</tr>
</thead>
<tbody>
<?php
while($row8 = mysqli_fetch_array($TableTeam)){ $task1234=$row8[1];
?>
<tr id="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
<?php if ($row8[0]=='HIGH')
{$statuscss= 'taskHigh';}
elseif ($row8[0]== 'MEDIUM')
{$statuscss= 'taskMedium ';}
else{ $statuscss= 'taskLow';}
echo 'class="',$statuscss,'"';?> style="margin-left: 30px;">OD_<?php echo $task1234?></p></td></tr>
<?php }?>
</tbody>
</table>
My php
require('server.php');
session_start();
$email=$_SESSION['email'];
$sqli="Select URLDomain from Admin.Users where Email = ?";
$stmt =mysqli_prepare($link,$sqli);
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$useremail=mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($useremail);
$DBdomain=$row[0];
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where urlDomain=?");
mysqli_stmt_bind_param($stmt,"s",$DBdomain );
mysqli_stmt_execute($stmt);
$TableTeam=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
mysqli_select_db($link,"Universe");
$stmt = mysqli_prepare($link,"Select Priority,TaskNumber from Task where TaskOwner=?");
mysqli_stmt_bind_param($stmt,"s",$email );
mysqli_stmt_execute($stmt);
$TableMY=mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
Here is my Javascript
<script>
function messagesTab() {
document.getElementById("task-message").style.display = "block";
}
</script>
<script>
function myTasks() {
document.getElementById("myTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "none";
document.getElementById("my").style.display = "block";
document.getElementById("messageDisplay").style.display = "block";
document.getElementById("myTaskView").style.display = "none";
}
</script>
<script>
function teamTasks() {
document.getElementById("teamTasks").style.color = "#1FAC96";
document.getElementById("teamTasks").style.underline = "#1FAC96";
document.getElementById("myTasks").style.color = "#FFFFFF";
document.getElementById("team").style.display = "block";
document.getElementById("my").style.display = "none";
document.getElementById("myTaskView").style.display = "none";
document.getElementById("messageDisplay").style.display = "block";
}
</script>
<script>
function myTaskView(Task_Number) {
$.ajax({
url:'messages_select.php',
type:'POST',
data:{Task_Number:Task_Number},
success:function(data){
$('#myTaskView').html(data);
document.getElementById("myTaskView").style.display = 'block';
document.getElementById("messageDisplay").style.display = 'none';
}
});
}
</script>
<script>
var main = function() {
$('form').submit(function(event) {
var $input = $(event.target).find('input');
var comment = $input.val();
if (comment != "") {
var user = '<i class="fas fa-user-circle"></i>';
var userInfo = $(user).text(' '+'nataliekoly#mail.usf.edu'+' | '+'01/31/19'+' | '+'3:45 PM')
var comment = $('<li>').text(comment);
comment.prependTo('#comments');
userInfo.prependTo('#comments');
$input.val("");
}
return false;
});
}
$(document).ready(main);
</script>
IDs need to be unique, you can't have id="my" and id="team" on each row of the table. Use classes instead:
<tr class="my" style="display: block;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
and
<tr class="team" style="display:none;" onclick="myTaskView('<?php echo $task1234?>')"><td bgcolor="#2B4353" border="0" valign="top" colspan="3"><p
Then you need to loop over them:
document.querySelectorAll(".my").forEach(el => el.style.display = "block");
I am trying to get the result from "headline" and "content" to show up one at a time and then fade in and out to the next result in a loop. Currently, it shows all the results at once and the fades in and out and then show all the results again. Any idea on how to get them to show one at a time TIA
<html>
<head>
<style>
#table1{/*table aspects and design */
border:1px solid #FFFFFF;
background:#FFFFFF;
display:none;
width: 60%;
margin-left: auto;
margin-right: auto;
}
th{/*align table headers*/
text-align:center;
}
td,th{
border:1px solid #FFFFFF;
text-align:center;
}
</style>
</head>
<table id="table1" cellpadding="5" cellspacing="1" width="50%">
<? if ($query=$pdo->prepare("SELECT * FROM `Announcements_Current`"))
{
/* select all information from the table and take it into the page */
$query->execute();
while ($result = $query->fetch(PDO::FETCH_ASSOC)){
$head = $result['headline'];/*puts result of headline from table into variable*/
$content = $result['content'];
/*puts result of content from table into variable*/
echo /* echo the table to display announcements*/'
<tr>
<th>
<h1>
'.$head.'
</h1>
</th>
</tr>
<tr>
<td>
<font size="4">
'.$content.'
</font>
</td>
</tr>';
}
}
?>
</table> <!--end of table-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
/* define script for jquery*/
for (var i = 0; i < 500; i++) {/* for loop to fade in and out the announcements*/
$(document).ready(function() {/*function to fade table in and out*/
$('#table1').fadeIn(2000);
$('#table1').delay(5000);
$('#table1').fadeOut(2000);
}
)};
</script>
You need to use a timer in your Javascript to show each row separately.
$(document).ready(function() {
var cur_row = 0;
setInterval(function() {
$("#table1 tr").fadeOut(2000).eq(cur_row).fadeIn(2000);
cur_row = (cur_row + 1) % $("table1 tr").length;
}, 5000);
});
I am creating a shopping cart using session which is working, Now I am making the quantity part I mean User can increase the product quantity and decrease the quantity and according to that the total amount will display on screen without refresh the page.
I just need when the user clicked on Plus sign then the amount will change as per quantity.
<?php echo $product['qty'];?> I am getting this value from my session
Any idea how can I do this?
I also added same code in https://jsfiddle.net/Narendra2015/uLx0912t/
/*increase the product qty*/
$(".ddd").on("click", function () {
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quntity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$input.val(newVal);
});
Second code after suggested Mr.A. Iglesias
$('a.ddd').click(function() {
var $productContainer = $(this).closest('div.sp-quantity');
var $pro_list = $(this).closest('tr.pro-list');
var productPrice = parseInt($pro_list.find('span.price_cal').text());
var $quantityInput = $productContainer.find('input.quntity-input');
var newQuantity = parseInt($quantityInput.val()) + parseInt($(this).data('multi'));
if (newQuantity>= 0) {
// Refresh quantity input.
$quantityInput.val(newQuantity);
// Refresh total div.
var currentChange = productPrice*parseInt($(this).data('multi'));
var total = parseInt($('div#total').text());
$('div#total').text(total + currentChange);
}
});
Css
.sp-quantity {
width:124px;
height:42px;
float: left;
}
.sp-minus {
width:40px;
height:40px;
border:1px solid #e1e1e1;
float:left;
text-align:center;
}
.sp-input {
width:40px;
height:40px;
border:1px solid #e1e1e1;
border-left:0px solid black;
float:left;
}
.sp-plus {
width:40px;
height:40px;
border:1px solid #e1e1e1;
border-left:0px solid #e1e1e1;
float:left;
text-align:center;
}
.sp-input input {
width:30px;
height:34px;
text-align:center;
border: none;
}
.sp-input input:focus {
border:1px solid #e1e1e1;
border: none;
}
.sp-minus a, .sp-plus a {
display: block;
width: 100%;
height: 100%;
padding-top: 5px;
}
HTMl
<?php if(!empty($_SESSION['products'])):
foreach($_SESSION['products'] as $key=>$product):?>
<tbody>
<tr class="pro-list">
<td>
<div class="ordered-product cf">
<div class="pro-img">
<img src="admin/images/products/<?php echo $product['p_images'];?>" alt=" prodcut image">
</div>
<div class="pro-detail-name">
<h3><?php echo $product['p_name'];?></h3>
</div>
<?php
$p_delete=$product['p_id'];
//$decrypted_delete_id = decryptIt($p_delete);
$encrypted_user_id = encryptIt($p_delete);
$delete_product_id=urlencode($encrypted_user_id);
?>
<i class="fa fa-times" aria-hidden="true"></i>
</div>
</td>
<td>£<span id="price_cal"><?php echo $product['p_currentprice'];?></span></td>
<td>
<div class="sp-quantity">
<div class="sp-minus fff"><a class="ddd" href="javascript:void(0)" data-multi="-1">-</a></div>
<div class="sp-input">
<input type="text" class="quntity-input" value="<?php echo $product['qty'];?>" />
</div>
<div class="sp-plus fff"><a class="ddd" href="javascript:void(0)" data-multi="1">+</a></div>
</div>
</td>
<?php $single_total = $product['qty']*$product['p_currentprice'];?>
<td class='total_amount' data-price='£<?php echo $single_total;?>'>£<?php echo $single_total;?></td>
</tr>
<?php $total = $total+$single_total;
$_SESSION['total_cost']=$total;
endforeach;?>
<tr class="pro-list">
<td></td>
<td></td>
<td><span>Subtotal</span></td>
<td>£<?php $_SESSION['total_cost']=$total;echo $total;?></td>
<!-- <td><span>Shiping Cost</span></td>
<td><i class="fa fa-fighter-jet" aria-hidden="true"></i>£<?php echo $total;?></td> -->
</tr>
<tr class="pro-list">
<td></td>
<td></td>
<td><span>Total Cost</span></td>
<td>£<?php echo $total;?></td>
</tr>
</tbody>
<?php endif;?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
for total amount, I added this in the script.
// Refresh total div.
var subtotal_amount = subtotal_amount+lineTotal;
$pro_list.find('td.subtotal_amount').data('price','£'+subtotal_amount).html('£'+subtotal_amount);
HTML inside <tr class="pro-list">
<td class='subtotal_amount' data-price='£<?php echo $total;?>'>£<?php echo $total;?></td>
First you can put your product price and the total amount inside of div with a class or id, to make them easy to select, something like...
<?php $product=10;?>
<div class="sp-quantity">
<div class="product-price"><?=$product?></div>
<div class="sp-minus fff"><a class="ddd" href="javascript:void(0)" data-multi="-1">-</a></div>
<div class="sp-input">
<input type="text" class="quntity-input" value="<?php echo $product['qty'];?>" />
</div>
<div class="sp-plus fff"><a class="ddd" href="javascript:void(0)" data-multi="1">+</a></div>
</div>
<?php
$single_total = $product['qty']*$product;
echo $total = $total + $single_total;
?>
<div id="total"><?=$total?></div>
Then, refresh its values anytime you change the quantity of a product...
$('a.ddd').click(function() {
var $productContainer = $(this).closest('div.sp-quantity');
var productPrice = parseInt($productContainer.find('div.product-price').text());
var $quantityInput = $productContainer.find('input.quntity-input');
var newQuantity = parseInt($quantityInput.val()) + parseInt($(this).data('multi'));
if (newQuantity>= 0) {
// Refresh quantity input.
$quantityInput.val(newQuantity);
// Refresh total div.
var currentChange = productPrice*parseInt($(this).data('multi'));
var total = parseInt($('div#total').text());
$('div#total').text(total + currentChange);
}
});
I hope it helps
I'm not sure to really understand, but the total amount corresponds to total price (depended on product's quantity), isn't it ?
If I'm right, I think the better way is to display the total amount in a 'div' tag (for example) containing an attribute 'data-total' with the product's price.
Then, in JS, you can access to attribute's data and update the total with the price and the quantity.
Something like that:
<div class='total_amount' data-price='<?php echo $product['price']?>' >
0
</div>
And then update your JS file as:
$(".ddd").on("click", function () {
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quntity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$input.val(newVal);
var price = $('.total_amount').data('price');
$('.total_amount').html(price * newVal);
});
Hope it will help you :)
PS: Sorry for my English, I'm French :P
I have in defi.php a form with the following AJAX call:
$('#def').submit(function (event) {
var data = $(this).serialize();
$.post('defidos.php', data)
.success(function (result) {
$('#dos').html(result);
})
.error(function () {
console.log('Error loading page');
})
return false;
});
defidos.php has the following table row which contains a check box:
<tr>
<td>
<input type="checkbox" name="seleccion[]" value="<?php echo $id_plantilla; ?>" />
</td>
<td>
<?php echo $faquerynm['cve_plaza']; ?>
</td>
<td>
<?php echo $desc_cat; ?>
</td>
<td>
<?php echo $faquerynm['tiempo']; ?>
</td>
<td>
<?php echo $faquerynm['situacion']; ?>
</td>
<td>
<?php echo $div_areal; ?>
</td>
</tr>
After the call the checkbox is not shown.
If I put the checkbox outside the table it shows correctly.
I solved the problem using css , creating the table with divs .
#container {
display: table;
}
#row {
display: table-row;
}
#left, #right, #middle {
display: table-cell;
text-align: center;
}
.titulos {
font-weight: bold;
}
With this the checkbox shows correctly