user1317647
user1317647

Reputation:

Jquery counting

How do i count #total value + 170 with jquery?

$("#member").click(function() {
if ($('#member').is(':checked')) {
    var totalv = $("#total").val();
    var skatz = 170;
    var skaits = totalv + skatz;
    $("#total").val(skaits);
}

Upvotes: 1

Views: 270

Answers (2)

JakeJ
JakeJ

Reputation: 1381

You should check if the provided value is actually a number (You can do onkeypress or keyup each time but I say you should always check on submission). Below is your code modified to work (With checks to see if the value is a number).

EDIT: Make sure that your javascript has document ready wrapped around it. (Functions can be outside of this call)

$(document).ready(function () {
    $("#member").click(function() {
    if ($('#member').is(':checked')) {
        var totalv = $("#total").val();
        if(isNumber(totalv) == true)
        {
            var skatz = 170;
            var skaits = parseInt(totalv) + skatz;
            $("#total").val(skaits);
        }
        else
        {
            alert("You must enter a numerical value");
        }
    }
});

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

Upvotes: 1

steveukx
steveukx

Reputation: 4368

The result of .val() will be a string, so you first need to convert it to a number:

var totalv = $("#total").val();
var skatz = 170;
var skaits = +totalv + skatz;
$("#total").val(skaits);

(notice the additional + prefix to the totalv variable.

Upvotes: 1

Related Questions