Request.JSON
sending a JSON request to the jsFiddle backend.
Later on parse and display the data.
HTML
<!DOCTYPE html>
<body>
<h2>Add a User:</h2>
<form>
<input type="text" name="username" placeholder="name" />
<input type="email" name="email" placeholder="email" />
<button>add user</button>
</form>
<h2>Users:</h2>
<ul id="users"></ul>
</body>
CSS
input.error {
background-color: #FFFFB8;
}
div.error {
border: 1px dashed red;
border-radius: 6px;
color: red;
padding: 5px;
margin: 10px;
-webkit-box-shadow: 1px 1px 3px #c1c1c1;
-moz-box-shadow: 1px 1px 3px #c1c1c1;
box-shadow: 1px 1px 3px #c1c1c1;
}
ul {
margin: 15px;
border: 1px solid #c1c1c1;
border-radius: 6px;
padding: 8px;
-webkit-box-shadow: 1px 1px 3px #c1c1c1;
-moz-box-shadow: 1px 1px 3px #c1c1c1;
box-shadow: 1px 1px 3px #c1c1c1;
}
ul > li {
border-bottom: 1px solid #DFDFDF;
padding: 5px;
}
ul > li:last-child {
border-bottom: none;
}
JavaScript
/*
Assignement:
HTML: Complete the HTML to have semantic and compliant markups.
JAVASCRIPT: Dynamically add a user to the users list.
- Highlight the email input when a user enters an invalid email address and display following message: "please enter a valid email address" in red.
- Use the add_user function to submit the user's data.
- If the ajax request returns an error, display the error message in red.
- Display the newly added user in the users list when the request was successful.
BONUS:
- no jQuery
- add some CSS3 properties
*/
// START YOUR CODE HERE
$(function () {
var $form = $('form');
var $email = $('[name=email]', $form);
var $username = $('[name=username]', $form);
var simpleEmailValidation = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var formCallback = function (data) {
if (data && data.success) { // If Success
addUserToList($username.val(), $email.val());
} else { // If failure
if (data.error) {
showError(data.error);
}
}
};
$form.on('submit', function (e) {
resetForm();
var username = $username.val(),
email = $email.val();
if (simpleEmailValidation.test(email)) { // If Email Is Valid
addUser(username, email, formCallback);
} else { // If email is not valid
showError('please enter a valid email address');
$('[name=email]').addClass('error').focus();
}
e.preventDefault();
});
});
function showError(errorText) {
$("form").prepend($('<div/>', {
'class': 'error',
text: errorText
}));
}
function resetForm() {
$("div.error").remove();
$('input').removeClass("error");
}
function addUserToList(username, email) {
var $list = $('ul');
$list.append('<li>' + username + ' - ' + email + '</li>');
}
// END YOUR CODE HERE
// Do not modify this function. Add user service wrapper.
function addUser(username,...