how to avoid refresh on a dropdown menu - javascript

when I use a drop down menu to select a quantity on a e-commerece based cart app, the drop down menu refresh to 1 after making the necesari changes on the variables.
the cart will change the quantity for the item and the price acordingly BUT will refresh itself and show 1 despite of the change on the rest of the variables.
here is my code:
<table class="table">
<tbody>
<tr>
<th></th>
<th>ITEM NAME</th>
<th>QUANTITY</th>
<th>UNIT PRICE</th>
<th>ITEMS TOTAL</th>
</tr>
<?php
foreach ($_SESSION["shopping_cart"] as $product){
?>
<tr>
<td>
<img src='<?php echo $product["image"]; ?>' width="90" height="80" />
</td>
<td><?php echo $product["name"]; ?><br />
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>"
/>
<input type='hidden' name='action' value="remove" />
<button type='submit' class='remove'>Remover</button>
</form>
</td>
<td>
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>"
/>
<input type='hidden' name='action' value="change" />
<select name='quantity' class='quantity' onChange="this.form.submit()">
<option <?php if($product["quantity"]==1) echo "selected";?>
value="1">1</option>
<option <?php if($product["quantity"]==2) echo "selected";?>
value="2">2</option>
<option <?php if($product["quantity"]==3) echo "selected";?>
value="3">3</option>
<option <?php if($product["quantity"]==4) echo "selected";?>
value="4">4</option>
<option <?php if($product["quantity"]==5) echo "selected";?>
value="5">5</option>
</select>
</form>
</td>
<td><?php echo "R$".$product["price"]; ?></td>
<td><?php echo "R$".$product["price"]*$product["quantity"]; ?></td>
</tr>
<?php
$total_price += ($product["price"]*$product["quantity"]);
}
?>
<tr>
<td id="td_tot" colspan="5" align="right">
<strong>TOTAL: <?php echo "R$".$total_price; ?></strong>
</td>
</tr>
</tbody>
</table>
and here is the head section:
$status="";
if (isset($_POST['action']) && $_POST['action']=="remove"){
if(!empty($_SESSION["shopping_cart"])) {
foreach($_SESSION["shopping_cart"] as $key => $value) {
if($_POST["code"] == $key){
unset($_SESSION["shopping_cart"][$key]);
$status = "<div class='box' style='color:red;'>
Produto Removido</div>";
}
if(empty($_SESSION["shopping_cart"]))
unset($_SESSION["shopping_cart"]);
}
}
}
if (isset($_POST['action']) && $_POST['action']=="change"){
foreach($_SESSION["shopping_cart"] as &$value){
if($value['code'] === $_POST["code"]){
$value['quantity'] = $_POST["quantity"];
break;
}
}
}
?>
I need to make it stay showing the last selection instead and after several tries and looking out on internet for an answer I only can rely on this comunity to help me.
thank you.

Replace onChange to onBlur.
It will not update unless click outside of select menu.

Because of Sending over the wire via HTTP, everything is a string, you have to use == instead of ===. See php operator here

Related

How to calculate the rest of the inputs

I have a table and I am calculating the difference of hours but only first row of the table calculates me. and I have a method where created a new table is if the date is different
$(document).ready(function() {
getHrs();
});
function getHrs()
{
hstart=$('#horaInicio').val();
hend=$('#horaTermino').val();
hr1 = (hstart).split(":");
hr2 = (hend).split(":");
hrstart=(hr1[0]);
minstart=(hr1[1]);
hrend=(hr2[0]);
minend=(hr2[1]);
totalstart=parseInt((hrstart*60)) + parseInt(minstart);
totalend=parseInt(hrend*60) + parseInt(minend);
rsthr=(totalstart - totalend);
total=(rsthr / 60).toFixed(2);
$('#resultado').val(total);
}
here my table, I create a table for each different day.
<?php if ($seguimientos): ?>
<?php $fechas = array();
foreach ($seguimientos as $seguimiento) {
$fechas[$seguimiento-> fecha][] = $seguimiento;
}
?>
<?php foreach ($fechas as $fecha): ?>
<table class="table table-hover">
<thead>
<tr>
<th>Fecha</th>
<th>Orden</th>
</tr>
</thead>
<?php foreach ($fecha as $seguimiento): ?>
<tr>
<td>
<?php echo $seguimiento-> fecha; ?>
</td>
<td>
<?php echo $seguimiento-> horaInicio; ?>
<input type="hidden" id="horaInicio" value=" echo $seguimiento-> horaInicio;">
</td>
<td>
<?php echo $seguimiento-> horaFin; ?>
<input type="hidden" id="horaInicio" value=" echo $seguimiento-> horaFin;">
</td>
<td>
<input type="text" id="resultado" value="" readonly>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
<?php endif; ?>
could be the problem the ID must be unique
Yes, that is the problem, try not to use id's but rather data attributes, or classes.
like this: <input type="hidden" data-start="horaInicio" value=" echo $seguimiento-> horaInicio;">
Then your selector becomes: hstart=$('[data-start]').val(); And the same for the other input.

submit product with session with add to cart

I have asked this question before. But it is updated with ajax and add to cart.
I have a form, which have some input fields and also have some check box fields. If any one fill fields and select some checkbox and then submit. Then some data according submission shows on another div.
Now If same person again fill that fields after first submission and select checkbox and submit. Then some data according submission shows on div. But it replace old submission content. I need all submission content, on div including all old submission content.
My code is:
<form class="reservation-form mb-0" action="" method="post" novalidate autocomplete="off">
<input name="name1" class="form-control required " type="text" placeholder="Enter Name" aria-required="true" required>
<input name="age" class="form-control required " type="number" placeholder="Enter Age" aria-required="true" required>
<select required id="selectarea" class="form-control" name="selectgender">
<option>Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<?php
$query1=mysql_query("select * from lab_location_package_rel where city_id='$selectcity1' AND area_id='$selectarea1' AND lab_id='$selectlab1'") or die (mysql_error());
while($value = mysql_fetch_array($query1)) {
$mrp=$value['mrp'];
$opp=$value['offer_price_perc'];
$package_id=$value['package_id'];
$per=$mrp*$opp/100;
$total=$mrp-$per;
$query2=mysql_query("select * from package_master where id='$package_id'") or die (mysql_error());
$value2 = mysql_fetch_array($query2);
?>
<li class="list-group-item">
<div class="checkbox">
<input type="checkbox" id="checkbox" name="namec[]" class="quantity<?php echo $value["id"]; ?>" value="<?php echo $value["id"]; ?>" />
<label for="checkbox">
<b>Package Name:</b> <?php $package_title1=$value2['package_title']; echo $package_title1;?> <br>
<b>MRP:</b> <strike><?php $mrp1=$value['mrp']; echo $mrp1; ?> </strike><br>
<b>Offer Price:</b> <?php $total1=$total; echo $total1; ?>
</label>
</div>
</li>
<?php }
?>
<input type="button" class="pull-right btn btn-warning" value="Submit" onclick="add_cart('<?php echo $value["id"]; ?>')">
</form>
<div class="cart_data">
</div>
My AJAX is:
<script>
function add_cart(p_id=""){
var quantity = $(".quantity"+p_id).val();
$.ajax({
type:"post",
url:"ajax_cart.php",
data:{action:'add',p_id:p_id,quantity:quantity},
success:function(result){
$('.cart_data').html(result);
}
});
}
function remove_cart(p_id){
//alert(p_id);
$.ajax({
type:"post",
url:"ajax_cart.php",
data:{action:'delete',p_id:p_id},
success:function(result){
$('.cart_data').html(result);
}
});
}
function empty_cart(){
$.ajax({
type:"post",
url:"ajax_cart.php",
data:{action:'empty'},
success:function(result){
$('.cart_data').html(result);
}
});
}
</script>
My ajax_cart.php is:
<?php
include"connection.php";
$action = $_REQUEST['action'];
#$p_id = trim($_REQUEST['p_id']);
//$_SESSION['product_cart'] = array();
if($action == 'add'){
#$quantity = $_REQUEST['quantity'];
if(!empty($p_id)){
$query1=mysql_query("select * from lab_location_package_rel where id='$p_id'") or die (mysql_error());
while($product_data = mysql_fetch_assoc($query1)) {
$mrp=$product_data['mrp'];
$opp=$product_data['offer_price_perc'];
$package_id=$product_data['package_id'];
$per=$mrp*$opp/100;
$total=$mrp-$per;
$query2=mysql_query("select * from package_master where id='$package_id'") or die (mysql_error());
$value2 = mysql_fetch_array($query2);
}
$product = array("p_id"=>$product_data['id'],"title"=>$value2['package_title'],"price"=>$product_data['mrp']*$quantity,"image"=>$product_data['offer_price_perc']);
if(isset($_SESSION['product_cart']) && !empty($_SESSION['product_cart']))
{
if(!array_key_exists($product_data['id'],$_SESSION['product_cart']))
{
$_SESSION['product_cart'][$product_data['id']] = $product;
}
}
else{
$_SESSION['product_cart'][$product_data['id']] = $product;
}
}
}
if($action == "delete"){
unset($_SESSION['product_cart'][$p_id]);
}
if($action == "empty"){
session_destroy();
}
?>
<div class="cart_data">
<?php
if(isset($_SESSION['product_cart'])){
foreach($_SESSION['product_cart'] as $data){
?>
<h5>Patient Details</h5>
<table class="table table-bordered">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th></th>
</tr>
<tr>
<?php //if(isset($_POST["submit"])==true)
{
?>
<td><?php //echo $_POST['name1']; ?></td>
<td><?php //echo $_POST['age']; ?></td>
<td><?php //echo $_POST['selectgender']; ?></td>
<td>Update</td>
</tr>
</tbody></table>
<br><br>
<h5>Package Details</h5>
<table class="table table-bordered">
<tbody>
<tr>
<th>Package</th>
<th>MRP</th>
<th>Offer Price</th>
<th></th>
</tr>
<tr>
<td><?php echo $data['title']; ?></td>
<td><strike><?php echo $data['price']; ?></strike></td>
<td><?php echo $data['image']; ?></td>
<td>Delete</td>
</tr>
<?php
}
?>
</tr>
</tbody></table>
<?php } } ?>
</div>

Live validation adding/updating data in a table php,ajax,javascript

Can help me to solve this?
I got a table and I have added 2 buttons to add or update information.
I wanna make a validation in the "description" field where **you can only write letters and less than 255 characters, and in the "name" field you can only write less than 50 characters. Anyway, I can not click on the button "save" or "add" respectively (the button is locked until everything is right).
Also, the page must show "In real time (before clicking the button) the errors in each field".
Here is my code, when adding new informationin the table:
<?php include('connect.php');
$error="";
if(isset($_POST['btnsave']))
{
$career_id=$_POST['carrera'];
$name=$_POST['txtname'];
$description=$_POST['txtdescription'];
$hourss=$_POST['txthours'];
if($_POST['txtid']=="0")
{
$a_sql=mysql_query("INSERT INTO subjects VALUES('','$career_id','$name','$description','$hourss')");
if($a_sql)
{
header("location:index.php");//
}
}else{
echo "Update";
}
}
$sqlm = mysql_query("SELECT * FROM careers");
$options = "";
while($result = mysql_fetch_array($sqlm)){
$options .= "<option value='".$result['id']."'>".$result['name']."</option>";
}
?>
<h2 align="center">ADD NEW SUBJECT</h2>
<form method="Post">
<table align="center">
<tr>
<td>Career:</td>
<td><select name='carrera'><?php echo $options; ?></select><input type="hidden" name="txtid" value="0" /></td>
</tr>
<tr>
<td>Name:</td>
<td><input type='text' name='txtname'/></td>
</tr>
<tr>
<td>Description:</td>
<td><input type='text' name='txtdesription'/></td>
</tr>
<tr>
<td>Hours:</td>
<td>
<select name='txthours'/>
<option <?php if($hourss=='1') echo 'selected' ; ?> value="2">2 (two)</option>
<option <?php if($hourss=='1') echo 'selected' ; ?> value="4">4 (our)</option>
<option <?php if($hourss=='1') echo 'selected' ; ?> value="6">6 (six)</option>
<option <?php if($hourss=='1') echo 'selected' ; ?> value="8">8 (eight)</option>
<option <?php if($hourss=='1') echo 'selected' ; ?> value="10">10 (ten)</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type='submit' value=save name='btnsave'/></td>
</tr>
</table>
</form>
And the another code updates the information in the table:
<?php include('connect.php');
$error="";
if(isset($_GET['edit']))
{
$ident=$_GET['iden'];
$row=mysql_query("SELECT * FROM subjects WHERE id=$ident");
$st_row=mysql_fetch_array($row);
}
?>
<h2 align="center">UPDATE SUBJECT</h2>
<form method="Post" action=''>
<table align="center">
<tr>
<td>Career:</td>
<td><input type='text' name='txtcarreras_id' value="<?PHP echo $st_row['career'] ?>"/></td>
</tr>
<tr>
<td>Name:</td>
<td><input type='text' name='txtnombre' value="<?PHP echo $st_row['name'] ?>"/></td>
</tr>
<tr>
<td>Description:</td>
<td><input type='text' name='txtdescripcion' value="<?PHP echo $st_row['description'] ?>"/></td>
</tr>
<tr>
<td>Hours:</td>
<td><input type='text' name='txtcarga_horaria' value="<?PHP echo $st_row['hours'] ?>"/></td>
</tr>
<tr>
<td></td>
<td><input type='submit' value="save" name='btnsave'/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['btnsave']))
{
$career_id=$_POST['txtcarreras_id'];
$name=$_POST['txtnombre'];
$description=$_POST['txtdescripcion'];
$hours=$_POST['txtcarga_horaria'];
$a_sql=mysql_query("UPDATE materias SET career='$career_id', name='$name', description='$description', hours='$hours' WHERE id='$ident'");
if($a_sql)
{
header("location:index.php");
}
}
?>
I know, there are a lot of ways to solve this but i wanna the very best method!
Hope you can help me :)
Thanks!
You can do that using Javascript. With Jquery or another library it's even easier.
Using jQuery:
$('input[name=txtname]').keyup(function() {
if ($(this).val().length < 50) {
// Do Error stuff here
} else {
// Remove error stuff here
}
});
If you have jQuery and use the above keyup event handler, it should display as you type.

How to get the value of selected checkbox in jquery and assign it to a json array?

I have a problem, I have little understanding about jquery that's why I am having a hard time with my code. I have a pagination of products. And there are checkboxes on it. And my simple goal is to disable the products if the checkboxes are selected. But I can't do it in one form because I have already another process in my form which is delete products if selected. That's why I am planning to create a form action in my jquery and pass all the product id from my checkbox to a json array. But how can I do that?
Here's a bit of my code
<form action="<?php echo $delete; ?>" method="post" enctype="multipart/form-data" id="form">
<table class="list">
<thead>
<tr>
<td width="1" style="text-align: center;"><input type="checkbox" onclick="$('input[name*=\'selected\']').attr('checked', this.checked);" /></td>
<td class="left"><?php echo $column_name; ?></td>
<td class="right"><?php echo $column_sort_order; ?></td>
<td class="left"><?php echo $column_status; ?></td>
<td class="right"><?php echo $column_action; ?></td>
</tr>
</thead>
<tbody>
<?php if ($categories) { ?>
<?php foreach ($categories as $category) { ?>
<tr>
<td style="text-align: center;"><?php if ($category['selected']) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $category['category_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $category['category_id']; ?>" />
<?php } ?></td>
<td class="left"><?php echo $category['name']; ?></td>
<td class="right"><?php echo $category['sort_order']; ?></td>
<td class="right"><?php echo ($category['status'] == 1 ? 'Enable' : 'Disable'); ?></td>
<td class="right"><?php foreach ($category['action'] as $action) { ?>
[ <?php echo $action['text']; ?> ]
<?php } ?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td class="center" colspan="4"><?php echo $text_no_results; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
<br />
<div align="right">
<select name="action_select">
<option value="enable">Enable Selected</option>
<option value="disable">Disable Selected</option>
</select>
<input type="button" class="button" id="update_status" value="Update Status" />
</div>
<br />
Here's my jquery sample
<script type="text/javascript">
$("#update_status").on('click', function(){
//how can I get the id of my checkboxes and assign it to a json array
//How can I create a form inside it?
});
</script>
That's all guys I hope you can understand my question. Thanks.
Otherwise you can use the below example code
<script>
$(document).ready(function()
{
$("input[type=checkbox]").click(function()
{
var categoryVals = [];
categoryVals.push('');
$('#Category_category :checked').each(function() {
categoryVals.push($(this).val());
});
$.ajax({
type:"POST",
url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
data:{'category': categoryVals},
success : function(response){
//code to do somethng if its success
}
});
}
}
</script>
try
$('input[name="selected[]"]:checked').each(function() {
console.log(this.value);
});
for more info :- use jQuery to get values of selected checkboxes
Try
var values = $('.list input[name="selected[]"]:checked').map(function () {
return this.value;
}).get();

How to pass DATA to PopUp Div in PHP?

I want to the pass ID value to POPUP DIV and update into table with status , suggest_text area with ID.
if I pass like this href="#pop1?id=<?php echo $row['id']; ?> The POPUP div is Not opening. so I dont know how to pass,so some one tell me that how can I pass in PHP or else in Javascript
Thanks in advance
<div class="widget-content">
<table class="table table-bordered table-striped data-table">
<thead>
<tr>
<th>S.No</th>
<th>Employee Name</th>
<th>Reason</th>
<th>Category</th>
<th>From</th>
<th>To</th>
<th>No Of Days</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result=mysql_query("select * from leave_request");
while($row=mysql_fetch_array($result))
{?>
<tr>
<td><?php echo $row['id'];?></td>
<td> <?php echo $row['emp_name'];?></td>
<td> <?php echo $row['reason'];?></td>
<td> <?php echo $row['category'];?></td>
<td><?php echo $row['from_date'];?></td>
<td><?php echo $row['to_date'];?></td>
<td><?php echo $row['no_of_days'];?></td>
<td>
Accept |
Reject |
Suggest </td>
<div id="pop1" class="pop-up">
<?php $suggest_id = $_GET['id']; ?>
<div class="popBox">
<div class="popScroll">
<form>
<textarea name="suggest" id="suggest" cols="60" rows="8" ></textarea>
<input type="text" name="id" value="<?php echo $suggest_id; ?>">
<input type="text" name="status" value="3">
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
<!-- popup content end here -->
</div>
<span>Back to links</span>
</div>
Back to links
</div>
</tr>
<?php }?>
</tbody>
</table>
</div>
As I see your popup div is in WHILE loop so you can get your id like this :-
Initialize a value say K = 1; and put this value to every popup
Suggest
Full Code :-
<?php
$result=mysql_query("select * from leave_request");
while($row=mysql_fetch_array($result))
{
$k =1;
?>
<tr>
<td><?php echo $row['id'];?></td>
<td> <?php echo $row['emp_name'];?></td>
<td> <?php echo $row['reason'];?></td>
<td> <?php echo $row['category'];?></td>
<td><?php echo $row['from_date'];?></td>
<td><?php echo $row['to_date'];?></td>
<td><?php echo $row['no_of_days'];?></td>
<td>
Accept |
Reject |
Suggest </td>
<div id="pop<?php echo $k; ?>" class="pop-up">
<div class="popBox">
<div class="popScroll">
<form>
<textarea name="suggest" id="suggest" cols="60" rows="8" ></textarea>
<input type="text" name="id" value="<?php echo $row['id']">
<input type="text" name="status" value="3">
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
<!-- popup content end here -->
</div>
<span>Back to links</span>
</div>
Back to links
</div>
</tr>
<?php
$k++;
}?>

Categories

Resources