3

How can I use these JavaScript math functions ?

For example, I want to compute the square of all <input> values in a form, without submiting the form.

Can you give a little example? Thank you.

12
  • Example of what? You need to be more specific in order to get an answer here. Commented Jan 17, 2011 at 16:28
  • It doesn't make any difference if you're using jQuery or not. The Math functions work as usual. Commented Jan 17, 2011 at 16:29
  • 11
    Please don't use w3schools as a resource for learning JavaScript (or anything else, for that matter). w3fools.com Commented Jan 17, 2011 at 16:30
  • You misunderstood me (or i can't explain myself) . I don't know javascript to much. So i need a small example which return square of all <input>'s , for example. Commented Jan 17, 2011 at 16:33
  • 2
    @Tom, They misunderstood me and comments are really funny :) (For example BoltClock's comment "How is it possible to know jQuery without knowing JavaScript?") . Maybe i can't explain. Question edited. You can check again but question is closed. Commented Jan 17, 2011 at 16:38

7 Answers 7

7

JQuery doesn't need to support math functions as it is an addon library for Javascript, you can still use Javascript in your JQuery code, so you can still use all the native math functions.

Examples:

Addition

var x = 1;
var y = 2;
var lol = x+y;
alert(lol);

Subtraction

var x = 10;
var y = 1;
var lol = x-y;
alert(lol);

Edit: Now we understand your question a little better...

<input type="text" id="field1" value="16" />
<input type="text" id="field2" value="25" />
<input type="text" id="field3" value="36" />

var field1Value = document.getElementById("field1").value;
var field2Value = document.getElementById("field2").value;
var field3Value = document.getElementById("field3").value;

alert(Math.sqrt(field1Value ));
alert(Math.PI * field2Value);
alert(Math.sin(field3Value));
Sign up to request clarification or add additional context in comments.

3 Comments

@Eray Alakese: How is it possible to know jQuery without knowing JavaScript?
@BoltClock: It is unfortunate that what you just mentioned has become the norm rather than the exception.
@BoltClock, :D . You misunderstood me. Question edited. You can check. Thanks.
2

You can act on each individual input using an each()(docs) loop.

Click here to test a working example. (jsFiddle)

$('a.square').click(function() {
    $('#myform :text').each(function() {
        this.value *= this.value;
    });
});

$('a.square_root').click(function() {
    $('#myform :text').each(function() {
        this.value = Math.sqrt(this.value);
    });
});

When either link is clicked, it finds all the text inputs in myform and iterates over them.

Inside the each function, this refers to the current input element.

1 Comment

Or: $('#myform :text').val(function(i,v) { return v*v; });
1

JavaScript is the programming language, not jQuery, which is a library for web application programming written in JavaScript. To effectively use jQuery, you need to know JavaScript.

It is, however, possible to use jQuery's functionality to easily work with multiple textboxes at once:

// Set each single-line textbox's value to the square
// of its numeric value, if its value is in fact a number.
$('input:text').each(function() {
    var num = +this.value;
    if(!isNaN(num)) {
        this.value = num * num;    // or Math.pow(num, 2)
    }
});

Comments

1

It would be quite useful if jQuery had a reduce() function.

When dealing with lists of data, most functional languages, and indeed most traditional languages these days, have methods that perform a repetitive function over the entire list, taking each element in turn and applying a function to it.

The simplest of these is map, which jQuery implements for you. This takes a list and applies a function to each element and returns the list of results, one result per entry in the list. eg. [1,2,3] -> (map x2) -> [2,4,6].

Sometimes you want a total or collective result from a list, rather than a list of individual mappings. This is where the reduce (or fold) operation comes in. Unfortunately jQuery does not have this method available as standard, so below is a plugin for it. A reduce function takes an accumulator value and the value of the current element, and returns the modified accumulator, which will be passed on to the next call. eg. [1,2,3,4] -> (reduce + [initial:0]) -> 10 = ( ( ( (0 + 1) + 2 ) + 3 ) + 4 ) or ([1,2,3,4] -> (reduce * [initial:1]) -> 24 = ( ( ( (1 * 1) * 2 ) * 3 ) * 4 ).

(function($) {
    $.reduce = function(arr, callback, initial) {
        var accumulator = initial || 0;

        $.each(arr, function(index, value) {
            accumulator = callback(accumulator, value, index);
        });

        return accumulator;
    }
})(jQuery);

Then you can use it like this to get a sum of squares:

var answer = $.reduce($('input:text'), function(acc, elem) {
    var cVal = $(elem).val();
    return acc + cVal * cVal;
}, 0);

3 Comments

You might want to explain what reduce means. If he's having trouble with using the Math library he might not understand what a reduce does.
Another point is that you can check for array.reduce which is implemented in firefox & chrome. Native code always runs better
@Raynos: Very true, I tend to ignore the existence of functions that do not exist (at least in some format) in all browsers. But the implementation could use the underlying function where available if handled properly.
1

i was looking for a solution too , and i saw a lot of questions here that doesn't work (even this one) in case someone wondering like me , here is my working solutiuon :

$("#apport").keyup( 
function(){
var apport = parseFloat($("#apport").val());
var montant = parseFloat($("#montant-financer").val());
var moinmontant = parseFloat(montant) - parseFloat(apport);     
$("#montant-financer").val(moinmontant);    
}
);

All the id's selector are input

Comments

0

Use the jquery map function to create an array

$('input:text').map(function() {
  return this.value * this.value; // math calculation goes here
}).get();

See a live example

Comments

0

Looking at the initial question that was posted, it clearly states compute the square of all values in a form, without submiting the form.

i think keyup would be the best solution.

$("input").keyup(function () {
  var value = $(this).val();
  var x=value*value;
  $("p").text(x);
}).keyup();

Click here to check the working example. http://jsfiddle.net/informativejavascript/Sfdsj/3/

For more details visit http://informativejavascript.blogspot.nl/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.