I'm using laravel and I want to sum two numbers and show it in my blade.
Logic
I have hidden input field which is holding my product price
I have drop-down options which users can select
When users select any of the options my product price should sum to
that option price and return the result as total to users.
Codes
<!--hidden field of product price-->
<input type="hidden" id="harga" name="harga" value="{{$product->price}}">
<!--div to show total price-->
<div id="totalPriceInTotal"></div>
<!--my options-->
<select name="attr[]" class="form-control">
<option value="">{{ __('Select') }}</option>
#foreach($optioncollection as $suboption)
<option value="{{$suboption->id}}">{{$suboption->title}} - {{ __('Rp') }} {{ number_format($suboption->price, 0) }}</option>
#endforeach
</select>
JavaScript:
<script>
$(document).ready(function() {
var optionprice = document.getElementById('harga').val();
$.ajax({
success:function(data) {
// var optionprice = $(#attr).val();
var shipingcost = parseFloat(data)+parseFloat(optionprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('<p>Cost: Rp '+nf.format(shipingcostnumber)+'</p>');
}
});
});
</script>
PS: I am aware that my JavaScript code is wrong, what I'd tried to do
here was to getting my hidden input value in my totalPriceInTotal
div which obviously was unsuccessful and then try to add my drop-down
values into it.
Questions
What should I change to get my hidden input value in my
totalPriceInTotal div when page loads?
How do I add my options value into it?
Note: for my options part i cannot add my options prices into value="" part because i need that value to be id for my cart so I added the price in options like {{ number_format($suboption->price, 0) }} probably i need help to remove texts around this price before i can actually sum it with my product price.
thanks in advance.
I advise giving the hidden field a data attribute, e.G
<input type="hidden" id="harga" name="harga" data-price="{{$product->price}}">
Then in JavaScript you can do this:
$('#harga').data('price');
You can do the same for the dropdown, although I do not fully comprehend what this does
{{$suboption->id}}">{{$suboption->title}} - {{ __('Rp') }} {{ number_format($suboption->price, 0) }}
You can then take both values and add them to each other, and then append them to the "totalPriceInTotal" div (which is a terrible name imho ^^)
If appending does not work, just use
$('#totalPriceInTotal').val() = '<p>Cost: Rp ' + calculatedPrice + '</p>';
At this point I am not sure what EXACTLY does not work for you, so if you need more help, please let me know!
SOLVED
So Ihad to add function in my controller in order to get my drop-down options prices and here is my final code I commented my parts for better understanding
<script>
$(document).ready(function() {
// if option is not selected shows product price
$('#totalPriceInTotal').empty();
var productprice = $('#harga').val();
var shipingcost = parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
// if option is selected will sum product price and option price
$('select[name="attr[]"]').on('change', function() {
var productprice = $('#harga').val();
var optionprice = $(this).val();
if(optionprice) {
$.ajax({
url: '{{ url('admin/getoptionprice') }}/'+encodeURI(optionprice),
type: "GET",
dataType: "json",
success:function(data) {
$('#totalPriceInTotal').empty();
var shipingcost = parseFloat(data)+parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
}else{
// if user decided to back to default and not using any option price will back to normal
$('#totalPriceInTotal').empty();
var productprice = $('#harga').val();
var shipingcost = parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
});
</script>
Hope this can help others.
Related
I want to calculate 2 options from different selects in HTML and display the result in an input field. The first select will fill from a mysql database, the second select will fill with 1 option that is the pair of the first. I want to multiply them and display the result in the last input field. Here is an example:
The table of the database the field are "id product"-id quantity price type
table view
Here is the result that i want: to display
When the user selects the quantity the corresponding value is going to be displayed to the next field.
After that in the last input field i want to calculate the previous selections
the user can only select the quantity and not the price
I made a select with php and made an array which is converted to javascript array object
<?php
$sth = $conn->prepare("SELECT quantity,price FROM eb_products_price WHERE product_id = 20");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$json_array = json_encode($result);
print_r($result);
With this code the only thing i can do is to display the quantity with a foreach
BUT the price will remain the last one and it wont change while i change the quantity.
I found a way to display the correct price but with javascript here is the code
<script>
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity= document.getElementById("quantity");
var price= document.getElementById("price");
var arrprice = quantity.options[quantity.selectedIndex].value;
while (price.options.length) {
price.remove(0);
}
var prices = arrayObjects[arrprice];
if (prices) {
var i;
for (i = 0; i < prices.length; i++) {
var price1 = new Option(prices[i], i);
price.options.add(price1);
}
}
}
</script>
Here is the calculate function that work without the last part of code:
calculate = function()
{
var quantity= document.getElementById('quantity').value;
var price= document.getElementById('price').value;
var number = parseFloat(quantity)*parseFloat(price);
var n = number.toFixed(2);
document.getElementById('result').value = n
}
To change a HTML-Element dynamically you need event Listeners like onChange example below:
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity = document.getElementById("quantity");
var factor = document.getElementById("factor"); // added
var price= document.getElementById("price");
// Fill dropdown (quantity)
while (quantity.options.length) {
quantity.remove(0);
}
// fill by key
for( var quantity_key in arrayObjects ) {
var quantity_option = new Option(
quantity_key,
quantity_key
);
quantity.options.add(quantity_option);
}
// onChange-Listener
quantity.onchange = () => {
factor.value = arrayObjects[quantity.value];
// look for factor by key in arrayObjects
price.value = Math.round(
quantity.value *arrayObjects[quantity.value]
);
};
}
products();
<select id='quantity'></select>
KG
<input type='text' id='factor' readonly="readonly">
<input type='text' id='price' readonly="readonly">
in javascript, to get the selected element (value) of a select, use :
var e = document.getElementById("quantity");
var quantity= e.options[e.selectedIndex].text;
Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...
I wrote a question show hide jquery table rows for imported xml data about how to show hide some table rows using jquery, and now using the same question, I want to know how to force the first 5 elements to show up. I used the following code in my example:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('event').each(function(){
var Col0 = $(this).find('title').text();
var Col1 = $(this).find('country').text();
var Col2 = $(this).find('date').text();
var Col3 = $(this).find('time').text();
var Col4 = $(this).find('course').text();
var Col5 = $(this).find('topic').text();
var Col6 = $(this).find('pre-course').text();
$('<tr></tr>').html('<th>'+Col0+'</th><td>'+Col1+'</td><td>'+Col2+'</td><td>'+Col3+'</td><td>'+Col4+'</td><td>'+Col5+'</td><td>'+Col6+'</td>').appendTo('#test');
initalizeTable();
});
}
});
});
and html:
<table id="test">
<tr><td></td><th>country</th>
<th>Date</th><th>time</th>
<th>course</th><th>topic</th>
<th>pre-course</th></tr>
</table>
And then I used the javascript to display only some display options:
function initalizeTable() {
function show (min, max) {
var $table = $('#test'), $rows = $table.find('tbody tr');
min = min ? min - 1 : 0;
max = max ? max : $rows.length;
$rows.hide().slice(min, max).show();
return false;
}
$('#limit').bind('change', function () {
show(0, this.value);
});
}
I had to wrap the above code to include it in the first code so that it loads directly after the data being imported to html.
and here is the html I used to change the display option manually:
<select id="limit">
<option value="0">None</option>
<option value="5"selected>5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="" >All</option>
</select>
now everything works great, except that the data are imported in full table where I want to force showing only the first 5 rows in the table.
any idea how to do that??
Thanks
You could call show(0,5); at the end of your initalizeTable() function.
Or trigger your select's change event just after you bind it so that it automatically picks up the maximum value from the drop-down's currently selected option:
$('#limit').bind('change', function () {
show(0, this.value);
}).trigger('change');
Just to give you a better idea I am making a computer customization page with a bunch of dropdown lists
that display the Part name and have the PartID as the data value. I wish to append all the part name text values for all options excluding the currently selected option with the price difference between the price of this part and the currently selected one.
i.e:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
I do not have the price, so I would need to retrieve the price for all the option data values (PartID)
and return it as a json collection ({PartID, Price}) key value pairs as the page loads in Ajax call. I would only need to make one Ajax call and use this data for all onchange events for my dropdown list.
Then using Javascript/Jquery, for each option, using its data value (PartID) as key, find its price from the returned Json collection and append to the end of the non selected options text value the difference between its price and the currently selected options price. This will have to run every time (onchange) that a new option is selected.
Using ASP.NET MVC3/Razor
Here's what my dropdown list html looks like, I have about ten such dropdown lists:
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option value="3">Intel Core i7 950</option>
<option value="4">Intel Core i7 930</option>
</select>
Someone has now suggested I take the easier approach and simply add the cost to each option as additional attribute. In my view I have code as follows:
#Html.DropDownList("partIdAndCount[0].PartID", new SelectList(Model.Processor.Products, "ProductID", "Name"), "Select processor" )
I can add additional attributes but only to the select tag and not option?
new { datacost = Model.Processor.Products[0].ListPrice }
I know how to get at the text value of all the options/option and to change it entirely, but not how to append to it or use javascript to use the options data values to find their price in the json collection and then only append to the non selected options text values etc. Also no idea how initially gather all options data values and pass them in an ajax call to my action method that will return the json result.
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
$(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var text = $(this).attr("text");
$(this).find('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
Maybe it would be easier if you just included the price of each item in the option (inside of a data-cost attribute, or whatever), like this (just guessing on the prices):
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option data-cost="210" value="5">Intel Core i7 930</option>
<option data-cost="250" value="3">Intel Core i7 950</option>
<option data-cost="280" value="4">Intel Core i7 960</option>
</select>
Then use this script to update the options instead of needing to make numerous calls to your server to get more json data. Here is a demo.
$('select')
.find('option').each(function() {
// add spans to the option, done here because it doesn't
// seem to work if you include the span in the markup
$(this).append(' <span></span>');
}).end()
.change(function() {
var v, diff,
// get cost of selected option
sel = parseFloat($(this).find('option:selected').attr('data-cost'), 10) || 0;
// Add cost difference to option
$(this).find('option[data-cost]').each(function() {
v = parseFloat($(this).attr('data-cost'), 10);
diff = '(' + (sel > v ? '-' : '+') + ' $' + Math.abs(sel - v) + ')';
if (sel === v) {
diff = '';
}
$(this).find('span').html(diff);
});
})
// show values on init
.trigger('change');
Im trying to build a form that calculates a total price based on a series of drop down boxes with string values such as "This option costs £30" i know this is not ideal but im putting this together as a hack for an existing script
For the most part ive got it working however im not sure how to run the each function for each child of #productconfig
I can manually input each of the drop downs ids into an array and that makes the calculation but it would be good if it just worked with all the children of #productconfig
<code>
<div id="#productconfig">
<label>Model Type</label>
<select name="products[220][data][modeltype]" id="data-modeltype-220">
<option value="M-Type £500">M-Type £500</option>
<option value="P-Type £500">P-Type £500</option>
<option value="S-Type £500">S-Type £500</option>
</select>
</div>
</code>
<code>
$(document).ready(function() {
$("#productconfig").children().change(function () {
calculateoptions();
});
calculateoptions();
});
</code>
<code>
function calculateoptions() {
var arr = ["data-modeltype-220"];
var total = 0;
jQuery.each(arr, function () {
var str = $('#' + this).attr("value");
var poundsign = str.indexOf('£');
var poundsign = poundsign + 1;
var lengthofstr = str.length;
var shortstr = str.substr(poundsign, lengthofstr);
total = eval(total) + eval(shortstr);
});
$('#price').html("£" + total);
}
</code>
How about this:
function calculateoptions() {
var total = 0;
jQuery('#productconfig select').each(function () {
total += $(this).val().match(/£(\d+)/)[1];
});
$('#price').html("£" + total);
}
You can use:
$("#productconfig select").each(function(){...});
To select each drop down in the product config div.