Record Editing with jQuery UI Dialog

A simple example of a jQuery UI button and a modal dialog allowing HTML records to be edited.

by Julien Vernet

HTML

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/dark-hive/jquery-ui.css">
<div class="record">
    <p>Name: <span class="name">Chris</span></p>
    <p class="prout">dqsdsds</p>
    <button class="editButton">Edit</button>
</div>

<div class="record">
    <p>Name: <span class="name">Bart</span></p>
    <button class="editButton">Edit</button>
</div>

<div class="record">
    <p>Name: <span class="name">Homer</span></p>
    <button class="editButton">Edit</button>
</div>




<div id="response">This is the response DIV</div>

<div id="dialogContent" title="This is a dialog box">
    <p>You can have whatever you need inside a dialog box and program the buttons to do whatever you like.</p>
    
    <form action="#" method="post" id="editForm">
        <label for="myInput">dsqd</label>
        <input type="text" id="myInput" name="myInput" value="" />
        <br>
        <label for="test">Hello</label>
        <input type="text" id="test" name="test" value="" />
    </form>
</div>

CSS

body { padding: 15px; font-size: 11px; font-family: Arial }
#dialogContent { display:none; }
#response { border: 1px solid green; margin-top:20px; padding:15px; }
#dialogContent p { margin-bottom: 1.5em; }
.record { margin-bottom:20px; padding:5px; border: 1px solid red; }

JavaScript

//Global variable to 'remember' which record you're editing.
var record;

//set up the button styling and click functionality
$('.editButton')
    .button({ icons: { primary: "ui-icon-document" }})
    .click(function() {
        //set which record we're editing so we can update it later
        record = $(this).parents('.record');
        //populate the editing form within the dialog
        $('#myInput').val(record.find('.name').html());
        $('#test').val(record.find('.prout').html());
        //show the dialog
        $( "#dialogContent" ).dialog( "open" )
    });


//set up the dialog box.
$( "#dialogContent" ).dialog({
    autoOpen: false,
    modal: true,
    buttons: {
        OK: function() {            
            $('#response').html('The value entered was ' + $('#myInput').val());
            record.find('.name').html($('#myInput').val());
            record.find('.prout').html($('#test').val());
            $( this ).dialog( "close" );
        },        
        Cancel: function() {
            $('#response').html('The Cancel button was clicked');
            $( this ).dialog( "close" );
        }
    }
});