jquery calculate BMI - javascript

I stuck to this problem. I want to calculate body BMI.
My HTML - every row <tr> is created dynamically by PHP.
<tbody>
<tr id="person_bmi">
<td>Jack</td>
<td><input name="weight" type="text" class="span1" id="weight" maxlength="5"></td>
<td><input name="height" type="text" class="span1" id="height" maxlength="5"></td>
<td><input name="bmi" type="text" class="span1" id="bmi" readonly></td>
</tr>
<tr id="person_bmi">
<td>Michael</td>
<td><input name="weight" type="text" class="span1" id="weight" maxlength="5"></td>
<td><input name="height" type="text" class="span1" id="height" maxlength="5"></td>
<td><input name="bmi" type="text" class="span1" id="bmi" readonly></td>
</tr>
//and so on...
</tbody>
What I try to achieve is every person Jack, Michael, so on.. will have their own BMI values in #bmi textfield after calculated their own $weight/($height*100/$height*100) value. I try to create my own code but its not make sense..
$("#weight, #height").keyup(function(){
var $weight= $("#weight").val();
var $height= $("#height").val();
var $bmi = $weight/($height/100*$height/100);
$("#bmi").val(parseInt($bmi));
});
Can someone show me the way? Thanks

Remove the duplicate IDs and use class="weight", class="height" and class="bmi" instead. Then you can use the following jQuery code:
$(".weight, .height").keyup(function() {
var row = $(this).closest('tr');
var weight = parseInt(row.find('.weight').val(), 10);
var height = parseInt(row.find('.height').val(), 10);
var bmi = weight / (height / 100 * height / 100);
row.find('.bmi').val(isNaN(bmi) ? '' : bmi);
});
If you want to allow floats for the input values, replace the two lines containing parseInt with these:
var weight = parseFloat(row.find('.weight').val());
var height = parseFloat(row.find('.height').val());
Demo: http://jsfiddle.net/KStjd/

The problem is most likely that val returns strings and strings can't me multiplied or divided. As mentioned by ThiefMaster you also can't have multiple items with the same id so change <tr id="person_bmi"> to <tr class="person_bmi">
$(".person_bmi input").keyup(function() {
var $parent = $(this).parent().parent();
var weight = parseFloat($parent.find("[name='weight']").val());
var height = parseFloat($parent.find("[name='height']").val());
var bmi = weight/(height/100*height/100);
$parent.find("[name='bmi']").val(bmi);
});​
Here is a fiddle of a full working example:
http://jsfiddle.net/uCAYF/1/
The .find function you see being used is "scoped" in the sense that it will only find nodes that are descended from the element it was called on. Since it is scoped it will safely select the the input field of interest on the given row.
jQuery lets you use CSS selectors when searching for elements so you can do more than just look things up by id. For instance, in the example above I find your input elements by their name.
Here are some good resources on the different selectors you can use and how they work:
http://www.w3.org/TR/CSS2/selector.html
http://www.w3.org/TR/selectors/

Please try to add unique id's:
var weight= parseFloat($("#person1_weight").val());
var height= parseFloat($("#person1_height").val());
var bmi = weight/(height/100*height/100);
$("#person1_bmi").val(bmi); // bmi is not an integer
Or the following will probably work regardless of the invalid non unique id's so you could leave them (not recommended) or take all of the id's off. It uses the input positions.
$("tr input:eq(0), tr input:eq(1)").keyup(function(){
var weight= parseFloat($(this).closest('tr').find('input:eq(0)'));
var height= parseFloat($(this).closest('tr').find('input:eq(1)'));
var bmi = weight/(height/100*$height/100);
$(this).closest('tr').find('input:eq(2)').val(bmi);
});

$("input[name=weight], input[name=height").keyup(function() {
var row = $(this).parent().parent(),
weight = parseFloat($('input[name=weight]', row).val()),
height = parseFloat($('input[name=height]', row).val());
var bmi = weight / (height / 100 * height / 100);
$('.bmi', row).val(isNaN(bmi) ? '' : bmi);
});
Working Sample

$(document).ready(function()
{
$("PutYourButtonID_Here").click(function(event){
var weight= parseFloat($("#person1_weight").val());
var height= parseFloat($("#person1_height").val());
var bmi = weight/(height/100*height/100);
$("#person1_bmi").val(bmi);
});
});

Related

Addition of Textbox Values which having same name & id ( Textbox getting for loop as per database )

Good Afternoon... I am trying to do the addition of textbox value and show in total textbox using onBlur but not able to do the same. Textbox are generated using foreach loop as per buffaloID base on database which having same name and id. ( Ref. Attached Image) For first textbox, the function gives the value but for next textboxes, not able to get the same.
My Modal Table Code.
#foreach ($buffalodata as $item )
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk" name="eachmorningmilk" value="00"></td>
<td><input type="number" id="eacheveningmilk" name="eacheveningmilk" value="00"></td>
<td><input type="text" id="eachtotalmilk" name="eachtotalmilk" value="00" readonly></td>
</tr>
#endforeach
JavaScript Code for Function to run onblur
$("#eachmorningmilk").blur(function(){
eachbmorning = parseInt($("#addmilkbuffalo #eachmorningmilk").val());
eachbevening = parseInt($("#addmilkbuffalo #eacheveningmilk").val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById('eachtotalmilk').value=eachbuffalototalmilk;
})
Ref. Images
Please use the onchange method and assign unique id and name to each field. You can refer to the below code and it will work.
HTML
<tr>
<td>{{$item->buffaloID}}</td>
<td><input type="number" id="eachmorningmilk{{$item->buffaloID}}" name="eachmorningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" value="00"></td>
<td><input type="number" id="eacheveningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" name="eacheveningmilk{{$item->buffaloID}}" value="00"></td>
<td><input type="text" id="eachtotalmilk{{$item->buffaloID}}" name="eachtotalmilk{{$item->buffaloID}}" value="00" readonly></td>
JS
function totalmilk(id){
var morningmilk = "#eachmorningmilk"+id;
var eveningmilk = "#eacheveningmilk"+id;
var totalmilk = "eachtotalmilk"+id;
eachbmorning = parseInt($(morningmilk).val());
eachbevening = parseInt($(eveningmilk).val());
var eachbuffalototalmilk = eachbmorning + eachbevening;
document.getElementById(totalmilk).value=eachbuffalototalmilk;
}

How to get Contact Form 7 field values in javascript?

Please help me, i've the javascript allmost done. Only the last part is very difficult.
I've used the calculator plugin for contact form7, to calculate the BMI, this works perfectly.
To hide the BMIhigh text also works, and the click
Length (cm):
<label id="centi">[number* cm min:130 max: 220]</label>
Hight (kilo):
<label id="kilo">[number* kilo min:40 max:140]</label>
<label id="calcbutton">[calculate_button "calculate"]</label>
<label id="calc">[calculation calculate precision:1 "kilo / ((cm / 100) * (cm / 100))"]</label>
<label id="BMIhigh">
Your BMI is too high
</label>
[submit "Send"]
At the bottom i've got the following code:
// Hide the BMIhigh text field by default
document.getElementById("BMIhigh").style.display = 'none';
// On every 'click' on the calculator call the displayTextField function
document.getElementById("calcbutton").addEventListener("click", displayTextField);
function displayTextField() {
// Get the inserted values for centi and kilo and calculate the BMI again
// for the function without the help of the calculator build in into the extra plugin.
var centimeter = +document.getElementById("centi").value;
var kilogram = +document.getElementById("kilo").value;
var BMIvar = kilogram / ( ( centimeter / 100 ) * ( centimeter / 100 ) );
// If BMIvar higher than 30 it is too high, the text should show.
// THIS LAST PART DOES NOT WORK
if(BMIvar > 30) {
document.getElementById("BMIhigh").style.display = 'block';
} else {
document.getElementById("BMIhigh").style.display = 'none';
}
}
</script> ```
Your variable BMIvar never get evaluated because,
var centimeter = +document.getElementById("centi").value;
var kilogram = +document.getElementById("kilo").value;
these variables are not being populated properly. CF7 converts field tags into <span> encapsulated <input/> fields,
<label id="centi">
<span class="wpcf7-form-control-wrap cm">
<input type="number" name="cm" value="" class="wpcf7-form-control wpcf7-number wpcf7-validates-as-required">
</span>
</label>
and as such getElementById returns the <label/> element and not the <input/> one. element.value only works for <input/> fields. Try instead to use getElementsByName and replace the above 2 lines with,
var centimeter = 1.0*document.getElementsByName("cm")[0].value;
var kilogram = 1.0*document.getElementsByName("kilo")[0].value;
Here is a jsFiddle with a working example.

How to update price dynamically based on quantity using jQuery?

I have build a shopping cart where I want to update the price based on Quantity..But the problem I'm facing is using following javascript code that for the first item i could update the price based on Quantity but for the second item or next item i couldn't ..Can anyone help me out to find the Error please.
Here's my html :
<td class="total_price table-default total" >${{$row->price}}
<span></span></td>
<td class="qty table-default">
<input type="number" class="quantity" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> ×${{$row->p_price}}
Here's the jQueryPart:
$(".quantity").change(update);
function update()
{
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('.total').html("$"+total);
}
Remove the following block:
$("#quantity").each(function(i){
so the function is:
function update(){
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('#total').html("$"+total);
}

jQuery Math Operation on Multiple Elements

I have a simple invoicing page so I can invoice my client, however when I am going to perform multiplication to the quantity and price, the row total is not adding. Here's my jQuery so far.
$(":input").bind('keypress keydown keyup change', function(){
var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
var qty = parseFloat($(this).closest('tr').find('.quantity').val(),10);
var v = '';
if(!isNaN(price) && !isNaN(qty)) {
v = price * qty;
}
$(this).closest('tr').find('.rowtotal').val(v.toString());
});
And this is my HTML:
<table>
<tr>
<td>1</td>
<td><input name="item_name[]"class="form-control"></td>
<td><input name="item_description[]"class="form-control"></td>
<td><input name="item_price[]"class="form-control price"></td>
<td><input name="item_quantity[]"class="form-control quantity"></td>
<td><span class="rowtotal">0.00</span></td>
</tr>
<tr>
<td>2</td>
<td><input name="item_name[]"class="form-control"></td>
<td><input name="item_description[]"class="form-control"></td>
<td><input name="item_price[]"class="form-control price"></td>
<td><input name="item_quantity[]"class="form-control quantity"></td>
<td><span class="rowtotal">0.00</span></td>
</tr>
</table>
Now on my page, it shows no error while reviewing the console, but it does not perform the operation that I have created following this post "Automatically updating input field with math using jquery?"
Any help is appreciated.
TIA
You've got a typo in this line:
var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
^^ Shouldn't be a class selector
Should be:
var price = parseFloat($(this).closest('tr').find('.price').val(),10),
Next line is fine. Additionally, you can replace all those events with:
$(":input").on("input", function() {
// Triggers on any input event
});
You also have a few other issues:
There is no overload for parseFloat which takes two parameters
You are using .val() to set the text of the span. You need to use .text() instead
You should probably cache the <tr> selector. You don't need to go find it each time.
$(":input").on('input', function(){
var $tr = $(this).closest("tr");
var price = parseFloat($tr.find('.price').val()),
qty = parseFloat($tr.find('.quantity').val());
var v = '';
if(!isNaN(price) && !isNaN(qty)) {
v = price * qty;
}
$tr.find('.rowtotal').text(v.toString());
});
Working Example

Undefined error getting parents childs input value

I have a table that looks like this:
<table>
<tr>
<td class="packing-vol">0.19</td>
<td class="qty-cell"><input type="text" name="qty[]" class="qty" value="2" /></td>
</tr>
<tr>
<td class="packing_total">0.70</td>
<td class="qty-cell"><input type="text" name="qty[]" class="qty" value="1" /></td>
</tr>
</table>
I'm looping through each occurence of .packing-vol getting it's text, then I want to get the qty from the same row so I go up to it's parent then drill into the .qty class. But when I alert(qty) i get 'undefined' message.
var total = 0;
jQuery('.packing-vol').each(function(i) {
var qty = jQuery(this).parent("td.qty-cell .qty").val();
alert(qty);
var cur = parseFloat(jQuery(this).text());
if(!isNaN(cur)){
total = total + cur;
}
});
I think you should do this:
var qty = jQuery(this).parent().find("td.qty-cell .qty").val();
You need to go 1 level up (using .parent) and then find your field inside with .find
parent is just one level upwards. You can't use it to go inside trees again.
parents is multiple levels upwards. You can't use it to go inside trees again.
You can use parent/parents and then use find to do what you want, or even better:
var total = 0;
jQuery('.packing-vol').each(function(i) {
var qty = jQuery(this).parent().children('.qty-cell').children('.qty').val();
alert(qty);
var cur = parseFloat(jQuery(this).text());
if (!isNaN(cur)){
total = total + cur;
}
});
You could also use find, but it is slower than going directly inside, because it has to search the DOM object.
But you could also do:
var qty = jQuery(this).parent().find("td.qty-cell .qty").val();
Instead of
var qty = jQuery(this).parent("td.qty-cell .qty").val();
Try:
var qty = jQuery(this).parent().find(".qty").val();

Categories