HTML5 and CSS3, Second Edition

(singke) #1
html5_content_editable/show.html
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<scriptsrc="javascripts/edit.js"></script>

Then we can write the code to save our data when it changes:


html5_content_editable/javascripts/edit.js
$("#edit_profile_link").hide();
varstatus= $("#status");
$("span[contenteditable]").blur(function(){
varfield= $(this).attr("id");
varvalue= $(this).text();

varresourceURL= $(this).closest("ul").attr("data-url");

$.ajax({
url:resourceURL,
dataType:"json",
method:"PUT",
data:field+"="+ value,
success:function(data){
status.html("Therecordwas saved.");
},
error:function(data){
status.html("Therecordfailedto save.");
}
});
});
➤ }

We add an event listener to every span on the page that has the contenteditable
attribute. So, when the user tabs away from a field, all we have to do is submit
the data to our server-side script using jQuery’s ajax() method. When we coded
up the web page we added the server-side URL to the data-url attribute of the
<ul> tag, so we grab that URL and construct our request to the server. This
is just an example—we don’t have a back end to save this, and writing one
is beyond the scope of this book. However, you’ll learn about a few ways you
can save user data on client machines in Chapter 9, Saving Data on the Client,
on page 183.

Falling Back


We’ve done a bunch of things that won’t work for some of our audience. First,
we’ve created a dependency on JavaScript to save the edited results back to
the server, which is a bad thing. Rather than worrying much about situations
that might prevent a user from using our technique, let’s just give users the

Chapter 3. Creating User-Friendly Web Forms • 62


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf