0

How can I use these JavaScript or jquery math functions ?

For example, I want to compute the sum of all values in a form, without submiting the form or in button click. I have 4 input fields and i want to add then and put the result of them in another input or paragraph.
Html code looks like this :

<form id='myform'>
    <label> Number 1 : </label><input value="" id="1"/><br>
    <label> Number 2 : </label><input value="" id="2"/><br>
    <label> Number 3 : </label><input value="" id="3"/><br>
    <label> Number 4 : </label><input value="" id="4"/><br> <br>
    <button href="#" class='add'> ADD</button> 
    <p id="p"> </p>
</form>

I tried to do something like this :

var one   = $("#1").val();
var two   = $("#2").val(); 
var three = $("#3").val();
var four  = $("#4").val(); 
$("add").on("click", function(){
    var sum = one + two + three + four;
    $('p').text(sum);        
})

I created a jsfiddle: example Can you give a little help? Thank you.

7
  • Fetch input value inside click handler jsfiddle.net/satpalsingh/LcyazLn1 Commented Sep 10, 2015 at 11:30
  • Always use document-ready handler, see api.jquery.com/ready Commented Sep 10, 2015 at 11:37
  • @Satpal - no need for the document ready handler in that link. It's running onLoad as per jsfiddle defaults. Commented Sep 10, 2015 at 11:38
  • @Archer, You just can't really on fiddle Onload or onDomReady as I have seen questions like code running in fiddle but not in site etc Commented Sep 10, 2015 at 11:39
  • @Satpal So have I, so you should have disabled the fiddle event handlers to avoid possible confusion. Anyway, I see no mention from the OP of the code not running. Is he not using document ready handlers then? Commented Sep 10, 2015 at 11:44

3 Answers 3

1

Change it to this...

$(".add").on("click", function(){
    var one   = parseInt($("#1").val(), 10);
    var two   = parseInt($("#2").val(), 10); 
    var three = parseInt($("#3").val(), 10);
    var four  = parseInt($("#4").val(), 10); 
    var sum = one + two + three + four;
    $("p").text(sum);        // or $("#p") since you gave it an ID
});

That way you get the values at the time you click "add", and you also need parseInt() to convert the values into integers, or they'll be treated as strings and concatenated instead.

Incidentally, using numbers as element IDs is not recommended. Simply prefixing them with a common name would be a good idea, like #value1, #value2 etc..

There was also a small issues with your markup, which I fixed...

<form id='myform'>
    <label> Number 1 : </label><input value="" id="1"/><br>
    <label> Number 2 : </label><input value="" id="2"/><br>
    <label> Number 3 : </label><input value="" id="3"/><br>
    <label> Number 4 : </label><input value="" id="4"/><br> <br>
    <button type="button" class="add">ADD</button> 
    <p id="p"> </p>
</form>

The button element defaults to a submit button, unless you specify type="button", so it was causing the page to submit, rather than just handle the button click. You can stop this with the click event handler, but I prefer to set the button type.

Here's the working example...

https://jsfiddle.net/fs5ysde1/17/

Sign up to request clarification or add additional context in comments.

6 Comments

$(".add") missed . also and add few line for document-ready handler
Thanks for the heads-up about the . - I didn't spot that. I'm not adding a document ready handler though as that's out of scope of the question and assuming the OP doesn't already have one.
@archer I run your code. It seems its not working in jsfiddle. Could you check it please
@Archer you'll also need to cancel the click event, otherwise it'll trigger a form submission. The event object is the first argument passed to the handler, so grab that and call .preventDefault() on it, or just return false from the handler.
I've updated it and added a working example for you to see. Also, if relevant, do pay attention to what @Satpal said about the document ready handler.
|
0

Add + before each to covert it into number if you want to add it as a number like this +$("#1").val();

$(".add").on("click", function(e){
        e.preventDefault();
        var one   = +$("#1").val();
        var two   = +$("#2").val(); 
        var three = +$("#3").val();
        var four  = +$("#4").val(); 
        var sum = one + two + three + four;
        $('#p').text(sum);        
    })

1 Comment

$(".add") missed . also, Just code dump is not use full
0

I know we have our answer, but I thought I'd show a different approach :-)

// get all the fields in one go
var $fields = $('#myform input');

$('.add').click(function(e){
    // kill the form submission
    e.preventDefault();

    var total = 0;
    $fields.each(function(pos, el) {
        // get the the vals, and, if blank, default to 0
        total += parseInt($(el).val()) || 0;
    });

    $('p').text(total);
});

Comments

Your Answer

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