Elizabeth Fuenzalida Elizabeth Fuenzalida - 1 month ago 7
Javascript Question

How do I use parseInt to add two numbers?

I'm supposed to use parseInt to add two numbers the user enters, then use my response object to send back the result and display output to the user.

For instance, if the user enters 2 and 3, the server should add these numbers together and send back an object containing the value 5.

Here's what I have tried so far/ have:
index.js

var express = require('express');
var router = express.Router();

/* GET home page. */

router.get('/add', function (request,response) {
console.log('add method called');
console.log('The parameters are: ', request.query);
//Attempt 1
//var parse = parseInt('#operatorA',12);
// var parse2= parseInt('operatorB',7);

//Attempt 2
//var operatorA = $('#operatorA').val();
// var operatorB = $('#operatorB').val();

//Attempt 3
//var a = parseInt(" ") ;
//var b = parseInt(" ") ;
//var x = parseInt (a + b);

//Attempt 4
//var x = a+b;

//Attempt 5
//var a = operatorA this won't work b/c operator a isn't defined here.

//Attempt 6
//var a = $('#operatorA').val();
//var b = $('#operatorB').val();
//var x = parseInt(a);
//var y = parseInt(b);

response.send([
//Attempt 1
//parse

//Attempt 2
//parseInt(operatorA,operatorB)

//Attempt 3 & 4
// x

//Attempt 6
//x + y
]);
});
module.exports = router;


Control.js

$(document).ready(function() {
'use strict';
console.log('Document loaded in isit320');

$('#read').click(read);
$('#readJson').click(callReadJson);
$('#add').click(add);
}

function add() {
var operatorA = $('#operatorA').val();
var operatorB = $('#operatorB').val();
console.log('operators: ', operatorA, operatorB);
var requestQuery = { operatorA: operatorA, operatorB: operatorB };
$.getJSON('/add', requestQuery,function(result) {
console.log(result);
$('#display').html(JSON.stringify(result));
});
}
});

Answer

parseInt is used as parseInt(string, radix) like so:

var a = parseInt($('#operatorA').val(), 10);
var b = parseInt($('#operatorB').val(), 10);
response.send([a+b]);
Comments