Generate Total Price, multiple products on one page - php

I'm trying to generate the total price on a one page store.
I have different products on the same page laid out like this within a foreach:
<input type="hidden" name="price_<?=$product_id?>" value="<?=$product_price?>" />
<input type="text" name="<?=$product_id?>" value="" onchange="calculateTotal();" />
So, the first input is hidden and contains the price of the product. The second input contains the quantity, with the name set as the product_id. The only issue is that there can be multiple inputs on one page.
Which would be the best way to do it? Either using Javascript to calculate the price, or an Ajax post and using PHP to do the calculations.

why not use the new data attribute and skip the hidden price field? Something like this:
<input class='quantity' type="number" data-price="1.5" name="prod1" value="" />
<div class='subtotal'>0.00</div>
<input class='quantity' type="number" data-price="7" name="prod2" value="" />
<div class='subtotal'>0.00</div>
<div id='total'>0.00</div>
with this:
$('.quantity').on('change', function(){
var sub = $(this).val() * $(this).data('price');
$(this).next('div.subtotal').html(sub).data('sub',sub);
var tot=0;
$('.subtotal').each(function(){
tot+= $(this).data('sub');
});
$('div#total').html(tot);
});

Noting that using HTML to store a price variable is usually bad etiquette why not keep a running total of all prices? Something like
$running_total = $running_total+$product_price;
This would output the total of all products that have been cycled through. If I misinterpreted your question I'm sorry.
Storing prices as a an HTML entity to be passed via POST or GET leaves the variable open for manipulation by the end user.

Do it however you want. As long as you perform the calculation at checkout (again?) on the server.

Related

How to update a form field as you type in value into another field

Good Day,
I'm trying to create a form calculate (a currency converter), in which when you are typing in the value of amount in USD, the other field is updated immediately without clicking any submit button. I have been searching but haven't gotten an answer (maybe due to searching for the wrong keywords).
An Example
<html>
<form action="">
<input type="number" name="amountUSD" value="1"><br/>
<input type="number" name="amountNGN" value="">
</form>
</html>
What I want to achieve is when the page loads, automatically, the value of amountNGN field should be 365 and of I remove the value of amountUSD field or make the value 0, the 365 in amountNGN field should go away or become 0.
Which makes the calculation: value(amountNGN) = value(amountUSD) * 356; (just an illustration, not sure this language exist).
The value of amountNGN field updates on the fly. Please how can I use JavaScript/jQuery to do this
Thanks
I believe this is what you want:
function convertCurrency(value) {
// your calculation here
return (value * 356);
}
$('[name="amountUSD"]').on('change keyup', function() {
value = $(this).val();
$('[name="amountNGN"]').val(convertCurrency(value));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<input type="number" name="amountUSD" value="1"><br/>
<input type="number" name="amountNGN" value="">
</form>
If you want your server to do this work then use ajax (not recommended, but posible).
If you want to change it on client side JAVASCRIPT will do the job (but then is not a php question); I recommend using the onkeyup javascript event on the field you are working with referencing the one you want to change.

How to dynamically add input fields to a form

I'm currently working with Asset Management system. The company is spread through out different locations.
This system can return asset items to store again if these items are not in use.
What I want to do is return the item there are lots of items. So I have input fields like this:
<td><input type="text" name="asset_id[]"/></td>
<td><input type="text" name="batch_code[]"/></td>
<td><input type="text" name="description[]"/></td>
<td><input type="text" name="status[]"/></td>
// current condition of the item
I can't use these fields again and again, I don't know how many fields are required for each particular situation.
If I can give an option to the user to add input fields if he/she needs, how do I do this.
Here you can see something like that
http://jsfiddle.net/damian_silvera/ATzne/
Using JS/jQuery propably :
HTML :
Add Row
jQuery
$(document).ready(function(){
$("a#plus_row").click(function(){
$("table#form_table").append($("table#form_table").find('tr').get(0));
});
});

Duplicating form using JS and changing name data

If it's possible, I would like a general explanation of how I should go about this so I can try to tackle the problem directly myself. As is, I'm having trouble thinking of a solution.
I'm passing values from a form containing book information (ISBN, price, condition, etc.). It's been working very well with a single book. All of this form information is placed inside a div.
I recently implemented a simple JS 'duplicate' function that duplicates all of the form data in the div so users can add another book, or multiple other books. The problem seems to be that all the name values in the original div that I duplicate aren't changing, or aren't accepting that they should now contain multiple values.
How should I go about making each 'book' have it's own values? Should the names in each input be arrays (e.g. book[0]['price']) and then every time another div is added the JS changes the name (e.g. book[1]['price'])?
I'm asking this because I'm really not sure if that would work, and I'd rather hear a more experienced opinion before changing the (already functional) way in which the form is working. If more information is needed please ask and I'll provide.
The names that you assign in html forms can be arrays. eg price[]
<input type="text" name="price[]">
Now if you have multiple form inputs with the name 'price[]', it doesn't matter. In fact this makes it useful.
Now in php you can easily access each name using
$_POST['price'][$i] //where $i is 0,1,2,3.....
Basically what this does is that it creates an array for 'price' under the $_POST array.
You can easily iterate over $i and get values for other fields too.
This answers your statement "or aren't accepting that they should now contain multiple values."
<div id="book1">
<input type="text" name="price[]" id="price1" />
<input type="text" name="isbn[]" id="isbn1" />
</div>
Duplicate this and update the IDs only, using js(since each ID should be unique),
<div id="book2">
<input type="text" name="price[]" id="price2" />
<input type="text" name="isbn[]" id="isbn2" />
</div>
Now $_POST['price'] should give you the array of prices and each corresponding element of isbn should give you the isbn of that book
server side would be like,
$price = $_POST['price'];
$isbn = $_POST['isbn'];
foreach( $price as $key => $value ) {
echo "The price is ".$value." and isbn is ".$isbn[$key];
}
This is one way I would go..

How to make Multiple Forms more reliable?

I am looking for a neat solutions for the multiple Forms.
Have a look at the example screenshot:
There are three networks in the dropdown, AT&T, Verizon Wireless and T-Mobile.
I've selected 'AT&T' from the dropdown list and then 'Sale Type' radios appear.
T-Mobile network may have same Sale Type as 'AT&T' network but two extras Sale Type.
Majority of the text boxes from all the Sale Type are the same. For example:
Consumers will have 20 Fields and Business have 27 Fields (Extras Fields). Sim-Only will have less fields - 15 Fields (A few removed and new fields).
What is a good solution implement like this and DRY principle?
I have used jQuery with a lot of $('.name').hide(); $('.name').hide(); but it get real messy. Example:
$(".at&t_consumer_radio").click(function(){
showSaleType("at&t_consumer");
});
function showSaleType(type) {
if (type == "at&t_consumer") {
$('.name').hide();
$('.name').hide(); and so on..
}
}
When completing the form, then I use PHP to validate it.
Here's the Fiddle: http://jsfiddle.net/GvGoldmedal/FxEGP/
Your best bet is to create the following class tags:
.att, .verizon. , .tmobile, .consumer, .business, .sim
Then you can tag the fields based on when they need to be hidden. If a field is used for verison then it'd get a verizon class. If a field is bussiness type then it'd get the business class. Also add the "hide" class to any field that isn't ALWAYS showing.
Some Field:
<input type="text" class=" hide verizon att consumer" />
Another Field
<input type="text" class = " hide att business" />
Make sure to label every field. Also make sure your radio buttons and the options in your select have values that match the classes. And give your select and radio button a class of 'option', like so:
att
verizon
tmobile
<input type='radio' name='sale_type' class='option' value="business" />
<input type='radio' name='sale_type' class='option' value="consumer" />
<input type='radio' name='sale_type' class='option' value="consumer" />
.. and so on
Now for the Jquery:
//selectId is the ID of your select
// myform is the id of your form
$(".option").change(function()
{
// get the value of our select and option
carrier = $('#selectId option:selected').val();
sale_type = $('input[name=sale_type]:checked').val();
// Hide all fields that don't always show up.
$(".hide").hide();
//Show all fields that match our carrier and sale type
$(".hide").each(function(){
if($(this).hasClass(carrier) && $(this).hasClass(sale_type))
{
$(this).show();
}
});
});
There you have it. Anytime a new option is selected all the fields that aren't part of the form all the time will be hidden and the ones matching your carrier and sale type will then be shown. It will happen almost immediately and the user won't be able to tell the different. You can do some fading to make it look more smooth if you want. Also, if a field is visible for both verizon and att then just add both classes to that input. Let me know if you have any questions.
I'll try and get a Fiddle up showing exactly how to do it.
Hide all the fields that are only shown for specific choices e.g Business or sim free.
Like so
<input type="text" class="standard" />
<input type="text" class="business" style="display:none" />
<input type="text" class="simOnly" style="display:none" />
<input type="text" class="standard" />
<input type="text" class="business simOnly" style="display:none" />
Not sure i'm explaining this that well. :(
Then use jquery to just show the business ones if that option is chosen
$("#businessRadio").click(function(){
$('.business').show();
});
This way you aren't showing and hiding everything, just those inputs specific to each sale type

Get data from AJAX - How to

I have a script, that takes the value from two select tags, and then do a simple math multipy to calculate a price. The thing I need, but cannot figure out is, how to get that calculated price, and use it as an php variable in a POST form.
As the calculated price is dynamic, how can I archive this?
If you want to send that value directly to a PHP script, you can use the jQuery post method:
$.post("yourScript.php", { price: yourPriceVar }, function(data) {
//Success! Do something interesting
});
Alternatively, you could set the value of a hidden input element to your calculated value, so that it can be submitted along with the rest of your form:
$("#hiddenInput").val(yourPriceVar);
HTML:
<input type="hidden" id="hiddenInput" name="price" />
to set the calculated price in the form use :
document.FORMNAME.FIELDNAME.value = CALCULATED_VALUE;
or jquery style
$('input[name="FIELDNAME"]').value(CALCULATED_VALUE);
in your javascript.
in the form add an hidden field IE.
<input type="hidden" name="FIELDNAME" value="" />
if you are using $.ajax() or $.post(), simply append a new value to data parameter
if you are using common form submit, simply create a new input with the name attribute inside the form and set the calculated price to the value

Categories