Unable to access object created froma constructor function

4243 views javascript
7

Here's my problem: I have two input fields and upon button click a function is triggered to create a new object (from an object constructor function) using those two input values.

The console.log included in the function displays both object.input1 and object.input2 in the correct way. However, once the function is completed and I try console-logging again the newly created object OR object.input1 OR object.input1, I am getting 'undefined'

If I push the newly created object into an array, it's okay and I can access the object from the array, but not sure how to access the object elements when inside an array. Anyway, I don't understand what I have done wrong when creating the new object. Any help would be greatly appreciated.

<html>

<input type="number" id='input1' placeholder="Enter number only">
<input type="text" id='input2' placeholder="Max length 300" maxlength='300'>
<button id='btn'>Submit</button>


<script>
    var day1, notes1, day1List;


    function DayList(day, notes) {

        this.day = day;
        this.notes = notes;
    }

    document.getElementById('btn').onclick =

        function() {

            var day1 = document.getElementById('input1').valueAsNumber;

            var notes1 = document.getElementById('input2').value;

            var day1List = new DayList(day1, notes1);

            console.log(day1List.day, day1List.notes);

        }
</script>
</html>

answered question

1 Answer

0

Even though you are declaring the variables globally:

var day1, notes1, day1List;

You are not setting these, since you are redeclaring them in the function scope:

function() {
    var day1 = document.getElementById('input1').valueAsNumber;
    var notes1 = document.getElementById('input2').value;
    var day1List = new DayList(day1, notes1);
}

Simply remove the var declaration to apply to the global scope:

function() {
    day1 = document.getElementById('input1').valueAsNumber;
    notes1 = document.getElementById('input2').value;
    day1List = new DayList(day1, notes1);
}

Looking at your structure however, I believe you only really need day1List as a global variable. The rest appear to be stored in it.

posted this

Have an answer?

JD

Please login first before posting an answer.