Madhawa Ratnayake
Madhawa Ratnayake

Reputation: 189

JavaScript: Calculating inputs (select input) and resulting a number

LIVE DEMO

When I run select something from the drop-down ('room_type_id' and 'bed_type_id') it outputs a "NaN" (Not a Number). If I first select something from multiple select input ('bed_type_id') then the output results are: 52000, 53000, 53500 although the real values are 1000, 2000, 2500 as you can see in the HTML form in the demo above.

I suspect parseInt has something to do with it. parseFloat didn't work either. Any suggestions?

function jungi() {
   var room_type_id=document.getElementById('room_type_id').value;
   var meal_type_id=document.getElementById('meal_type_id').value;
   var bed_type_id=document.getElementById('bed_type_id').value;
   document.getElementById('total_amount').value = parseInt(room_type_id) + parseInt(meal_type_id) + parseInt(bed_type_id);
}

Upvotes: 1

Views: 77

Answers (2)

stepanVich
stepanVich

Reputation: 328

You must use selectedIndex and options values:

Javascript:

var room = document.getElementById("room_type_id");
var meal = document.getElementById("meal_type_id");
var bed = document.getElementById("bed_type_id");
document.getElementById("form1").onchange = jungi;
function jungi() {
 document.getElementById("total_amount").value = parseInt(room.options[room.selectedIndex].value) + parseInt(meal.options[meal.selectedIndex].value) + parseInt(bed.options[bed.selectedIndex].value);       
}

Moreover you must wrap selection tags into <form id = "form1">...</form> tag.

Upvotes: 1

mguimard
mguimard

Reputation: 1891

Your multiple select has no value selected on load, so you're trying to do :

parseInt("")

Which results as Not A Number

Maybe you should add selected on the first option of your multiple select.

<option value="1000" selected>Breakfast</option>

You can also check for an empty string before calling parseInt

Upvotes: 4

Related Questions