Rails 3 calculate line totals with Ajax - ruby-on-rails

I have an invoice app. An invoice has line items. The line totals and grand total are calculated fine after you submit the invoice.
But I also would like to calculate the line totals and grand total BEFORE the invoice is submitted. For example, if you change the quantity, the line total and grand total should change.
I'm currently looking at different jQuery plugins. Maybe you have done something similar in the past. What would you recommend?

You don't need a plugin. jQuery alone is enough. What you'll want to do is add a handler in your application.js file for either .change() or .blur(). I recommend the latter. Then utilize HTML5's "data-" attributes to store the price as a plain Float so that jQuery can grab it and do some math to it.
invoice.html.erb
<div class="item">
<h3>Item #1</h3>
Price: <div class="price" data-price="10.20">$10.20 USD</div>
Qty: <input type="text" size="2" id="product_1_quantity" class="quantity" value="1">
</div><br /><br />
<div class="item">
<h3>Item #2</h3>
Price: <div class="price" data-price="3.50">$3.50 USD</div>
Qty: <input type="text" size="2" id="product_2_quantity" class="quantity" value="1">
</div><br /><br />
Total Price: <span id="total-price">input quantities</span>
application.js
function getTotal(quantities) {
var total = 0;
$.each(quantities, function() {
total += parseFloat($(this).closest('.item').find('.price').attr('data-price')) * parseInt($(this).val());
});
$("#total-price").html("$" + total + " USD");
}
$(document).ready(function() {
var quantity = $('.quantity');
getTotal(quantity); // So the total is calculated on page load.
quantity.blur(function() {
getTotal(quantity);
});
});
This isn't perfect (you'll need to add some handling for multiplication that causes $50.9999999, for example, and for ending Zero's), but the idea is there.
Tested here: http://jsfiddle.net/J3YKh/1/
edit
Also note that with this code, if one of the quantities is empty, it will not work. That's an easy fix:
quantity.blur(function() {
var qty = $(this).val;
if(!qty) qty = '0';
getTotal(quantity);
}
Just fills in "0" if there is no value, then proceeds as normal. Untested.

Related

React / Meteor / Flowrouter: Passing data

I have been trying to figure out a way of using the data given through flowrouters routing parameter with reactjs.
What i am trying achieve is that when the user creates a farm with certain attributes and inserts that data into mongo collection, then in a another view i could update the values. so i would need to somehow to get the users _id for example, passed into this update view.
Currently i have this code as follows:
FlowRouter.route("/serviceplan/general/basic/:postId",{
name: "BasicInformation",
action(params){
renderTestLayout(<BasicInfo params={params}/>);
}});
The view code:
BasicInfo = React.createClass({
propTypes: {
params: React.PropTypes.object.isRequired,
},
mixins: [ReactMeteorData],
getMeteorData(){
return{
owner: Farms.findOne({farmname: this.props.params.postId})
}
},
updateFarm(){
console.log("updated!");
},
render(){
console.log(this.data.owner);
console.log(this.data.owner.address);
return(
<div>
<div className="col-sm-4">
<h1>Basic information</h1>
<form onSubmit={this.updateFarm}>
<label>Name:</label>
<input type="text" ref="fname" className="form-control" defaultValue=""/><br></br>
<label>Address:</label>
<input type="text" ref="address" className="form-control" defaultValue=""/><br></br>
<label>Postalcode:</label>
<input type="text" ref="postalcode" className="form-control" defaultValue=""/><br></br>
<label>Area:</label>
<input type="text" ref="municipality" className="form-control"defaultValue=""/><br></br>
<input type="submit" value="Update" className="btn btn-default" onClick={this.updateFarm}/>
</form>
</div>
</div>
);
}
The problem here is when i am redirected to this BasicInfo component view the data works fine with props. but when i try to submit the changes, the page reloads and the app crashes. And its probably because the prop value is null since it has not been given to this component.
What would be the solution so i would get the postId value from the url with every refresh?
I found the reason why the app was crashing and solution.
I was trying to access data which didn't exist.
if(this.data.owner){
farmname = this.data.owner.farmname;
address = this.data.owner.address;
postalcode = this.data.owner.postalcode;
municipality = this.data.owner.municipality;
region = this.data.owner.municipality;
Working solution is to check if the mongo data object is not null before accessing it.

Adding another input field when a add button is pressed

Im trying to create an app that will have fields a user can enter information into. The problem is I don't know how many fields that will be. For example, lets say you have a recipe app where you enter the ingredients in. Some recipes may have 2 ingredients and some may have more. What I am wanting is the option if there are more fields needed than what is on the screen presently, the user can press a add button and it will create the additional fields as needed instead of having some potentially unused fields. I've been looking around trying to find an example of what I'm looking for and not having any luck. Any help would be much appreciated.
best approach will be a UITableView. There you can add as much cell as you need.
There is a apples example though it not as like as you want but you can get the picture.
Hope this helps.. :)
Try this it will help you..
<pre><div id="divingredient" class="input_wrapar_search">
<span>Ivingredient Type : </span>
<input type="text" maxlength="50" id="txtIngredient0" />
</div> </pre>
<script>
var counter = 0;
$("[id$=btnaddnew]").live("click", function (e) {
counter++;
if (counter > 10) {
alert("Can not add more than 10 price !");
return false;
}
$("#divingredient").append('<input type="text" maxlength="50" id="txtIngredient' + counter + '" />');
e.preventDefault();
});
$("[id$=btnremove]").live("click", function (e) {
if (counter == 0) {
alert("one price is manadatory !");
return false;
}
$("#txtIngredient" + counter).remove();
counter--;
e.preventDefault();
});
</script>
<asp:Button ID="btnaddnew" runat="server" Class="btn" Text="Add New" />
<asp:Button ID="btnremove" runat="server" Class="btn" Text="Remove" /></pre>

Dynamic POST Radio Button

I create, dynamically, groups ou radio button in the "jQuery(document).ready(function())".
The partial code is:
(...) texto_html = texto_html + ""+record.descricao_equipamento+":"+record.nome_fornecedor+" ("+record.preco_equip_fornecedor+"€)";
(...)
The output is ok, one example:
<h5 class=""><strong>Transmissor 1:</strong></h5>
<div class="control-group">
<label class="control-label"></label>
<div class="controls">
<label class="radio line">
<input type="radio" name="optionsRadios11" value="11">Texto 1
</label>
</div>
</div>
<h5 class=""><strong>Transmissor 2:</strong></h5>
<div class="control-group">
<label class="control-label"></label>
<div class="controls">
<label class="radio line">
<input type="radio" name="optionsRadios12" value="120">
Texto 2
</label>
<label class="radio line">
<input type="radio" name="optionsRadios12" value="12">
Text 3
</label>
</div>
Now I want to POST my Form with AJAX (data: $("#myForm").serialize(),(..)
My problem is in my php file (that will retrieve the Posted values). How can I know how many radios groups I have? Is there a way to serialize them with, let's say an array of radios? Because really I just want their value, independently if they belong to group1 or group2 ou whatever.
thank you.
I'm stuck here! :)))
If I understood correctly you want to iterate over all the radios that were sent:
I can think of two ways of doing that:
You can iterate over all the $_POST values and filter them by a regex (to get just the "optionsRadiosXX" ones)
you can also append a new parameter in your http post (after form.serialize) with all the radios under a given form and then use this parameter as a guide in your php.
.
var getRadios = function() {
var map = {};
$("#formID input[type=radio]").each(function(){
var e = $(this);
if(!map[e.attr("name")]) {
map[e.attr("name")] = true;
}
});
var a = []
for(var r in map) {
a.push(r);
}
// alert(JSON.stringify(a));
return a;
}
See here an example: http://codepen.io/anon/pen/IKayC
Hope that helps.

<li> doesn't work. MVC

I have a view in which I am trying to display text as bulleted items (<ul> <li>) but it doesn't seem work. I tried <ul><li> without enclosing them in <div> still no luck. What is preventing it display the bullets in front of the text.
#model UDP.Models.MCVM
#{
ViewBag.Title = "MCReport";
Layout = "~/Views/Shared/_reportsLayout.cshtml";
}
<div class="span-24 last" >
#* code for filling a grid goes here*#
</div>
<div class="prepend-1 span-22">
<strong> Notes : </strong>
<ul type="circle" >
<li> All listings are sorted according to the user defined sort, and may not display in the order used to determine the median values.</li>
<li> Time ranges are based on a 360-day year commonly called the 'banking year'.</li>
<li> Listings are 'disqualified' from the median value calculations when their Selling, Expiration, or Inactive Date is more than 360 days from the current date.</li>
<li> The Sales Price/List Price calculations will be calculated using the original list price.</li>
</ul>
</div>
<script type="text/javascript">
function loadAndInit() {
$(".dvloading").hide();
if ($.browser.mozilla) {
if (location.pathname == "/udp/Reports") { // This is for local env.
$("#prntCss").attr("href", "../../../Content/SitePrint_FF.css");
}
else { // This is for DEV/QA/STAGE/PROD env.
$("#prntCss").attr("href", "../../Content/SitePrint_FF.css");
}
}
}
</script>

jQuery Mobile: number input and plus/minus buttons inline

Is there a possibility to have a number input with minus-button on the left and plus-button on the right? Or maybe also -- ++ to change value in bigger steps.
I know that I'm not the first one asking this but:
This solution is not displaying correctly in the first turn and jQuery-Mobile-Stepper-Widget from Github (can't post another link because I'm new) does not work with current version of jQuery Mobile.
The result should look like the screenshot in this question: Has anyone implemented jQuery Mobile Add (+/-) Button Number Incrementers? respectively horizontal grouped buttons in jQuery Mobile
Any ideas or new snippets, working with current version of jQuery mobile?
Here is a hint, the rest is purely CSS job and extra JS codes to control the value, e.g. maximum, minimum...etc.
HTML
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
<button id="plus" data-inline="true">+</button>
<input type="text" id="number" value="0" disabled="disabled" />
<button id="minus" data-inline="true">-</button>
</div>
Code
$('#plus').unbind('click').bind('click', function () {
var value = $('#number').val();
value++;
$('#number').val(value);
});
$('#minus').unbind('click').bind('click', function () {
var value = $('#number').val();
value--;
$('#number').val(value);
});
JSFiddle
In jQM the input type number does the most of the magic you want
<input type="number" name="number" value="0"/>
If you require more fancy styling you have to follow Omar's code
<i onclick="qty('plus');" class="fa fa-plus c_pointer"></i>
<input type="text" id="prdqty" name="qty" value="1" placeholder="1">
<i onclick="qty('minus');" class="fa fa-minus c_pointer"></i>
function qty(val){
pqty = $('#prdqty').val();
if (val == "plus") {
var newVal = parseFloat(pqty) + 1;
} else {
if (pqty > 1) {
var newVal = parseFloat(pqty) - 1;
} else {
newVal = 1;
}
}
$('#prdqty').val(newVal);
}

Resources