Skip to content
Advertisement

(Javascript) Trying to make class methods use input values

im working on a very simple program that allows me to calculate my budget. Still trying to learn JS, and having few problems that I cant find answers to.

class Money {
    constructor(type, amount){
        this.type = String(type);
        this.amount = Number(amount);
    }
    addItem(){
        if(this.type !== null && this.amount !== null){
            let new_li = document.createElement('li')
            new_li.innerHTML = (`${this.type + ' - ' + this.amount}`);
            document.getElementById('btn_income').addEventListener('click', this.addItem)
            document.getElementById('income_list').appendChild(new_li);
            new_li.setAttribute('id','new_item');
            clearInput();
        }
        else{
            alert('Please fix your errors!');
        }
    }

I need to get the value of the inputs i have in html

 <input name="typ" type="text" id="p_type" placeholder="Type of income"/>
 <input name="amount" type="text" id="p_amount" placeholder="Amount" />
 <button id="btn_income">Add</button>

The question is, how can i make the addItem() method to the values of the inputs specified in html? Huge thanks in advance

Advertisement

Answer

That might can help you, u have to addEventListener outside of your class, when an event happens, and pass their data from inputs. Here is an example

    class Money {
        addItem(type, amount) {
            if (amount && type) {
                let list = document.getElementById('list')
                let li = document.createElement('li')
                li.innerHTML = (`${type + ' - ' + amount}`);
                list.appendChild(li)
            }
            else {
                alert('Please fix your errors!');
            }
        }
    }

    const type = document.getElementById('p_type')
    const amount = document.getElementById('p_amount')
    const btn = document.getElementById('btn_income')
    btn.addEventListener('click', () => {
        const myMoney = new Money()
        myMoney.addItem(type.value, amount.value)
        type.value = null
        amount.value = null
    })
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input name="typ" type="text" id="p_type" placeholder="Type of income" />
    <input name="amount" type="text" id="p_amount" placeholder="Amount" />
    <button id="btn_income">Add</button>
    <ul id="list">
    </ul>
</body>
</html>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement