JavaScript CRUD Tutorial – Step By Step Guide!

Previously, we learned how to create, read, update, delete, search, and paginate data with our simple REST API tutorial in PHP.

Today, this tutorial will demonstrate a step-by-step approach to creating a CRUD (Create, Read, Update, Delete) application using JavaScript.

We will utilize a pre-existing REST API as the back-end and create a user-friendly front-end interface to interact with the data. This guide is perfect for developers learning to create dynamic web applications using JavaScript.

We will also incorporate search and pagination functionality to enhance the user experience. By the end of this tutorial, you will have a solid understanding of how to create a fully-functional CRUD application using JavaScript and a REST API. Let's get started!

Overview

What Is JavaScript? JavaScript is a programming language used to make websites interactive and dynamic. It is used on the client side, meaning it runs on the user's device (such as a computer or phone) rather than on a server.

It is used on 98% of websites and is often used in conjunction with HTML and CSS to create a complete web experience. With JavaScript, you can update content, control multimedia, and create animations.

But this tutorial will focus on creating, reading, updating, and deleting database records. We will do it using JavaScript, JSON, and PHP. JSON data will be handled by the REST API built using PHP.

I highly recommend studying the previous tutorials first before proceeding here. But if you think you can take this one, then go on.

Program Output

Below are the screenshots of our tutorial's final result. You can click an image to view the larger version of it.

Create a record.
Read list of records.
Read one record.
When delete button was clicked.

Let’s proceed to the step-by-step tutorial.

Set Up The REST API

In this tutorial, we will use a REST API built with PHP.

We did not include REST API source code because we were hoping you could focus on learning to code with JavaScript, not PHP.

But the good news is we made a separate tutorial about how to build a simple REST API with PHP. Click here to learn the step-by-step PHP REST API tutorial.

I highly recommend learning our REST API tutorial first. This is because we will use that API for the rest of this tutorial.

But if you already have your REST API that will work with this tutorial, that's also okay.

In my case, one example where I can access the REST API is: http://localhost/api/product/read.php

That link will show me the list of products from the database, in JSON format. It looks like the following screenshot.

Our JavaScript app will consume the data above. The list of products will be displayed in the Bootstrap table with buttons like "Read One," "Update," and "Delete." This tutorial will show it in the "How To Read JSON Data Using JavaScript?" section.

By the way, I'm using a Chrome extension called JSONView to make the JSON data readable in the browser.

Create index.html file

Create index.html file on your project's main folder. Open that file and put in the following code.

<!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">
    <title>Read Products</title>
    <!-- bootstrap CSS -->
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<!-- custom CSS -->
	<link href="app/assets/css/style.css" rel="stylesheet" />
</head>
<body>
<!-- our app will be injected here -->
<div id="app"></div>
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
    </script>
<!-- bootbox for confirm pop up -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<!-- app js script -->
<script src="app/app.js"></script>
<!-- products scripts -->
<script src="app/products/read-products.js"></script>
<script src="app/products/create-product.js"></script>
<script src="app/products/read-one-product.js"></script>
<script src="app/products/update-product.js"></script>
<script src="app/products/delete-product.js"></script>
</body>
</html>

Create custom CSS file

  1. Create "app" folder.
  2. Open the "app" folder and create the "assets" folder.
  3. Open the "assets" folder and create the "css" folder.
  4. Open the "css" folder and create "style.css" file.

The "style.css" file is our custom CSS file. You can put any CSS in this file for additional web page styling. In our case, we have the following CSS code inside the "style.css" file.

.m-r-10px{ margin-right:10px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-15px{ margin-bottom:15px; }
.m-b-20px{ margin-bottom:20px; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }
.display-none{ display:none; }
.padding-bottom-2em{ padding-bottom:2em; }
.width-30-pct{ width:30%; }
.width-40-pct{ width:40%; }
.overflow-hidden{ overflow:hidden; }
.margin-right-1em{ margin-right:1em; }
.right-margin{ margin:0 .5em 0 0; }
.margin-bottom-1em { margin-bottom:1em; }
.margin-zero{ margin:0; }
.text-align-center{ text-align:center; }

Use jQuery, Bootstrap, and Bootbox.js libraries

As you can see in the index.html file, we use jQuery and Bootbox.js libraries.

jQuery JavaScript library is needed to make it easy to control interactions like button clicking and form submission. In this tutorial, we are using jQuery version 3.6.0. jQuery CDN is here.

Bootstrap makes it easy for us to have a beautiful user interface. We are using Bootstrap version 3.3.7 in this tutorial. Bootstrap CDN is here.

Bootbox.js library is needed to make the "delete" confirmation dialog box look better. We are using Bootbox.js version 4.4.0 in this tutorial. Bootbox.js CDN is here.

Create app.js file

The "app.js" file contains some basic HTML and JavaScript functions that other JS files in our app can use.

  1. Open "app" folder.
  2. Inside that "app" folder, create "app.js" file.
  3. Open "app.js" file and put the following code.
$(document).ready(function(){
    // app html
    var app_html=`
        <div class='container'>
            <div class='page-header'>
                <h1 id='page-title'>Read Products</h1>
            </div>
            <!-- this is where the contents will be shown. -->
            <div id='page-content'></div>
        </div>`;
    // inject to 'app' in index.html
    $("#app").html(app_html);
});
// change page title
function changePageTitle(page_title){
	// change page title
	$('#page-title').text(page_title);
	// change title tag
	document.title=page_title;
}
// function to make form values to json format
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Create "products" scripts

Now, we will create several JavaScript files.

  1. Open "app" folder.
  2. Create "products" folder inside "app" folder.
  3. Create the following files inside "products" folder:
    • read-products.js
    • create-product.js
    • read-one-product.js
    • update-product.js
    • delete-product.js

What's the code inside the JavaScript files above? For now, we will leave them empty. But we will fill them out in the next several sections of this tutorial.

Output

Our code so far will have almost empty output. It should look like the following.

How To Read JSON Data Using JavaScript?

Show products on first page load

  1. Open "app" folder.
  2. Open "products" folder inside the "app" folder.
  3. Open read-products.js file inside the "products" folder.

The following code will call the showProducts() method on first load of the web page.

The showProducts() will show the list of products in an HTML table. Put the following code inside read-products.js file.

$(document).ready(function(){
    // show list of product on first load
    showProducts();
});
// showProducts() method will be here

Show products on click of a button

The following code will call showProducts() method in a click of a button with read-products-button class.

The button can be found in the "create product" and "update product" HTML template. We will see it in the next sections.

Put the following code under the showProducts(); of the previous section.

// when a 'read products' button was clicked
$(document).on('click', '.read-products-button', function(){
	showProducts();
});

Create showProducts() function

Now we will create the showProducts() method. Replace // showProducts() method will be here comment in read-products.js file with the following code.

// function to show list of products
function showProducts(){
}

Get list of products

The following code will contact our API to get the list of products in JSON format. Put the following code after the opening curly brace of the previous section.

// get list of products from the API
$.getJSON("http://localhost/api/product/read.php", function(data){
});

Add "Create Product" button

We have to add a "Create Product" button in the "products list" view. We will make this button work later in this tutorial.

Place the following code after the opening curly brace of the previous section.

// html for listing products
var read_products_html=`
    <!-- when clicked, it will load the create product form -->
    <div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
        <span class='glyphicon glyphicon-plus'></span> Create Product
    </div>

Build HTML table

We have to start building the HTML table where the list of products will appear.

The following code will build an HTML table with its heading. Place it after the previous section's code.

<!-- start table -->
<table class='table table-bordered table-hover'>
    <!-- creating our table heading -->
    <tr>
        <th class='w-25-pct'>Name</th>
        <th class='w-10-pct'>Price</th>
        <th class='w-15-pct'>Category</th>
        <th class='w-25-pct text-align-center'>Action</th>
    </tr>`;
	// rows will be here
// end table
read_products_html+=`</table>`;

Build table row per record

We will loop through each record returned by the API. In each record, we will create a table row.

Aside from product data, the table row will have the "action" buttons as well. These include the "Read One", "Edit" and "Delete" buttons.

Replace "// rows will be here" comment of the previous section with the following code.

// loop through returned list of data
$.each(data.records, function(key, val) {
    // creating new table row per record
    read_products_html+=`
        <tr>
            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>
            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>
                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>
                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>
        </tr>`;
});

Inject to page content

We have to make the HTML table appear on our webpage. We will do this by injecting the table into the "page-content" div.

Place the following code after the closing "table" tag

// inject to 'page-content' of our app
$("#page-content").html(read_products_html);

5.9 Change page title

The following code will change the "title" seen on the web page and the "title" seen on the browser tab.

Place the following code after the previous section's code.

// chage page title
changePageTitle("Read Products");

Output

After doing all the steps above, the output should look like the following.

How To Create or Insert Data Using JavaScript?

Handle "Create Product" Button Click

  1. Open "app" folder.
  2. Open "products" folder inside the "app" folder.
  3. Open create-product.js file inside the "products" folder.

The following code will handle a click of a button. This button should have "create-product-button" class.

Place the following code inside create-product.js file.

$(document).ready(function(){
    // show html form when 'create product' button was clicked
    $(document).on('click', '.create-product-button', function(){
		// categories api call will be here
    });
	// 'create product form' handle will be here
});

Get list of categories from API

We need to get list of categories from the API because we will build the "categories" select field. This is where the user can select the category of the product.

Replace "// categories api call will be here" of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){
});

Build "categories option" select field

This is where we build the HTML "select" field with the "categories" option.

Place the following code after the opening curly brace of the previous section.

// build categories option html
// loop through returned list of data
var categories_options_html=`<select name='category_id' class='form-control'>`;
$.each(data.records, function(key, val){
    categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`;
});
categories_options_html+=`</select>`;

Add "Read Products" button

The "read products" button is needed so that we can go back to the products list.

Place the following code after the previous section's code.

// we have our html form here where product information will be entered
// we used the 'required' html5 property to prevent empty fields
var create_product_html=`
    <!-- 'read products' button to show list of products -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Build "Create Product" HTML Form

Now we will build the actual "creat product" HTML form. This is where the user can enter the new product information that will be sent to the server.

Place the following code after the previous section's code.

<!-- 'create product' html form -->
<form id='create-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>
        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' required /></td>
        </tr>
        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input type='number' min='1' name='price' class='form-control' required /></td>
        </tr>
        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required></textarea></td>
        </tr>
        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>
        <!-- button to submit form -->
        <tr>
            <td></td>
            <td>
                <button type='submit' class='btn btn-primary'>
                    <span class='glyphicon glyphicon-plus'></span> Create Product
                </button>
            </td>
        </tr>
    </table>
</form>`;

Show "Create Product" form and change page title

We have to make the HTML button and form appear on our web page. We will change the page title as well.

Place the following code after the previous section's code.

// inject html to 'page-content' of our app
$("#page-content").html(create_product_html);
// chage page title
changePageTitle("Create Product");

Handle "create product" form submit

If the "create product" form is submitted, we need a script to handle it.

Find "// 'create product form' handle will be here" and replace it with the following code.

// will run if create product form was submitted
$(document).on('submit', '#create-product-form', function(){
	// form data will be here
});

Get form data

This is how we get data entered in our "create product" HTML form.

Replace "// form data will be here" of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

Now we will send the data to the server.

Place the following code after the previous section's code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/create.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});
return false;

Output

The output should look like the following.

How To Read One Data Using JavaScript?

Handle "read one" button click

The "read one" button is seen on the "product list" view. When click, it should show the complete product details.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "read-one-product.js" file.

Place the following code inside "read-one-product.js" file.

$(document).ready(function(){
    // handle 'read one' button click
    $(document).on('click', '.read-one-product-button', function(){
		// product ID will be here
    });
});

Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace "// product ID will be here" of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

Read one record from API

We will send the product ID to the API. It will return the data based on the given ID.

Place the following code after the previous section's code.

// read product record based on given ID
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
	// read products button will be here
});

Add "read products" button

We need the "read products" button so we can go back to the products list.

Replace "// read products button will be here" of the previous section with the following code.

// start html
var read_one_product_html=`
    <!-- when clicked, it will show the product's list -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Show record data in HTML table

We will place the product information returned by the API to an HTML table.

Place the following code after the previous section's code.

<!-- product data will be shown in this table -->
<table class='table table-bordered table-hover'>
    <!-- product name -->
    <tr>
        <td class='w-30-pct'>Name</td>
        <td class='w-70-pct'>` + data.name + `</td>
    </tr>
    <!-- product price -->
    <tr>
        <td>Price</td>
        <td>` + data.price + `</td>
    </tr>
    <!-- product description -->
    <tr>
        <td>Description</td>
        <td>` + data.description + `</td>
    </tr>
    <!-- product category name -->
    <tr>
        <td>Category</td>
        <td>` + data.category_name + `</td>
    </tr>
</table>`;

Show "Read One Product" HTML table and change page title

We have to make the HTML button and table appear on our web page. We will change the page title as well.

Place the following code after the previous section's code.

// inject html to 'page-content' of our app
$("#page-content").html(read_one_product_html);
// chage page title
changePageTitle("Create Product");

Output

The output should look like the following.

How To Update Data Using JavaScript?

Handle "udpate product" button click

The "edit" button is seen on the "product list" view. When click, it should show the "update product" form filled out with product information.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "update-product.js" file.

Place the following code inside "update-product.js" file.

$(document).ready(function(){
    // show html form when 'update product' button was clicked
    $(document).on('click', '.update-product-button', function(){
		// product ID will be here
    });
	// 'update product form' submit handle will be here
});

8.2 Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace "// product ID will be here" of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

Read product information

To fill out our "update product" HTML form, we need to get product information from the API.

Place the following code after the previous section's code.

// read one record based on given product id
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
	// values will be used to fill out our form
	var name = data.name;
	var price = data.price;
	var description = data.description;
	var category_id = data.category_id;
	var category_name = data.category_name;
	// load list of categories will be here
});

Get list of categories

A list of categories is needed for product category options. Category records will be rendered as options in a "select" HTML input field.

Replace "// load list of categories will be here" of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){
	// build 'categories option' html
	// loop through returned list of data
        var categories_options_html=`<select name='category_id' class='form-control'>`;
        $.each(data.records, function(key, val){
            // pre-select option is category id is the same
            if(val.id==category_id){ categories_options_html+=`<option value='` + val.id + `' selected>` + val.name + `</option>`; }
            else{ categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`; }
        });
        categories_options_html+=`</select>`;
	// update product html will be here
});

Add "Read Products" button

The "read products" button is needed so that we can go back to the products list.

Replace "// update product html will be here" of the previous section with the following code.

// store 'update product' html to this variable
var update_product_html=`
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Build "Update Product" form

Now we will build the "update product" HTML form. This form will be built with an HTML table and the input fields are filled out with product information.

Place the following code after the previous section's code.

<!-- build 'update product' html form -->
<!-- we used the 'required' html5 property to prevent empty fields -->
<form id='update-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>
        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input value=\"` + name + `\" type='text' name='name' class='form-control' required /></td>
        </tr>
        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input value=\"` + price + `\" type='number' min='1' name='price' class='form-control' required /></td>
        </tr>
        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required>` + description + `</textarea></td>
        </tr>
        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>
        <tr>
            <!-- hidden 'product id' to identify which record to delete -->
            <td><input value=\"` + id + `\" name='id' type='hidden' /></td>
            <!-- button to submit form -->
            <td>
                <button type='submit' class='btn btn-info'>
                    <span class='glyphicon glyphicon-edit'></span> Update Product
                </button>
            </td>
        </tr>
    </table>
</form>`;

Show "Update Product" form and change page title

We need to show our "update product" HTML on our webpage. We will change the page title as well.

Put the following code after the previous section's code.

// inject to 'page-content' of our app
$("#page-content").html(update_product_html);
// chage page title
changePageTitle("Update Product");

Handle "udpate product" form submission

If the "update product" form is submitted, we need a script to handle it.

Find "// 'update product form' submit handle will be here" and replace it with the following code.

// will run if 'create product' form was submitted
$(document).on('submit', '#update-product-form', function(){
	// get form data will be here 
	return false;
});

Get form data

We will get the product information from our "update product" HTML form.

Replace "// get form data will be here" of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

Send form data to server

After getting the form data, we will send the data to our API.

Place the following code after the previous section's code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/update.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});

Output

The output should look like the following.

How To Delete Data Using JavaScript?

Handle "Delete Product" button click

The "delete product" button is seen in the "read products" view. When it was clicked, we need to handle it.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "delete-product.js" file.

Place the following code inside "delete-product.js" file.

$(document).ready(function(){
    // will run if the delete button was clicked
    $(document).on('click', '.delete-product-button', function(){
		// product id will be here
	});
});

Get product ID

The product ID is needed to identify which record to delete using the API.

Replace "// product id will be here" of the previous section with the following code.

// get the product id
var product_id = $(this).attr('data-id');

Show "delete confirmation" dialog box

This is where we will use the Bootbox.js library. We will show a dialog box with "Are you sure?" message with "Yes" and "No" buttons.

Place the following code after the previous section's code.

// bootbox for good looking 'confirm pop up'
bootbox.confirm({
	message: "<h4>Are you sure?</h4>",
	buttons: {
		confirm: {
			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
			className: 'btn-danger'
		},
		cancel: {
			label: '<span class="glyphicon glyphicon-remove"></span> No',
			className: 'btn-primary'
		}
	},
	callback: function (result) {
		// delete request will be here
	}
});

Delete record using API

If the user clicked "Yes" on the dialog box, a "delete" request will be sent to the API.

Replace "// delete request will be here" of the previous section with the following code.

if(result==true){
	// send delete request to api / remote server
	$.ajax({
		url: "http://localhost/api/product/delete.php",
		type : "POST",
		dataType : 'json',
		data : JSON.stringify({ id: product_id }),
		success : function(result) {
			// re-load list of products
			showProducts();
		},
		error: function(xhr, resp, text) {
			console.log(xhr, resp, text);
		}
	});
}

Output

How To Search Data Using JavaScript?

This feature is part of our LEVEL 2 source code.

Include two JS file in index.html

<!-- products scripts -->
<script src="app/products/products.js"></script>
<script src="app/products/search-product.js"></script>

Create products.js file

The "products.js" file will contain any functions that can be used by other product components like our "read-products.js" or "search-products.js" files.

Open "app" folder. Open "products" folder. Create "products.js" file.

Open the "products.js" file and put the following code.

// product list html
function readProductsTemplate(data, keywords){
    var read_products_html=`
		<!-- search products form -->
		<form id='search-product-form' action='#' method='post'>
		<div class='input-group pull-left w-30-pct'>
			<input type='text' value='` + keywords + `' name='keywords' class='form-control product-search-keywords' placeholder='Search products...' />
			<span class='input-group-btn'>
				<button type='submit' class='btn btn-default' type='button'>
					<span class='glyphicon glyphicon-search'></span>
				</button>
			</span>
		</div>
		</form>
		<!-- when clicked, it will load the create product form -->
		<div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
			<span class='glyphicon glyphicon-plus'></span> Create Product
		</div>
		<!-- start table -->
		<table class='table table-bordered table-hover'>
			<!-- creating our table heading -->
			<tr>
				<th class='w-25-pct'>Name</th>
				<th class='w-10-pct'>Price</th>
				<th class='w-15-pct'>Category</th>
				<th class='w-25-pct text-align-center'>Action</th>
			</tr>`;
    // loop through returned list of data
    $.each(data.records, function(key, val) {
        // creating new table row per record
        read_products_html+=`<tr>
            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>
            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>
                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>
                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>
        </tr>`;
    });
    // end table
    read_products_html+=`</table>`;
    // inject to 'page-content' of our app
    $("#page-content").html(read_products_html);
}

Create search-product.js file

The "search-product.js" file will contain a code that catches the submission of the "search product" form.

Open "app" folder. Open the "products" folder. Create "search-products.js" file.

Open the "search-products.js" file and put the following code.

$(document).ready(function(){
    // when a 'search products' button was clicked
    $(document).on('submit', '#search-product-form', function(){
        // get search keywords
        var keywords = $(this).find(":input[name='keywords']").val();
        // get data from the api based on search keywords
        $.getJSON("http://localhost/api/product/search.php?s=" + keywords, function(data){
            // template in products.js
            readProductsTemplate(data, keywords);
            // chage page title
            changePageTitle("Search products: " + keywords);
        });
        // prevent whole page reload
        return false;
    });
});

Change read-products.js

We want the "product list" and "search product" to have the same HTML table template. To do this, we will use the readProductsTemplate() function of the products.js file.

Open "app" folder. Open "products" folder. Open the "read-products.js' file. Change the showProducts() function to the following code.

// function to show list of products
function showProducts(){
    // get list of products from the API
    $.getJSON("http://localhost/api/product/read.php", function(data){
        // html for listing products
        readProductsTemplate(data, "");
        // chage page title
        changePageTitle("Read Products");
    });
}

Output

How To Paginate Data Using JavaScript?

This feature is part of our LEVEL 2 and LEVEL 3 source codes.

Change JSON URL

To make pagination work, we'll have to change the JSON URL. The contents of this new JSON data will include the "paging" node. It looks like the following.

So we will change the JSON URL from:

http://localhost/api/product/read.php

to

http://localhost/api/product/read_paging.php

It means we have to change something in our code. See the change in the next section.

Show products using JSON URL

Open /app/products/read-products.js file. Replace the code with the following.

$(document).ready(function(){
    // show list of product on first load
    showProductsFirstPage();
    // when a 'read products' button was clicked
    $(document).on('click', '.read-products-button', function(){
        showProductsFirstPage();
    });
    // when a 'page' button was clicked
    $(document).on('click', '.pagination li', function(){
        // get json url
        var json_url=$(this).find('a').attr('data-page');
        // show list of products
        showProducts(json_url);
    });
});
function showProductsFirstPage(){
    var json_url="http://localhost/api/product/read_paging.php";
    showProducts(json_url);
}
// function to show list of products
function showProducts(json_url){
    // get list of products from the API
    $.getJSON(json_url, function(data){
        // html for listing products
        readProductsTemplate(data, "");
        // chage page title
        changePageTitle("Read Products");
    });
}

Add Pagination HTML

Open /app/products/products.js file. Find the ending "table" tag and put the following code under it.

// pagination
if(data.paging){
    read_products_html+="<ul class='pagination pull-left margin-zero padding-bottom-2em'>";
        // first page
        if(data.paging.first!=""){
            read_products_html+="<li><a data-page='" + data.paging.first + "'>First Page</a></li>";
        }
        // loop through pages
        $.each(data.paging.pages, function(key, val){
            var active_page=val.current_page=="yes" ? "class='active'" : "";
            read_products_html+="<li " + active_page + "><a data-page='" + val.url + "'>" + val.page + "</a></li>";
        });
        // last page
        if(data.paging.last!=""){
            read_products_html+="<li><a data-page='" + data.paging.last + "'>Last Page</a></li>";
        }
    read_products_html+="</ul>";
}

Output

After making the changes above, run index.html again. Do a hard refresh. You should see the paging buttons like the one below.

Download source codes

Choose your download

FEATURESBASICPRO
Create product
Read product
Read one product
Update product
Delete product
Bootstrap UI
Search products-
Pagination of products & search products-
Create category-
Read category-
Read one category-
Update category-
Delete category-
Search categories-
Pagination of categories & search categories-
Navigation bar-
Inline editing of products & categories-
Export CSV of products & categories-
Bootstrap tooltip on some products & categories buttons-
Use the buttons below to download. ↓BASICPRO

How To Run The Source Code?

We recommend that you first follow and study our well-detailed, step-by-step tutorial above. Nothing beats experience when it comes to learning.

But we believe you will learn faster if you also see the final source code. We consider it your additional guide.

Imagine the value or skill upgrade it can bring you. You can get additional income from your work, projects, or business. The precious time you save. Isn't that what you want?

By now, you need to download our source codes. To do it, use any download buttons in the next few sections below.

Once you have downloaded the source codes, here's how you can run it.

  1. Extract the files to your server directory.
  2. Set up the "api" by following the README.txt inside the "api" folder.
  3. Open your browser and run index.html
  4. If you can see the list of "product" records, it means your set up is correct.

Why download?

Do you need more reasons to download it?

MORE REASONS TO DOWNLOAD THE CODEALL
Use new skills for your multiple projectsYES
Save huge amount of time learning jQuery AJAXYES
Code examples are direct to the pointYES
Well explained and commented source codeYES
Fast and friendly email supportYES
Free source code updatesYES

What's Next?

Next, we will learn about authenticating users with REST API. Go to our REST API Authentication Example in PHP.

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

★★★★★ “Wow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

★★★★★ “The fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

★★★★★ “Thanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

★★★★★ “Hey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

★★★★★ “Words can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful JavaScript CRUD Tutorial – Step By Step Guide! Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our JavaScript CRUD Tutorial – Step By Step Guide! helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about JavaScript CRUD Tutorial – Step By Step Guide!

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Move Options Between Two Select Boxes

Today we are going to do a code that can move options between two select boxes and save the changes to the database.

I think this functionality will improve the user experience since the interface is intuitive.

In this example, we are going to have the first select box (left side) which contains the list or data of available objects, the buttons that will make the options move either to the left or right, the second select box (right side) which contains the list of assigned objects, and of course, the save button.

See my video demo here:

assigned_objects table – this will be used to store the ids of assigned objects.

CREATE TABLE IF NOT EXISTS `assigned_objects` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` int(11) NOT NULL COMMENT ‘1=user,2=location’,
  `object_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

locations table – this will be used to store the location objects

—
— Table structure for table `locations`
—
CREATE TABLE IF NOT EXISTS `locations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
 
—
— Dumping data for table `locations`
—
 
INSERT INTO `locations` (`id`, `name`) VALUES
(1, ‘Cavite’),
(2, ‘Laguna’),
(3, ‘Batangas’),
(4, ‘Rizal’),
(5, ‘Quezon’),
(6, ‘Antiipolo’),
(7, ‘Capiz’),
(8, ‘Boracay’),
(9, ‘Mindoro’),
(10, ‘Novaliches’);

Our index.php code:

<html>
    <head>
        <title>Move Options Between Two Select Boxes And Save Changes To Database</title>
        <!– include some style –>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
    </head>
<body>
<?php
//connect to database
include ‘db_connect.php’;
 
//if the form was submitted
if( $_POST ){
 
    //delete previously assigned locations
    //in this example, type = 2 means “location”
    $sql = “delete from assigned_objects where type = 2”;
     
    //execute the sql
    if( $mysqli->query( $sql ) ){
     
        //if the query was executed successfully
        //save newly assigned names
        //$_POST[‘location_right’] is the select box on the right side
        foreach( $_POST[‘location_right’] as $value ){
             
            //write save query
            $sql = “insert into assigned_objects ( type, object_id ) 
                        values( 2, “ . $mysqli->real_escape_string( $value ) . ” )”;
 
            //execute save sql query
            if( !( $mysqli->query( $sql ) ) ){
                 
                //if the query execution was unsuccessful
                echo “<div>Database Error: Unable to insert record.</div>”;
            }
             
        }
         
    }else{
        //if unable to delete previously assigned locations
        echo “<div>Database Error: Unable to delete assigned locations.</div>”;
    }
     
}
 
//get ids of currently assigned locations 
$sql = “select * from assigned_objects where type = 2”;
$result = $mysqli->query( $sql );
 
if( $result ){
     
    //$location_in will be our variable to accumulate currently assigned locations ids
    //example value will be “46, 49, 51”, 
    //which will be used to exempt currently assigned locations (right select box) 
    //to available locations list (left select box)
    $location_in = “”;
     
    //get number of rows found
    $num = $result->num_rows;
     
    if( $num ){ //if there are assigned locations in the database
     
        //set $x to 1, the first loop
        $x = 1;
         
        while( $row = $result->fetch_assoc() ){ //loop the accumulate values
         
            //object_id is actually the location id
            $location_in .= $row[‘object_id’];
             
            //when $x is less than the total number of rows, append a comma
            //else, do not append a comma
            if( $x < $num ){
                $location_in .= “, “;
            }
             
            //increment $x
            $x++;
        }
         
    }
 
}else{
    //when there’s an error selecting the assigned locations
    echo “Database Error: Unable to select assigned locations.”;
}
 
?>
 
<div>
 
<!–
    here on our form, the onsubmit value is very important,
    it will select all the values in the location_right select box,
    which is to be saved in the database.
    see the javascript section for details about selectAll()
–>
<form action=’index.php’ method=’post’ onsubmit=”return selectAll( new Array( ‘location_right’ ) );”>
 
    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_left’ id=’location_left’ size=’7′ multiple=’multiple’>
            <?php
             
            if( $location_in ){ //if $location_id has a value, there are location ids to be exempted
                $sql = “select * from locations where id not in ( {$location_in} ) order by name”; 
            }else{
                //else, select all locations
                $sql = “select * from locations”; 
            }
             
            $result = $mysqli->query( $sql );
 
            if( $result ){
                //if it returns a result, loop through it with options tag
                while( $row = $result->fetch_assoc() ){
                    echo “<option value=’{$row[‘id’]}‘>{$row[‘name’]}</option>”;
                }
            }
            ?>
        </select>
    </div>
 
    <!– direction move buttons –>
    <div class=’btn’>
        <!– option move to right button –>
        <button type=”button” onclick=”move( ‘location_left’, ‘location_right’ )”> > </button>
        <br />
        <!– option move to left button –>
        <button type=”button” onclick=”move( ‘location_right’, ‘location_left’ )”> < </button>
    </div>
 
    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_right[]’ id=’location_right’ size=’7′ multiple=’multiple’>
         
            <?php       
            //query joining assigned_objects and locations table
            //so we can easily get the location_name
            $sql = “select
                        l.id as location_id, 
                        l.name as location_name 
                    from 
                        assigned_objects ao, locations l
                    where 
                        ao.type = 2 
                        and ao.object_id in ( {$location_in} )
                        and ao.object_id = l.id”;
                     
            $result = $mysqli->query( $sql );
 
            if( $result ){
                //if query successful, loop through the values with option tag
                //so it will show up in the select list
                while( $row = $result->fetch_assoc() ){
                     
                    echo “<option value=’{$row[‘location_id’]}‘>{$row[‘location_name’]}</option>”;
                 
                }
            }
             
            ?>
        </select>
         
    </div>
     
    <div style=’clear:both;’></div>
    <input type=’submit’ value=’Save’ />
     
</form>
 
<script type=’text/javascript’>
//this function will select all the values of the right select box, so you can post it
//this function can accept array of select boxes with id as its reference
function selectAll( obj_arr ){
 
    var obj_sel;
    for ( var i = 0; i < obj_arr.length; i++ ){
     
        obj_sel = document.getElementById( obj_arr[i] );
         
        for( var j = 0; j < obj_sel.options.length; j++ ){
            obj_sel.options[j].selected = true;
        }
         
    }
     
}
 
function move( id_1, id_2 ){
         
        //the box where the value will come from
        var opt_obj = document.getElementById( id_1 );
         
        //the box where the value will be locationd
        var sel_obj = document.getElementById( id_2 );
         
        for ( var i = 0; i < opt_obj.options.length; i++ ){ //loop to check for multiple selections
                 
                if ( opt_obj.options[i].selected == true ){ //check if the option was selected
                         
                        //value to be transfered
                        var selected_text = opt_obj.options[i].text;
                        var selected_value = opt_obj.options[i].value;
                         
                        //remove from opt
                        opt_obj.remove( i );
                         
                        //decrease value of i since an option was removed 
                        //therefore the opt_obj.options.length will also decrease
                        i–;
                         
                        //process to sel
                        var new_option_index = sel_obj.options.length;
                        sel_obj.options[new_option_index] = new Option( selected_text, selected_value );
                         
                }
                 
        }
}
         
</script>
 
</body>
</html>

I have another example here that uses two objects which are users and locations. See my video demo:

users table – this will be used to store the user objects.

—
— Table structure for table `users`
—
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ;
 
—
— Dumping data for table `users`
—
 
INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `username`, `password`, `modified`) VALUES
(28, ‘John’, ‘Dalisay’, ”, ‘john’, ‘john123’, ‘2012-01-15 15:26:14’),
(39, ‘Jemski’, ‘Panlilios’, ‘[email protected]’, ‘jemboy09’, ‘jem123’, ‘2012-03-17 23:20:05’),
(40, ‘Darwin’, ‘Dalisay’, ”, ‘dada08’, ‘dada123’, ‘2012-01-15 15:25:34’),
(46, ‘Jaylord’, ‘Bitamug’, ”, ‘jayjay’, ‘jay123’, ‘2012-01-15 15:27:04’),
(49, ‘Justine’, ‘Bongola’, ”, ‘jaja’, ‘jaja123’, ‘2012-01-15 15:27:21’),
(50, ‘Jun’, ‘Sabayton’, ”, ‘jun’, ‘jun123’, ‘2012-02-05 18:15:14’),
(51, ‘Lourd’, ‘De Veyra’, ”, ‘lourd’, ‘lourd123’, ‘2012-02-05 18:15:36’),
(52, ‘Asi’, ‘Taulava’, ”, ‘asi’, ‘asi123’, ‘2012-02-05 18:15:58’),
(53, ‘James’, ‘Yap’, ”, ‘james’, ‘jame123’, ‘2012-02-05 18:16:17’),
(54, ‘Chris’, ‘Tiu’, ”, ‘chris’, ‘chris123’, ‘2012-04-11 17:16:29’);

The code download is included in the download link above of this post. I have written this code few years ago with MySQL, but you can easily convert it to MySQLi or PDO though. Here’s the mysql_index.php code:

<html>
        <head>
                <title>Move Options Between Two Select Boxes</title>
                 
                <style type=’text/css’>
                        select{
                                width:200px;
                        }
                         
                        .select_box{
                                float:left;
                                margin:0 0 20px 0;
                        }
                         
                        .btn{
                                float:left;
                                margin:20px;
                        }
                </style>
        </head>
<body>
<?php
//connect to database
include ‘mysql_db_connect.php’;
 
if( $_POST ){
 
    //delete previously assigned names
    $sql = “delete from assigned_objects where type = 1”;
    mysql_query( $sql );
     
    //save newly assigned names
    foreach( $_POST[‘name_right’] as $value ){
         
        $sql = “insert into assigned_objects ( type, object_id ) values( 1, {$value} )”;
        mysql_query( $sql );
         
    }
     
    //delete previously assigned locations
    $sql = “delete from assigned_objects where type = 2”;
    mysql_query( $sql );
     
    //save newly assigned locations
    foreach( $_POST[‘location_right’] as $value ){
         
        $sql = “insert into assigned_objects ( type, object_id ) values( 2, {$value} )”;
        mysql_query( $sql );
         
    }
     
}
 
//(name) prepare id values for IN
$sql = “select * from assigned_objects where type = 1”;
$rs = mysql_query( $sql );
 
$in = “”;
$x = 1;
$num = mysql_num_rows( $rs );
 
if( $num ){
    while( $row = mysql_fetch_array( $rs ) ){
        extract( $row );
        $in .= $object_id;
         
        if( $x < $num ){
            $in .= “, “;
        }
         
        $x++;
    }
}
 
//(location) prepare id values for IN
$sql = “select * from assigned_objects where type = 2”;
$rs = mysql_query( $sql );
 
$location_in = “”;
$x = 1;
$num = mysql_num_rows( $rs );
 
if( $num ){
    while( $row = mysql_fetch_array( $rs ) ){
        extract( $row );
        $location_in .= $object_id;
         
        if( $x < $num ){
            $location_in .= “, “;
        }
         
        $x++;
    }
}
?>
 
<!–
    here on our form, the onsubmit value is very important,
    it will select all the values in the location_right select box,
    which is to be saved in the database.
    see the javascript section for details about selectAll()
–>
<form action=’#’ method=’post’ onsubmit=”return selectAll( new Array( ‘name_right’, ‘location_right’ ) );”>
 
    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Users</div>
        <div style=’clear:both;’></div>
        <select name=’name_left’ id=’name_left’ size=’7′ multiple=’multiple’>
         
            <?php
             
            if( $in ){ //if $in has a value, there are location ids to be exempted
                $sql = “select * from users where id not in ( {$in} ) order by firstname”; 
            }else{
                //else select all users
                $sql = “select * from users”; 
            }
             
            $rs = mysql_query( $sql );
             
            while( $row = mysql_fetch_array( $rs ) ){
                extract( $row );
                echo “<option value=’{$id}‘>{$firstname} {$lastname}</option>”;
            }
             
            ?>
        </select>
    </div>
 
        <!– direction move buttons –>
        <div class=’btn’>
            <!– move to right button –>
            <button type=”button” onclick=”move( ‘name_left’, ‘name_right’ )”> > </button>
            <br />
            <!– move to left button –>
            <button type=”button” onclick=”move( ‘name_right’, ‘name_left’ )”> < </button>
        </div>
 
    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Users</div>
        <div style=’clear:both;’></div>
        <select name=’name_right[]’ id=’name_right’ size=’7′ multiple=’multiple’>
         
            <?php       
             
            $sql = “select
                        u.id as user_id, 
                        u.firstname as fn,
                        u.lastname as ln
                    from 
                        assigned_objects ao, users u
                    where 
                        ao.type = 1
                        and ao.object_id in ( {$in} )
                        and ao.object_id = u.id”;
            $rs = mysql_query( $sql );
             
            while( $row = mysql_fetch_array( $rs ) ){
                 
                echo “<option value=’{$row[‘user_id’]}‘>{$row[‘fn’]} {$row[‘ln’]}</option>”;
                 
            }
             
            ?>
        </select>
         
    </div>
 
    <div style=’clear:both;’></div>
 
    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_left’ id=’location_left’ size=’7′ multiple=’multiple’>
            <?php
             
            if( $location_in ){
                $sql = “select * from locations where id not in ( {$location_in} ) order by name”; 
            }else{
                $sql = “select * from locations”; 
            }
             
            $rs = mysql_query( $sql );
             
            while( $row = mysql_fetch_array( $rs ) ){
                extract( $row );
                echo “<option value=’{$row[‘id’]}‘>{$row[‘name’]}</option>”;
            }
             
            ?>
        </select>
    </div>
 
        <!– direction move buttons –>
        <div class=’btn’>
            <!– move to right button –>
            <button type=”button” onclick=”move( ‘location_left’, ‘location_right’ )”> > </button>
            <br />
            <!– move to left button –>
            <button type=”button” onclick=”move( ‘location_right’, ‘location_left’ )”> < </button>
        </div>
 
    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_right[]’ id=’location_right’ size=’7′ multiple=’multiple’>
         
            <?php       
            $sql = “select
                        l.id as location_id, 
                        l.name as location_name 
                    from 
                        assigned_objects ao, locations l
                    where 
                        ao.type = 2 
                        and ao.object_id in ( {$location_in} )
                        and ao.object_id = l.id”;
            $rs = mysql_query( $sql );
             
            while( $row = mysql_fetch_array( $rs ) ){
                 
                echo “<option value=’{$row[‘location_id’]}‘>{$row[‘location_name’]}</option>”;
                 
            }
             
            ?>
             
        </select>
    </div>
     
    <div style=’clear:both;’></div>
    <input type=’submit’ value=’Save’ />
         
</form>
 
<script type=’text/javascript’>
 
function selectAll( obj_arr ){
 
    var obj_sel;
    for ( var i = 0; i < obj_arr.length; i++ ){
     
        obj_sel = document.getElementById( obj_arr[i] );
         
        for( var j = 0; j < obj_sel.options.length; j++ ){
            obj_sel.options[j].selected = true;
        }
         
    }
     
}
 
function move( id_1, id_2 ){
         
        //the box where the value will come from
        var opt_obj = document.getElementById( id_1 );
         
        //the box where the value will be locationd
        var sel_obj = document.getElementById( id_2 );
         
        for ( var i = 0; i < opt_obj.options.length; i++ ){ //loop to check for multiple selections
                 
                if ( opt_obj.options[i].selected == true ){ //check if the option was selected
                         
                        //value to be transfered
                        var selected_text = opt_obj.options[i].text;
                        var selected_value = opt_obj.options[i].value;
                         
                        //remove from opt
                        opt_obj.remove( i );
                         
                        //decrease value of i since an option was removed 
                        //therefore the opt_obj.options.length will also decrease
                        i–;
                         
                        //process to sel
                        var new_option_index = sel_obj.options.length;
                        sel_obj.options[new_option_index] = new Option( selected_text, selected_value );
                         
                }
                 
        }
}
         
</script>
 
</body>
</html>

If you have many object types stored in your database, you have to use a loop to generate the pair of select boxes and buttons.

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12441" text="Download Now" style="button" color="green"]

Thank you for learning from our post about: Move Options Between Two Select Boxes.

How To Use Vertical TinyDropdown 2

Hi guys, today I wanna share to you the code I tweaked with this amazing multi-level JavaScript Dropdown Menu by Scriptiny.

In my opinion, it looks fast, smooth and clean.

The hover animation is really nice. I love it.

But there’s a problem. The script provided by Scriptiny is for horizontal dropdown menu only (as you can see in the picture above). But I needed it to be a vertical dropdown menu like some people were asking about. I’m gonna show you the example code I tweaked to make this a vertical dropdown menu.

Our index.html code looks like the following.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
    <head>
        <meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1” />
        <title>TinyDropdown 2 Vertical Version</title>
         
        <link rel=“stylesheet” href=“tinydropdown.css” type=“text/css” />
        <script type=“text/javascript” src=“tinydropdown.js”></script>
         
    </head>
<body>
     
     
<div class=“nav”>
    <ul id=“menu” class=“menu”>
        <li>
            <span>One</span>
            <ul style=‘top: 0; margin-left: 170px;’>
                <li><a href=“#”>One</a></li>
                <li><a href=“#”>Two</a></li>
                <li><a href=“#”>Three</a></li>  
                <li><a href=“#”>Four</a></li>
            </ul>
        </li>
         
        <li>
            <span>Two</span>
            <ul style=‘top: 0; margin-left: 170px;’>
             
                <li>
                    <a href=“#”>One</a>
                    <ul>
                        <li><a href=“#”>One</a></li>
                        <li><a href=“#”>Two</a>
                            <ul>
                                <li><a href=“#”>One</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                 
                <li><a href=“#”>Two</a></li>
                 
            </ul>
        </li>
         
        <li>
            <span>Three</span>
            <ul style=‘top: 0; margin-left: 170px;’>
                <li><a href=“#”>One</a></li>
                <li><a href=“#”>Two</a></li>
            </ul>
        </li>
        <li>
            <span>Four</span>
            <ul style=‘top: 0; margin-left: 170px;’>
                <li><a href=“#”>One</a></li>
                <li><a href=“#”>Two</a></li>
            </ul>
        </li>
        <li>
            <span><a href=‘#’>Five</a></span>
        </li>
         
    </ul>
</div>
<script type=“text/javascript”>
    var dropdown=new TINY.dropdown.init(“dropdown”, {id:’menu’, active:’menuhover’});
</script>
 
</body>
</html>

Our tinydropdown.css code:

*{
    margin:0; 
    padding:0; 
    outline:0;
}
.nav {
    height:auto; 
    width: 170px; 
    float:left; 
    background:#aaa; 
    color:#fff; 
    /*text-shadow:1px 1px #888; */
    z-index:1000;
}
 
.menu a {
    color:#fff; 
    text-decoration:none; 
    width:170px; 
    height:auto; 
    display:block;
}
 
.menu span {
    color:#fff; 
    text-decoration:none; 
    width:170px; 
    height:auto; 
    font-weight:bold;
    display:block;
}
 
.menu a:hover {
    color:#fff; 
    height:auto; 
    background:#999;
    display:block;
    height:auto;
    width:170px;
}
 
.menu {
    list-style:none; 
    font:16px Arial,Verdana; 
    text-align:center; 
    width:600px; 
    margin:0 auto;
}
 
.menu li {
    position:relative;
    width:170px; 
    z-index:1000;
    height:auto; 
    line-height:30px;
    background:#AAAAAA;
    /*line-height:28px; this is responsible for line height*/
    border-bottom:thin solid #fff;
     
}
 
.menu ul {
    display:none; 
    position:absolute; 
    font:normal 16px Arial,Verdana; 
    top:36px; 
    left:0; 
    background:#aaa; 
    display:none; 
    list-style:none;
}
 
.menu ul li {
    float:none; 
    width:170px;
    display:block;
}
 
.menu ul li a, li.menuhover li a, li.menuhover li.menuhover li a {
    float:none; 
    display:block; 
    background:none; 
    height:auto; 
     
    width:170px;
    display:block;
     
}
 
.menu ul li a:hover, li.menuhover li a:hover, li.menuhover li.menuhover li a:hover {
    background:#999; 
    color:#fff;
    height:auto; 
     
    width:170px;
    display:block;
     
}
 
.menu ul li span, li.menuhover li span, li.menuhover li.menuhover li span {
    float:none; 
    display:block; 
    background:none; 
    height:auto; 
     
     
    width:170px;
}
 
.menu ul ul {
    left:170px; 
    top:0;
}
.menu li.submenu {
     
}
 
.menu li.noborder {
    border-top:none;
}
 
li.menuhover a, li.menuhover li.menuhover a {
    color:#fff; 
    background:#999; 
    height:auto; 
     
    width:170px;
    display:block;
     
}
 
li.menuhover span, li.menuhover li.menuhover span {
    color:#fff; 
    background:#999;
    height:auto; 
     
    width:170px;
    display:block;
     
}
 
#info {
    width:180px; 
    background:#eee;
}
 
#info li {
    width:160px; 
    border-top:none; 
    padding:8px 10px; 
    color:#666; 
    /*text-shadow:1px 1px #fff; */
    text-align:left;
}

Our tinydropdown.js code:

var TINY={};
function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}
 
TINY.dropdown=function(){
    var p={fade:1,slide:1,active:0,timeout:200}, init=function(n,o){
        for(s in o){p[s]=o[s]} p.n=n; this.build()
    };
    init.prototype.build=function(){
        this.h=[]; this.c=[]; this.z=1000;
        var s=T$$(‘ul’,T$(p.id)), l=s.length, i=0; p.speed=p.speed?p.speed*.1:.5;
        for(i;i<l;i++){
            var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i];
            h.onmouseover=new Function(p.n+‘.show(‘+i+‘,1)’);
            h.onmouseout=new Function(p.n+‘.show(‘+i+‘)’)
        }
    };
    init.prototype.show=function(x,d){
        var c=this.c[x], h=this.h[x];
        clearInterval(c.t); clearInterval(c.i); c.style.overflow=‘hidden’;
        if(d){
            if(p.active&&h.className.indexOf(p.active)==-1){h.className+=‘ ‘+p.active}
            if(p.fade||p.slide){
                c.style.display=‘block’;
                if(!c.m){
                    if(p.slide){
                        c.style.visibility=‘hidden’; c.m=c.offsetHeight; c.style.height=‘0’; c.style.visibility=”
                    }else{
                        c.m=100; c.style.opacity=0; c.style.filter=‘alpha(opacity=0)’
                    }
                    c.v=0
                }
                if(p.slide){
                    if(c.m==c.v){
                        c.style.overflow=‘visible’
                    }else{
                        c.style.zIndex=this.z; this.z++; c.i=setInterval(function(){slide(c,c.m,1)},20)
                    }
                }else{
                    c.style.zIndex=this.z; this.z++; c.i=setInterval(function(){slide(c,c.m,1)},20)
                }
            }else{
                c.style.zIndex=this.z; c.style.display=‘block’
            }
        }else{
            c.t=setTimeout(function(){hide(c,p.fade||p.slide?1:0,h,p.active)},p.timeout)
        }
    };
    function hide(c,t,h,s){
        if(s){h.className=h.className.replace(s,”)}
        if(t){c.i=setInterval(function(){slide(c,0,-1)},20)}else{c.style.display=‘none’}
    }
    function slide(c,t,d){
        if(c.v==t){
            clearInterval(c.i); c.i=0;
            if(d==1){
                if(p.fade){c.style.filter=”; c.style.opacity=1}
                c.style.overflow=‘visible’
            }
        }else{
            c.v=(t–Math.floor(Math.abs(t–c.v)*p.speed)*d);
            if(p.slide){c.style.height=c.v+‘px’}
            if(p.fade){var o=c.v/c.m; c.style.opacity=o; c.style.filter=‘alpha(opacity=’+(o*100)+‘)’}
        }
    }
    return{init:init}
}();

The output of the codes above will look like this:

Also, if you want my version of its horizontal dropdown menu, output looks like this:

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12435" text="Download Now" style="button" color="green"]

Thank you for learning from our post about: How To Use Vertical TinyDropdown 2.

Sample Use of JavaScript OnFocus and OnBlur Event

You can see this example on many sites today such as yahoo mail.

When you click on the search box, the word “Search” will go.

When you click on another part of the webpage, the word “Search” comes back in it.

HOW TOs.

Step 1: Create your index.html file and put the following codes:

<html>
     <head>
          <title>Sample Use of JavaScript OnFocus and OnBlur Event</title>
     </head>
<body>
     <input type="text" value="Type keywords here..." size="40"
       OnFocus="if(this.value=='Type keywords here...') this.value='';"
       OnBlur="if(this.value=='') this.value = 'Type keywords here...';" />
</body>
</html>

TIPs

This thing is used often in search boxes. You will save webpage space ‘coz you won’t have to put the label “Search” before the search box

Thank you for reading! Belated Merry Christmas and Advanced Happy New Year Everyone! :)