Calculate values using jquery - javascript

I am still studying jquery and I have this code in my gsp:
<g:each in="${poundList}" var="poundInstance">
<span>${poundInstance?.name}<span/>
<span class="price">${poundInstance?.price}<span/>
</g:each>
<span id="total"></span>
In my jquery:
function calculatePound() {
totals= 0;
$(".price").each (function() {
totals= totals+ parseFloat("0" + $(this).val());
});
$("#total").text(totals.toFixed(2));
}
$(document).ready(function() {
calculatePound();
});
The code above has no errors. But the problem is that the <'span id="total"'> is empty or has a value of 0.0
What I was trying to do is to calculate the price of each poundInstance and display it.
How can I make it work using this code? Or I am too far from what I want to achieve?
Thanks.

You can't use val(), the method is primarily used to get the values of form elements such as input, select and textarea. You can use text():
function calculatePound() {
var totals= 0;
$(".price").each (function() {
totals= totals+ parseFloat("0" + $(this).text());
});
$("#total").text(totals.toFixed(2));
}

Related

jQuery to loop through dynamically created elements with the same class

I have no. of div which is created dynamically in button click.
<table>
<tbody id="ProductDetail"></tbody>
</table>
In button click, some no. of div are created with Amount value.
funtion createDiv(){
$("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}
I want to loop through these dynamically created div to get Amount values in jquery.I tried below code. But its not iterating loop.
function calculateAmount(){
$('.Amount').each(function (i, obj) {
TotalAmountValue=TotalAmountValue+$(this).html();
});
}
Please anybody help me.
I got this working just fine!
$(document).ready(function(){
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#sum").click(function()
{
var sum = 0;
$(".Amount").each(function()
{
sum += parseInt($(this).text());
});
alert(sum);
});
});
the .each iterates through all your elements that have the class Amount. Use the . selector for class and add the name.
Index represents the position, while the val is the current element.
Edit: get a local variable and set it to 0. After that, iterate through all the elements with that class and take their text. Since it is String, js will try to convert the sum variable to String. You need to parse the text to int. This is a working example.
Here is the HTML
<table>
<tbody id="ProductDetail"></tbody>
</table>
<input type="button" id="sum" value="Sum">
Try using text()
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});
$('.Amount').each(function(index, val)
{
//do something
});
If you are calling the calculateAmount() function right after createDiv() depending on your page weight, it might happen that the DIV you create on the fly it's not written to the DOM yet and your each function inside calculateAmount() it's not triggered. I recommend adding a JS delay to give the browser the time to append the divs to the DOM. For the user, it will make no difference.
HTML
<table>
<tbody id="ProductDetail"></tbody>
</table>
JS
function createDiv(){
$("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}
function calculateAmount(){
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});
}
createDiv();
setTimeout(function () {
calculateAmount();
}, 400);

Get span value with jquery

I have tested every solution I have found on Internet, but none of them works.
I have this HTML:
<h4>Códigos disponibles:<span id="codesQuantity">#Model.ExternalCodesForThisProduct</span></h4>
And this Javascript:
$('#eCodesFrm').on('submit', function (e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var availableCodes = $("#codesQuantity");
var totalCodesUsed = 0;
alert(availableCodes);
$('#eCodesFrm *').filter(':input').each(function () {
if (this.name.match(/.Quantity$/)) {
totalCodesUsed = totalCodesUsed + parseInt(this.value, 10);
}
});
But availableCodes is [object Object].
What am I doing wrong?
If you need the inner element try .html(). As long as it's plain text in there there shouldn't be a problem.
To get the text inside the <span> use .text():
jQuery("#codesQuantity").text() //or $("#codesQuantity").text() if $ is jQuery in your code.
The problem here is that you're assigning a jQuery object to your variable, and not the content of the element. To extract the text inside the <span>, you should use either .html() or .text(), and do this instead:
var availableCodes = $("#codesQuantity").text();

Jquery changing css and form data

I'm making a form where the users fill in a title which they can size up or down. I have a preview window that changes when they click on the "size up button". But I want to store this in a hidden form to get the value when posting.
HTML - FORM
<input id="title" name="title" />
<input id="titlesize" name="titlesize" value="50" />
<div id="sizeUp">Size up!</div>
HTML - PREVIEW WINDOW
<h2 id="titlepreview" style="font-size: 50px;">Title</h2>
Javascript
$(document).ready(function() {
$("#sizeUp").click(function() {
$("#titlepreview").css("font-size","+=5"),
$("#titlesize").val("+=5"); // <-- Here's the problem
});
Any ideas?
Try this using the .val( function(index, value) ):
$(document).ready(function () {
$("#sizeUp").click(function () {
$("#titlepreview").css("font-size", "+=5"),
$("#titlesize").val(function (index, value) {
return parseInt(value, 10) + 5;
});
});
});
FIDDLE DEMO
You need parseInt to handle strings as numbers.
$("#sizeUp").click(function () {
var obj = $("#titlesize");
var value = parseInt(obj.val());
obj.val(value + 5);
});
OK, I'm not entirely sure where the problem is here, but here's a way of going about it anyway:
If you want a range of sizes so you can't get a title too big or small, you could (while this is long-winded) make a css class for each size.
Then, you could use JqueryUI's .addClass() and .removeClass. With these you could do something like:
$("#sizeupbutton").click(function(e){
$(#title).removeClass("size45");
$(#title).addClass("size50");
});
Sorry if I've completely got your question wrong, but good luck!
Edit: OK, now i think i understand what you want, I would advise you check out Vucko's answer below.
you can get variable like this:
$(document).ready(function () {
$("#sizeUp").click(function () {
$("#titlepreview").css("font-size", "+=5");
var up=parseInt(($("#titlepreview").css("font-size")),10);
$("#titlesize").val(up);
});
});
example:fiddle

How to get the values of html hidden wrapped by a div using jquery?

Im very new to javascript and jquery so please bear with me.
Here's my code: http://jsfiddle.net/94MnY/1/
Im trying to get the values of each hidden field inside the div.
I tried
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = 7;
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField hidden").html());
}
});
});
but the value Im getting is null.
I also wanna know how to get the total number of html elements inside a div. In my case how am I gonna get the total number hidden field inside the div. I assigned the value of totalHidden = 7 but what if I dont know total number of hidden fields.
Please help. Thanks in advance.
$('#hiddenField hidden') is attempting to access an actual <hidden> tag that is a child of #hiddenField
Try this instead. What you want to use is the input[type=hidden] selector syntax. You can then loop through each of the resulting input fields using the jQuery.each() method.
If you want to iterate over the <input> elements and alert each value try this:
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('#hiddenField input').each(function() {
alert(this.value);
});
});
});
http://jsfiddle.net/94MnY/8/
Here it is.
Basically, you are looking for .each(). I removed a few input fields because so many alert messages are annoying. Also added in the selector the type hidden to avoid getting your last input field.
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('input[type="hidden"]').each(function(i){
alert($(this).attr('value'))
})
});
});
To stick to what you already have - but with few modifications:
DEMO
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = $('#hiddenField input[type=hidden]').length; // get number of inputs
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField input[type=hidden]").eq(i).val());
}
});
});
You can actually just create an array of those hidden elements using query and loop through them and alert their values.
I have put a jsfiddle for you to see
http://jsfiddle.net/94MnY/4/
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$("#hiddenField input[type='hidden']").each(function(i, e){
alert($(this).val());
});
});
});
Try
$('#hiddenfield input[type=hidden]').each(function(){
alert(this.val());
});

tag cloud filter

I have a div that contains many spans and each of those spans contains a single href.
Basically it's a tag cloud. What I'd like to do is have a textbox that filters the tag cloud on KeyUp event.
Any ideas or is this possible?
Updated question: What would be the best way to reset the list to start the search over again?
Basically, what you want to do is something like this
$('#myTextbox').keyup(function() {
$('#divCloud > span').not('span:contains(' + $(this).val() + ')').hide();
});
This can probably be improved upon and made lighter but this at least gives the functionality of being able to hide multiple tags by seperating your input by commas. For example: entering this, that, something into the input will hide each of those spans.
Demo HTML:
<div id="tag_cloud">
<span>this</span>
<span>that</span>
<span>another</span>
<span>something</span>
<span>random</span>
</div>
<input type="text" id="filter" />
Demo jQuery:
function oc(a){
var o = {};
for(var i=0;i<a.length;i++){
o[a[i]]='';
}
return o;
}
$(function(){
$('#filter').keyup(function(){
var a = this.value.replace(/ /g,'').split(',');
$('#tag_cloud span').each(function(){
if($(this).text() in oc(a)){
$(this).hide();
}
else {
$(this).show();
}
})
})
})

Categories