Im trying to create a cost calculator script. It basically shows if the manual input is for example 10$ and if you choose week, month or year it multiples with 52 for week, 12 for month and 1 for year so it shows the cost total in year.
In the code snippet there are 2 variables for a house and car. For house it works fine and thats what I could do so far. I also need to add more fields like a car in example. And I want to be able to fill the cost for house and car and more fields and when I hit calculate button, it should be showing all the costs like house cost + car cost + other fields..
so far I could only make it work for the house, if you fill the car field it doesn't add in the total, how can I make it work and add more fields if I want and they should be also working.
var btn = document.querySelector('#calculate');
btn.addEventListener('click', function () {
var num1 = Number(document.querySelector('#num1').value),
rlt = document.querySelector('p.answer');
var method = document.querySelector('option[name="method"]:checked').value;
var answer = 0;
if ('week' === method) {
answer = num1 * (52);
} else if ('month' === method) {
answer = num1 * (12);
} else if ('year' === method) {
answer = num1;
}
rlt.innerHTML = answer;
});
<div class="container">
<div class="input-control">
<label style="Float:left;" for="num1">🏠
<input type="text" id="num1" autofocus>
$</label>
<label style="Float:left;" for="dropdown">
<select>
<option name="method" id="method_week" value="week">Week</option>
<option name="method" id="method_month" value="month">Month</option>
<option name="method" id="method_year" value="year">Year</option>
</select>
</label>
<div style="clear:both;"></div>
</div>
<div class="input-control">
<label style="Float:left;" for="num2">🚗
<input type="text" id="num2" autofocus>
$</label>
<label style="Float:left;" for="dropdown">
<select>
<option name="method" id="method_week" value="week">Week</option>
<option name="method" id="method_month" value="month">Month</option>
<option name="method" id="method_year" value="year">Year</option>
</select>
</label>
<div style="clear:both;"></div>
</div>
<div class="input-control button">
<button id="calculate">Calculate</button>
</div>
</div>
<div class="container result">
Answer
<p class="answer">0</p>
</div>