codeofaninja
website

JavaScript Array CRUD Example

Photo of Mike Dalisay
Modified Thursday, November 22, 2012
by - @ninjazhai
Our code for today will give us example on how to Create, Read, Update and Delete (CRUD) items in a
JavaScript array. This technique will give you full control over the fields and values of each array item.

Example use of this code is when you have long rows of input elements and wanted to detect only the elements with inputted values, get their id, value and other related information. You won't have to loop through all the input elements to check if there are inputted values.

This is because, you can instantly add an item to the array if the value was inputted, edit it when the value were changed, delete it when the value were removed and then read it for posting or later use. We can achieve better performance. Here is a video demo:



CRUD


Our index.php code - here you can see the our JavaScript CRUD functions (with some jQuery help) and sample HTML.

<html>
    <head>
        <title>JS Array CRUD - http://codeofaninja.com</title>
    </head>
   
<body>

<!--
    -example row of items
    -id is the item number
    -common class name
-->
Item 1 <input type='text' id='1' class='item' /><br />
Item 2 <input type='text' id='2' class='item' /><br />
Item 3 <input type='text' id='3' class='item' /><br />
Item 4 <input type='text' id='4' class='item' /><br />
Item 5 <input type='text' id='5' class='item' /><br />

<br />
<br />

<!-- display the operations here -->
<b>Actions:</b>
<div id='status'></div>

<br />

<!-- display the array length and items -->
<b>All Items:</b>
<div id='results'></div>

<!-- include the jquery -->
<script type='text/javascript' src='jquery.min.js'></script>

<script type='text/javascript'>
    // initialize array as global variable
    var items = [];
   
    $(document).ready(function(){
   
        //we use the jquery blur event
        $('.item').blur(function(){
       
            //in this example, the item id is the id attribute of the element
            var item_id = $(this).attr('id');
           
            //item value is the inputtedvalue
            var item_value = $(this).val();
           
            //then process the item
            process_item(item_id,item_value);
        });
       
    });
   
    // ------------ functions [START] ------------

    // process item, usually based in item id
    function process_item(item_id,item_value){
       
        if(item_value==""){
            //if item value is empty, delete from the array
            delete_item(item_id);
        }else if(checkIfExists(item_id)){
            //search if item_id exists in the array
            //if item exists, edit it
            edit(item_id,item_value);
        }else if(!checkIfExists(item_id)){
            //if item does not exist, add it
            add(item_id,item_value);
        }
       
        //read the items
        showAllItems();
    }
   
    // ADD
    function add(item_id,item_value){
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("Successfully added.");
    }

    // EDIT
    function edit(item_id,item_value){
       
        //delete first
        items.remove("item_id", item_id);
       
        //then add again
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("successfully edited.");
           
    }
   
    // DELETE
    function delete_item(item_id){
        items.remove("item_id", item_id);
        $("#status").text("Successfully deleted.");
    }
   
    // READ
    function showAllItems(){
       
        //clear results text
        $("#results").text("");
       
        var arr_len = items.length;
       
        // display also the array length
        $("#results").append("Array len: " + arr_len+ "<br />");
       
        //loop through the array to read the items
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            //append to results div to display
            $("#results").append("item_id: " + item_id + " >>> item_value: " + item_value + "<br />");
        }
    }
   
    function checkIfExists(check_item_id){
       
        //get the array length first
        var arr_len = items.length;
       
        //search the array
        //there might be another way
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            if(check_item_id==item_id){
                //it means the item exists
                return true;
            }
        }
       
        return false;
    }
   
    //needs a remove function
    Array.prototype.remove = function(name, value) {
        array = this;
        var rest = $.grep(this, function(item){
            return (item[name] != value);  
        });

        array.length = rest.length;
        $.each(rest, function(n, obj) {
            array[n] = obj;
        });
    };
    // ------------ functions [END] ------------
</script>

</body>
</html>

Convert to JSON

You can also convert the array to a JSON this way:

Add the json2.js file from here.

<script type='text/javascript' src='json2.js'></script>

...and do this

var json_str= JSON.stringify(items);

Posting the Array

If you want to post the resulting array..

1. Prepare the PHP file that will receive the post value. I created get_post.php with the code:

<?php
//just to display raw values
echo "<pre>";
    print_r($_POST);
echo "</pre>";

//access the values
foreach($_POST['items'] as $item){
    echo $item['item_id'] . ":" . $item['item_value'] . "<br />";
}
?>

2. Add a button and a new div area to our index.php

The button:

<input type='button' value='Post Array' id='post' />

Div area where we can see the posted values..

<!-- display the posted items value -->
<b>Posted Items:</b>
<div id='postedItems'></div>

3. Clicking the post array button will show the posted value to postedItems div.

$('#post').click(function(){
    $.ajax({
        url: "get_post.php",
        data: {'items': items},
        type: 'post',
        success: function(data) {
            $('#postedItems').append(data);
        }
    });
});

The value posted to get_post.php look like this:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_value] => john
                )

            [1] => Array
                (
                    [item_id] => 3
                    [item_value] => michael
                )

        )

)

Thanks for reading this JavaScript CRUD example!
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.