how to update the price if quantity changed in cart - javascript

I am making the Review Cart & Checkout form. IF user want to change the quantity I want that if quantity is changed the price of it will be changed automatically.
Please help to adjust the code in the same JS of plus minus or separate.
Image is below of Review Cart & Checkout:
JS for Plus & Minus:
<script type="text/javascript">
function subtractQty(){
if(document.getElementById("number").value - 1 < 0)
return;
else
document.getElementById("number").value--;
}
</script>
HTML/PHP for plus minus:
<div class="quantity">
<input style="font-size:21px;" type="button" value="-" onclick='javascript: subtractQty();' class="">
<input id="number" type="number" value="<?php echo $qtyT; ?>" class="qty" name="picpac">
<input style="font-size:21px;" type="button" value="+" onclick='javascript: document.getElementById("number").value++;' class="plus">
</div>

You can follow two different strategies:
Invoke the server with an Ajax call, pass the quantity as parameter, calculate the total amount and return it.
Do all the operations in the front-end with jQuery and finally, pass the calculated value to store it.
In this link I have coded a quick example for the second one with your provided HTML. I just added a div for the calculated value
<div id="product1_total_price">0</div>
An input hidden for the product base price
<input type="hidden" id="product1_base_price" value="10">
And this jQuery code that do the magic:
$(document).ready(function() {
$(".operator").on('click',function() {
$("#product1_total_price").text($("#product1_base_price").val()*$("#number").val());
});
});
Hope it helps.
EDITED:
I add a (and update the JSFiddle link) suppossed Ajax call with jQuery, to update the DB on every quantity change:
$.ajax({
type: "GET",
data: {
idProduct: yourProductId,
quantity: $("#number").val(),
totalPrice: calculatedValue
},
url: "your-script.php",
success: function(json_response) {
if(json_response.result != 'SUCCESS') {
// Whatever
} else {
alert("Updated in DB");
});
})

Related

Post multiple data using Jquery/Ajax

I have this script below that sends only 1 value to the requested URL, but now I need to adjust it to accept 2, I couldn't find a way to do that.
Each checkbox is accompanied by an input hidden named #note, I need to pass this #note value (that's my order ID) together.
$('#importaNF').click(function(){
var checkbox = $('.import_checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"<?php echo base_url(); ?>adm/pedidos/importaNF",
method:"POST",
data:{checkbox_value:checkbox_value},
success:function()
{
$('.removeRow').fadeOut(1500);
}
})
}
else
{
alert('Select atleast one records');
}
}
My HTML
<div class="btn-group">
<input type="checkbox" class="import_checkbox" name="import_checkbox" value="<?= $registro->NUMERO ?>">
<input type="input" id="note" class="import_input" name="import_input" value="<?= $registro->FATURA ?>" style="visibility:hidden">
</div>
I may be misinterpretting, but you can just extract it like you did the checkbox value and add a second property to the data object:
data:{checkbox_value:checkbox_value, note_value: note_value},
Unless you mean you're trying to pass a second url parameter?

Can't write AJAX output variable in html form

I need to print inside a span tag ("estimation2") the result of a calculation (for now, just a simple sum of the two input boxes "SHm2" and "STm2"). I'm using an AJAX call to perform that task. It seems to work perfectly until the alert, which shows the correct result, but for some reasons I can't write that result in my html form. I've been looking around and tried several things, yet none of them worked. For instance I've tried using the write method but it didn't work or stuff like $("#estimation2").html(estimation); or
document.getElementById("estimation2").innerHTML = estimation;
The only way I managed to get it written was by using window.onload, but this generates the calculation when the page loads, and I don't want that. I only want the AJAX code to be triggered when I click on my button.
Also, just for info, the calculation is made in my django view, even though I don't think it's relevant here as it looks to work properly. I'm really lost here, could you please help?
Here is my html code and the AJAX script:
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
<script type="text/javascript">
function calculate () {
var SHm2 = $('#SHm2').val();
var STm2 = $('#STm2').val();
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
'SHm2':SHm2,
'STm2':STm2,
estimation: 'estimation',
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
</script>
so what you wanna do is run the JS after the HTML document has loaded, and as mentioned in the comment section you need to add type="button" to estimation button
HTML
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" type="button" onclick="calculate()" >Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
JS
$(document).ready(function() {
function calculate() {
var SHm2 = $("#SHm2").val();
var STm2 = $("#STm2").val();
$.ajax({
url: "/myApp/templates/homepage/",
type: "POST",
data: {
SHm2: SHm2,
STm2: STm2,
estimation: "estimation"
},
success: function(estimation) {
console.log(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
});

Django - Get "total" between two elements in HTML in real-time using a script

I know this question has being done here a lot but I looked and tried a lot of answers, wasn't able to retrieve what i need.
First, I pass a value from an item using django forms through the view. In this example, the template receive the value of "900" because I use the default {{form.price}} in HTML .
<input type="text" name="price" value="900" readonly="readonly" id="id_price">
Inside the same HTML i have a field to manually insert a quantity:
<input type="text" name="quantity" id="quantity">
And the final input to show to multiplication between those two
<input type="text" name="total" id="total">
As a script I used this (saw the answer in a question but i wasn't able to recreate the result in my "total" input)
SCRIPT
<script>
$(document).ready(function () {
$('').keyup(function () {
var multiplyAndShow = function () {
var val1 = parseFloat($('#id_price').val())
var val2 = parseFloat($('#quantity').val())
val3 = val1 * val2 || "Some Text"
$("#total").html(val3)
}
$("#id_price").keyup(function () { multiplyAndShow(); });
$("#quantity").keyup(function () { multiplyAndShow(); });
});
});
</script>
The script is not been used because when I set a quantity it doesn't make a thing in real time. The price value is readonly so i don't know if that's the problem.
I'm a newbie in javascript so any help will be appreciated
You should set the value of the total field, not the html. Change the following line
$("#total").html(val3)
to
$("#total").val(val3)
You should also change the $('') to $(document).

Newbie to Javascript: how to avoid sending data that have not changed?

I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

Check if fields are edited or not? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).
You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});
You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/
You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})

Categories