Sudarshan Kalebere
Sudarshan Kalebere

Reputation: 3929

Adding object to my array of objects using javascript functions

So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks

<html>
<head>
    <title></title>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<body>          
    <input placeholder="name" type="text"  id="name"></br>
    <input placeholder="rno" type="text"  id="rollno"></br>
    <input type="submit" value="Add Roll" id="add" >
    <script type="text/javascript">
        $(document).ready(function(){
            console.log("loaded");
            var list=[
                      {name:"sud",rno:1},
                      {name:"diya",rno:2},
                      {name:"sakshi",rno:3}
                      ];

            for(i=0;i<list.length;i++){             
                console.log("old list is"+list[i].rno+"\t"+
                    list[i].name);          
            };

            $("#add").click(function(){
                var rno = $("#rollno").val();
                var name = $("#name").val();
               //here i want to add rno and name to my list 
                for(i=0;i<list.length;i++){             
                console.log("new list is"+list[i].rno+"\t"+
                    list[i].name);          
                };
            });
        });
    </script>
</body>
</html>

Upvotes: 0

Views: 71

Answers (2)

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

to append to an array you can use push

list.push({name:"sudarshan",rno:"33"});  

or just

list[list.length] = {name:"sudarshan",rno:"33"}; 

which is the same as above.

Upvotes: 0

Richard Foster
Richard Foster

Reputation: 608

Array#push adds items to the end of an array. eg: arr.push("test");

$("#add").click(function(){
    var rno = $("#rollno").val();
    var name = $("#name").val();

    // Use Array#push to add an item to an array.
    // No need to use `new` when using the `{}` syntax for object creation.
    list.push({name:"sudarshan",rno:"33"});

    // Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
    for(var i = 0; i < list.length; i++){             
        console.log("new list is"+list[i].rno+"\t"+list[i].name);          
    };
});

Upvotes: 1

Related Questions