Home jQuery

Convert a DIV Area to an Editable HTML Form

Hello guys! today we are going to do a code that converts a DIV area to an editable HTML form and save the changes to the database.

We are going to use jQuery, PHP & MySQL ofcourse.

My inspiration for this post is Youtube!

For beginners, this post covers some useful stuff like:

  • jQuery on(), post(), hover(), text(), val(), serialize(), css(), show() and hide() function examples
  • For PDO, we'll cover how to use the SELECT and UPDATE commands for database interaction.
  • You will also learn or see an example on how to submit form without page refresh (AJAX).

Our database would look like this:

  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
– Dumping data for table `users`

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `username`, `password`, `modified`) VALUES
(28, 'John', 'Dalisay', 'Male', 'john', 'john123′, '2012-07-23 13:26:39′);

The Code

our libs/db_connect.php code, change as you needed.

$host = "localhost";
$db_name = "codeofaninja";
$username = "root";
$password = "";
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();

our index.php code:

        <title>Div to Form – https://codeofaninja.com/</title>
        <!–just to include some styles –>
        <link rel="stylesheet" type="text/css" href="css/style.css" />
<div id='banner'>
    <h2>Code of a Ninja Programming Blog</h2>
    <div>Converting a div to an editable HTML form and save changes to database</div>

//just getting the id of the user to be edited
$id = $_REQUEST['id'];

//connect to database
include 'libs/db_connect.php';

try {

    //prepare query
    $query = "select id, firstname, lastname, gender from users where id = ? limit 0,1″;
    $stmt = $con->prepare( $query );
    //this is the first question mark on the query above
    $stmt->bindParam(1, $id);
    //execute our query
    //store retrieved row to $row variable
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    //values to fill up our form
    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $gender = $row['gender'];
}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();

<!–start of our form –>
<form id='user_form'>

<!–id field is hidden, this is used to identify what row is to be edited–>
<input type='hidden' value='<?php echo $id; ?>' name='id'/>

    -just a form made with divs
    -when this div was clicked, it will be a form
<div id='form_div'>
    <div class='field'>
        <div class='field_lbl'>Firstname:</div> <!–field name divs –>
        <div class='field_val'>
            <div class='field_div'>
                    -this shown on page load
                    -and is hidden when the form_div was clicked
                    -and will be shown again when the user clicked anywhere outside the form_div or cancel button
                <div id='firstname_text'><?php echo $firstname; ?></div>
            <div class='field_input'>
                    -this is hidden on page load
                    -and is shown when form_div was clicked
                    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
                <input type='text' value='<?php echo $firstname; ?>' name='firstname' id='firstname'/>
            <div class='clear_fix'></div>
        <div class='clear_fix'></div>
    <div class='clear_fix'></div>
    <!–same explanation above are given to these next fields–>
    <div class='field'>
        <div class='field_lbl'>Lastname:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='lastname_text'><?php echo $lastname; ?></div>
            <div class='field_input'><input type='text' value='<?php echo $lastname; ?>' name='lastname' id='lastname' /></div>
            <div class='clear_fix'></div>
        <div class='clear_fix'></div>
    <div class='clear_fix'></div>
    <div class='field'>
        <div class='field_lbl'>Gender:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='gender_text'><?php echo $gender; ?></div>
            <div class='field_input'>
                <select name='gender' id='gender'>
                    <option <?php if($gender == "Male") echo "selected";  ?> >Male</option>
                    <option <?php if($gender == "Female") echo "selected";  ?>>Female</option>
            <div class='clear_fix'></div>
        <div class='clear_fix'></div>
    <div class='clear_fix'></div>
    -these buttons are hidden on page load
    -they are shown when form_div was clicked
    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
    <div class='btns'>
        <input type='button' value='Save' id='save_btn' />
        <input type='button' value='Cancel' id='cancel_btn' />


<script src="js/jquery.min.js "></script>
<script type='text/javascript'>
$( document ).ready( function(){

    enable_hover(); //hover effect is enabled on page load

    //when clicked the cancel button
    $('body').on('click', '#cancel_btn', function(){
        normal_mode(); //back to normal mode
    //we used the jquery delegate func for live events
    $('body').on('click', '#save_btn', function(){
        //save first here
        //get the current values
        var fn = $('#firstname').val();
        var ln = $('#lastname').val();
        var gender = $('#gender').val();
        //the make it appear in the UI
        //save the actual data
        //we use jquery serialize to serialize the form and easily get the form values
        //this is how to submit or post form without page refresh
            function(data) {
                //you can do any event you want here
                alert(data); //alert that the date were saved
                normal_mode(); //back to normal mode
    //this way we can detect if the user clicked outside the form_div area
    $("body").click(function(e) {
        if (e.target.id == "form_div" || $(e.target).parents("#form_div").size()) { 
            //if clicked inside form_div area,
            //do nothing
        } else {
            //if the user clicked outside the form_div area, 
            //we'll be in normal mode


function edit_mode(){

    $('#form_div').css({ 'background-color' : '#fff' }); //just make a white background
    $('#form_div').unbind('hover'); //disable hover
    $('.field_div').hide(); //hide the text
    $('.field_input').show(); //show the form element
    $('.btns').show(); //show the buttons


//the normal state is the appearance of the page/element when it was first loaded
function normal_mode(){
    enable_hover(); //enable the hover effect again
    $('.field_div').show(); //show the texts
    $('.field_input').hide(); //hide the input elements
    $('.btns').hide(); //hide the buttons

//hover effect is used when NOT in 'edit form' mode
//we unbind this effect when we are in the 'edit form' mode
function enable_hover(){
        function(){ //when we hover form_div, bg will be gray with a bit of rounded corners
                    'background-color' : '#dcdcdc',
                    '-moz-border-radius' : '5px',
                    'border-radius' : '5px'
        function(){ //when mouse is not hovered, bg will be transparent
            $(this).css({'background-color' : 'transparent'});


our save.php code:

//this is where the data were updated/saved
//connect to database
include 'libs/db_connect.php';

    //write query
    //in this case, it seemed like we have so many fields to pass and 
    //its kinda better if we'll label them and not use question marks
    //like what we used here
    $query = "update 
                firstname = :firstname, 
                lastname = :lastname,
                gender = :gender
            where id = :id";

    //prepare query for excecution
    $stmt = $con->prepare($query);

    //bind the parameters
    $stmt->bindParam(':firstname', $_POST['firstname']);
    $stmt->bindParam(':lastname', $_POST['lastname']);
    $stmt->bindParam(':gender', $_POST['gender']);
    $stmt->bindParam(':id', $_POST['id']);
    // Execute the query
    if( $stmt->execute() ){
        echo "Record was updated.";
        echo "Unable to update record.";

}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();

our style.css file:

    font-family:arial, verdana, tahoma;
    margin:0 0 50px 0;

    margin:0 auto;

    padding: 10px;

    margin:0 10px 0 0;




    margin:0 0 0 8px;


Thank you guys for your kind comments, messages and suggestions. I really appreciate it!

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Thank you for learning from our post about Convert a DIV Area to an Editable HTML Form.

Before you write a comment, please read this guide and our code of conduct.
4 replies
  1. sushmit
    sushmit says:

    i am getting error in index.php line no 16

    14 <?php

    15 //just getting the id of the user to be edited

    16 $id =$_REQUEST['id'];

    17 //connect to database

    18 include 'libs/db_connect.php';

    19 try {

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.