Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.5 kB
1
Indexable
Never
 // common function for getting input value

function getInputValue(value) {
    const inputValue = document.getElementById(value).value;
    document.getElementById(value).value = '';
    return inputValue;
}

// using common function for getting input value

document.getElementById('calculate-btn').addEventListener('click', function () {
    const incomeInput = parseFloat(document.getElementById('inp-income').value);
    const foodInput = parseFloat(getInputValue('inp-food'));
    const rentInput = parseFloat(getInputValue('inp-rent'));
    const clothInput = parseFloat(getInputValue('inp-cloth'));

    // calculation for total expense

    const totalExpense = foodInput + rentInput + clothInput;

// input validation check

    if (isNaN(totalExpense) || isNaN(incomeInput) || totalExpense > incomeInput || totalExpense < 0 || incomeInput < 0 || foodInput <= 0 || rentInput <= 0 || clothInput <= 0) {
        const error = document.getElementById('notify-msg');
        error.style.display = 'block';
        error.style.color = 'red';
    }
    else {
        document.getElementById('total-expense').innerText = totalExpense;
        document.getElementById('balance').innerText = incomeInput - totalExpense;
    }

})

// savings button event handler

document.getElementById('save-btn').addEventListener('click', function () {
    const savingsInput = document.getElementById('inp-save').value;
    const incomeInput = parseFloat(getInputValue('inp-income'));
    const savingsTotal = (incomeInput * savingsInput) / 100;
    document.getElementById('savings').innerText = savingsTotal;

    const mainBalance = document.getElementById('balance').innerText;
    const remainBalance = mainBalance - savingsTotal;

    document.getElementById('remain-balance').innerText = remainBalance;

    if (isNaN(savingsInput) || savingsInput < 0 || savingsInput > 100) {
        const error1 = document.getElementById('savings-error');
        error1.style.display = 'block';
        error1.style.color = 'red';
    }
    else {
        if (remainBalance < 0) {
            const errorMessage = document.getElementById('error-message');
            errorMessage.style.display = 'block';
            errorMessage.style.color = 'red';
        }
        else {
            // document.getElementById('savings').innerText = savingsTotal;
            // document.getElementById('remain-balance').innerText = remainBalance;
        }
    }
})