HTML and CSS Reference
In-Depth Information
if (!Modernizr.localstorage) {
alert("This browser doesn't support HTML5 Local Storage!");
}
$("#submit").click(SubmitData);
$("#irstName").change(function () { storage["FirstName"] = $(this).val(); });
$("#lastName").change(function () { storage["LastName"] = $(this).val(); });
$("#email").change(function () { storage["Email"] = $(this).val(); });
$("#irstName").val(storage["FirstName"]);
$("#lastName").val(storage["LastName"]);
$("#email").val(storage["Email"]);
GetQuestions();
})
A reference to the
localStorage
object is stored in a global variable—
storage
—for the sake of
convenience. The
click
event of the Submit Answers button is wired to the
SubmitData()
function. The
change
event handlers of the
firstName,
,
lastName
, and
email
text boxes are also wired. These
change
event
handlers retrieve the text box value using the
val()
method and save it in
localStorage
. This way, as soon
as users begin typing in these text boxes, their values are automatically saved in
localStorage
. If a user is
revisiting the survey form and the
firstName,
,
lastName
, and
email
values are already stored, then these
pieces are retrieved from
localStorage
and filled in the text boxes.
The
GetQuestions()
function is then invoked to fetch survey questions.
GetQuestions()
is shown in
Listing 7-7.
Listing 7-7.
GetQuestions()
Client-Side Function
function GetQuestions() {
$.ajax({
type: "POST",
url: "/Home/GetQuestions",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (results) {
for (var i = 0; i < results.length; i++) {
$("#container").append("<div data-questions-questionid='" +
results[i].QuestionID + "'>" +
results[i].QuestionText + "</div>");
$("div[data-questions-questionid]").addClass("paddedDiv");
}
GetChoices();
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
})
}
The
GetQuestions()
function invokes the
GetQuestions()
action method using
$.ajax()
. The
GetQuestions()
action method returns an array of question items. The
success
handler function iterates
through this array, and with each iteration, a
<div>
is dynamically added to the container. The
GetQuestions()
action method is shown in Listing 7-8.