jQuery calculating price if many elements on same page using same IDs? - javascript

I have 12 of these forms on a page on each product. It allows someone to enter a quantity and have it calculate the price, but doesn't yet work. The new price should replace what's in the orderprice class div.
<form action="" method="post">
<input type="number" id="amount-<?php echo $productId; ?>" class="orderamount" name="amount" value="1" min="1" max="2000" maxlength="4" />
<input type="hidden" name="product" value="<?php echo $productId; ?>" readonly="readonly" disabled="disabled" />
<div id="price-<?php echo $productId; ?>" class="orderprice">
<?php
echo html_entity_decode($currencyAlignCode) . round($productPrice * $currencyMultiplier, 2);
?>
</div>
<input type="submit" class="addcart" value="" name="order" />
</form>
I want to take the value of amount-<?php echo $productId; ?>, and automatically calculate the price by multiplying that value by $productPrice and again by $currencyMultiplier, and then add html_entity_decode($currencyAlignCode) in front of it.
I know how to do that if there were only 1 form on the page and I didn't need to account for <?php echo $productId; ?>. This is how I would do it for an individual form, but how can I do it for several? And each price would only grab the quantity from the associated input box?
$(document).ready(function() {
$("#amount").bind('click keyup', function(event) {
var amount = $("#amount").val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = amount * productPrice * currencyMultiplier;
$("#price").html('currencyCode' + totalPrice);
});
});
This code will only do it for 1 product. I want the input from each to show in the respective price box.
Sorry if it's not clear, it was kind of hard to explain.

Maybe something like this? Use multiple selectors or grab the selectors that start with something.
<input type="number" id="amount-<?php echo $productId; ?>" productPrice="<?php echo $productPrice; ?>" ...
$("[id^=amount]").each(function(index){
$(this).bind("click key up", function(){
var amount = $(this).val();
var productPrice = $(this).attr('productPrice');
...
});
});
https://api.jquery.com/each/
http://api.jquery.com/attribute-starts-with-selector/

I ended up doing some extensive Googling and coming up with the solution.
I use attr to grab the id based on the changed class.
$(document).ready(function() {
$(".orderamount").bind('click keyup', function(event) {
var productId = $(this).attr('id');
var setId = productId.substring(7);
var amount = $('#amount-' + setId).val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = round(amount * productPrice * currencyMultiplier, 2);
$('#price-' + setId).html('currencyCode' + totalPrice);
});
});

Related

My interaction between PHP and JavaScript is not working . What can i do to solve this?

I am echoing in the screen the (id,name,city) from MySQL.
But the problem and the challenge is inserting the values from MySQl into some inputs.
I am using the code:
verificar_id($pdo);
function verificar_id($pdo){
if(isset($_POST['verificar']) && isset($_POST['id_cliente'])){
session_start();
$id_cliente = $_POST['id_cliente'];
$sql= $pdo->prepare("SELECT * FROM `clientes` where `id`=?");
$sql->execute(array($id_cliente));
$info = $sql->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($info);
echo "</pre>";
foreach ($info as $key => $value) {
$_SESSION['id'] = $value['id'];
$_SESSION['nome'] = $value['nome'];
$_SESSION['cidade'] = $value['cidade'];
}
}
}
?>
<script type='text/javascript'>
var nome = document.getElementById('id').value = "<?php echo $_SESSION['id'] ?>"
var nome = document.getElementById('nome').value = "<?php echo $_SESSION['nome'];?>"
var nome = document.getElementById('cidade').value = "<?php echo $_SESSION['cidade'];?
>"
</script>
And My HTML:
<body>
<form method="post" id="form">
<input type="number" name="id_cliente">
<input type="submit" name="verificar">
</form>
<input type="text" name="id" id="id">
<input type="text" name="nome" id="nome">
<input type="text" name="sobrenome" id="cidade">
</body>
And this is the result:
How you can see the result is almost exactly what i wanted: The only problem in all this is the browser is not doing what should do. Of some how, the browser is understanding that this a Js code(and inside the code, it is appearing the same result tha the "print_r", but is not running and i don't know how to solve this.
Someone can help me to solve this problem? Or solve this or show another way to me get the result? Pls.
Maybe another way to insert the values into a input.

Calculating final total after taking store credit into account

So I've done my order form differently now and I'm trying to calculate the final total based on how much store credit a user has. So for example if they had £100 credit and the total comes to £50 then it would just take away £50 from the total and then the user would be left with £50 credit. Then as well if the total came to £500 then taking into account the user's credit the total would come to £400 and the user would be left with £0 credit.
The final total is priced by taking the user's store credit into account
I'm having some difficulty calculating the final total, so this is my order form at the moment:
<form action='' method='post' align = "center">
<h2>Purchase</h2>
<p>Return to website</p>
<p><label>Name</label><br />
<input type='text' name='name' required ></p>
<p><label>Email</label><br />
<input type='text' name='email' required ></p>
<p><label>Number</label><br />
<input type='text' name='number' required ></p>
<p><label>Address</label><br />
<input type='text' name='address' required ></p>
<p><label>Town</label><br />
<input type='text' name='town' required ></p>
<p><label>Postcode</label><br />
<input type='text' name='postcode' required ></p>
<p><label>County</label><br />
<input type='text' name='county' ></p>
<p><label>Product</label><br />
<input type='text' name='product' readonly value='<?php echo $row['product'];?>'></p>
<p><label>Price</label><br />
<input type='text' name='price' readonly value='<?php echo $row['price'];?>'></p>
<p><label>Amount</label><br />
<input type="text" id="amount" name="amount" oninput="calc()" onkeypress="return isNumber(event)" />
<p>Price : <b>£<span name="totalPrice" id="totalPrice" size="8"></span></b></p>
<input type ="text" value="" name="shopTotal" id="shopTotal" />
<input type="text" value="" id="minusCredit" name="minusCredit"/>
<p>Delivery is £4.99</p>
<p><input type='submit' name='submit' value='Submit Order'></p>
and this is the script I have in place at the moment to try calculate the final total:
<script>
function calc()
{
var amount = document.getElementById("amount").value;
<?php
//calculate the discount
$price = $row['price'];
$deliv = 4.99;
$money = $_SESSION['money'];
if ($money > $price) {
$discount = $price;
} else {
$discount = 0;
}
echo $discount;
?>
//calculate final cost
var totalBefore = <?php echo $price ?> * amount + <?php echo $deliv?>
var discount = <?php echo $discount ?> * amount + <?php echo $deliv?>
var totalAfter = <?php echo $price ?> * amount + <?php echo $deliv?> - discount
document.getElementById("totalPrice").innerHTML = totalAfter.toFixed(2)
document.getElementById("shopTotal").value = totalAfter.toFixed(2)
document.getElementById("minusCredit").value = discount.toFixed(2)
}
</script>
The issue with this is that no matter what the total comes to it, the discount will always take it to £0 no matter how much store credit the user has.
The amount of store credit they have is based on this value:
$money = $_SESSION['money'];
The issue with I just to $discount = $money - $price; is that if the total was only £10 and the user had store credit then $discount would then equal £90 so the final total would become £80.
What I'm trying to do is something like if the $money variable is greater than the price + delivery then the final would just be 0 and then I would update the database table to take away from the user's store credit. Or if the the price + delivery total is greater than the $money variable then final total would be the price + deliver minus the store credit the user has.
I'm hoping this now makes sense
How can I fix this?
Okay so after playing about with it I've managed to get it to work. Might not be the most elegant solution but it works.
My calculation script is now like so:
function calc()
{
var amount = document.getElementById("amount").value;
<?php
//calculate the discount
$price = $row['price'];
$deliv = 4.99;
$money = $_SESSION['money'];
$discountTotal = $money - $price;
$discount = min($discountTotal, $price);
echo $discount;
?>
//calculate final cost
var totalBefore = <?php echo $price ?> * amount + <?php echo $deliv?>
var discount;
var totalAfter;
if (totalBefore < <?php echo $money ?>) {
discount = <?php echo $discount ?> * amount + <?php echo $deliv?>;
}
if (totalBefore > <?php echo $money?>) {
var discountCalculate = <?php echo $price ?> * amount + <?php echo $deliv - $money?> ;
discount = totalBefore - discountCalculate;
}
var totalAfter = <?php echo $price ?> * amount + <?php echo $deliv?> - discount
document.getElementById("totalPrice").innerHTML = totalAfter.toFixed(2)
document.getElementById("shopTotal").value = totalAfter.toFixed(2)
document.getElementById("minusCredit").value = discount.toFixed(2)
}
</script>
The script checks to see if total before before taking into account store credit is bigger or less than the amount of store credit the user has.
If it is less then the total will be 0 and the amount taken off will be whatever the price was.
If it is more then the script will first calculate how much the total would be from the total before - the amount of store credit the user has.
The discount value is now the total before price - the value just calculated

jQuery event won't fire on HTML form submit

I'm sorry if this question has already been asked but all the solutions I've tried haven't worked for me. What I want it to do is trigger some jQuery code when the form element is submitted.
Here's my code.
JS:
$(document).ready(function() {
$('form').bind('submit', function() {
alert('hi');
var word10 = <?php echo $word10; ?>;
var word20 = <?php echo $word20; ?>;
var word1Txt = <?php echo $word1Txt; ?>;
var word2Txt = <?php echo $word2Txt; ?>;
$('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
$('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
});
});
HTML:
<form class="form-inline" method="post">
<input class="form-control" type="text" placeholder="First Word" name="word1" autofocus>
<input class="form-control" type="text" placeholder="Second Word" name="word2" autofocus>
<input class="btn btn-primary form-submit" type="submit" value="Compare">
</form>
Use .on() or .submit() instead and if your vars are supposed to be strings, quote them:
$(document).ready(function() {
$('form').on('submit', function() {
alert('hi');
var word10 = '<?php echo $word10; ?>';
var word20 = '<?php echo $word20; ?>';
var word1Txt = '<?php echo $word1Txt; ?>';
var word2Txt = '<?php echo $word2Txt; ?>';
$('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
$('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
});
});

Set value of input element using javascript and get the value using php

Here I have a form and input element:
cart.php
<form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post">
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$payableamount = 0;$totalsavings = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<input tpe="text" name="quantxt[]" id="quantxt" value="<?php echo $qty = $row['quantity']; ?>" onkeyup="showsubmit(<?php echo $row['cart_id'] ?>,<?php echo $row['product_id'] ?>)">
<input type="text" name="s1" id="s1" value=""/>
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
</table>
</form>
and the javascript is:
<script>
function showsubmit(id,prodid)
{
alert(id);
alert(prodid);
document.getElementById("sub_"+id).style.visibility ="visible";
document.getElementById("s1").value = prodid;
f = document.getElementById("s1").value;
alert("product id is:"+f);
}
</script>
when i am accessign the value of s1 element in cart2.php it gives nothing.
on next page s1 has no value,while i am expecting the value that is updated using javascript
$prod_id = $_POST['s1'];
echo "product id of clickable product is:".$prod_id."<br>";
this line:
<input type="text" name="s1" id="s1" value=""/>
is inside a loop. can you make sure that the loop only has one row returning? because if not, then you're creating multiple elements with same id which javascript can not catch properly. id is supposed to be unique. in the case of multiple same ids it'll catch the first match and stop.

Ajax to submit form generated dynamically by PHP do-while loop

I have an evaluation bar(progress bar generated by javascript), users can select a value and click to submit it. The issue is that I'm using PHP to generate the evaluation bars dynamically (using a do-while loop).
I can't figure out how to setup AJAX to recognized and submit any of the forms. Now it's submitting only the first one, even though I submit any of others.
My PHP code:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form3")) {
$insertSQL = sprintf("INSERT INTO tblpersonalidad (idUser, idPost, intEvaluacion, dateFecha) VALUES (%s,%s,%s,%s)",
GetSQLValueString($_POST['idUser'], "int"),
GetSQLValueString($_POST['idPost'], "int"),
GetSQLValueString($_POST['intEvaluacion'], "int"),
GetSQLValueString($_POST['dateFecha'], "timestamp"),
);
mysql_select_db($database_conexionproject_poll, $conexionproject_poll);
$Result1 = mysql_query($insertSQL, $conexionproject_poll) or die(mysql_error());
$insertGoTo = "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
do {
<form id="form3" name="form3">
<div class="progress-user">
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
<script>
$('.progress-user').on('mousemove', function (e) {
var self = this;
var offset = $(self).offset();
var width = $(self).width();
var relX = Math.round(10 * (e.pageX - offset.left)/width) * 10;
setBarRating(self, relX);
$(self).siblings('.mi-input').val(relX);
});
$("#form3").submit(function(a) {
var url = "<?php echo $editFormAction; ?>"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $('#form3').serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
$('.progress-user').click(function() {
$("#form3").submit();
});
var setBarRating = function (self, percentage) {
$(self).find('.progress-bar-success-user span.rating').text(percentage + '%');
if (percentage <= 50) {
$(self).find('.progress-bar-danger-user').width(percentage + '%');
$(self).find('.progress-bar-warning-user').width(0);
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 50 && percentage <= 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width((percentage - 50) + '%');
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width('30%');
$(self).find('.progress-bar-success-user').width((percentage - 80) + '%');
}
};
</script>
I'll really appreciate any help. I haven't could realized what is the modification to the AJAX + PHP code. Many thanks for your time.
You’re generating several forms with id=”form3”. You’re also listening to $(“form3”).submit(). You’re submitting those forms by listening clicks to ‘.progress-user’:
$('.progress-user').click(function() { $("#form3").submit(); });
So, not matter wich .progress-user do you click on, the first #form3 will be the form submitted.
You should generate unique id’s to your forms and bars when creating them inside the loop. I.E;
$i = 0;
do {
<form id="<?php echo 'form' . $i ?>" name="<?php echo 'form' . $i ?>" class="progress-form">
<div class="progress-user" id="<?php 'progress-user' . $i; ?>" data-numer="<?php echo $i; ?>" >
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
$i++; //dont forget this :-)
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
Now you have several forms with its own unique id and several progress bars with its unique id and a data-number attribute. Also, the dinamically generated form have that 'progress-form' class.
So now you can listen to clicks on progress bars like before, then caching the data-number of that element:
$('.progress-user').click(function() {
var formNumber = $(this).attr('data-number');
$("#form" + fromNumber).submit();
});
This way, you can be sure the form being submitted is the one whose progress-bar was clicked. Now you should also modify your submit listener:
$('.progress-form').submit(function(e){
var url = "<?php echo $editFormAction; ?>";
var data = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault();
});
So now you're serializing and sending only the form whose progress bar was clicked, and not the first '#form3' in the document.
Hope this helps.

Categories