JSFiddle - React, Tailwind, and code Playground
by igalst
HTML
<h1>Register new person</h1>
<button type="button" id="toggleForm">Show form</button>
<form>
<label for="firstName">First Name</label>
<input type="text" id="firstName" class="input">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" class="input">
<label for="email">Email</label>
<input type="text" id="email" class="input">
<label for="age">Age</label>
<input type="text" id="age" class="input">
<label for="city">City</label>
<select id="city" class="input"></select>
<div>
<input type="checkbox" id="terms">
<label for="terms">I accept the terms and conditions</label>
</div>
<button type="submit">Send</button>
<p id="error" class="error"></p>
</form>
CSS
form {
display: none;
}
.input {
display: block;
}
.error {
display: none;
color: red;
border: dotted 3px yellow;
padding: 10px;
}
JavaScript
var cities = [
"Tel Aviv",
"Bat Yam",
"Holon"];
function fillCities() {
var option;
var select = $("#city");
if (select.children().length > 0) {
return;
}
// for (var j = 0; j < 9999; j++) {
for (var i = 0; i < cities.length; i++) {
option = $("<option>" + cities[i] + "</option>");
select.append(option);
}
// }
}
var toggleFormButton = $("#toggleForm");
toggleFormButton.click(function () {
fillCities();
var form = $("form");
// Show or hide the form each time depending on its current visibility
if (!form.is(":visible")) {
form.slideDown();
toggleFormButton.text("Hide form");
} else {
form.slideUp();
toggleFormButton.text("Show form");
}
});
$("form").submit(function (event) {
if (!$("#terms").is(":checked")) {
abortSendWithError(event, "Please accept terms");
return;
}
// TODO 1: Make sure age has only digits
// TODO 2: Make sure names do not have digits
// TODO 3: Make the email is valid (has @ and . inside of them - do not use RegEx, use indexOf)
// TODO 4: Make sure each name is longer than 2 chars if the input is not empty
if ($("#age").val() == "" || $("#age").val() < 18) {
abortSendWithError(event, "You must be over 18 to register");
return;
}
if (!$.isNumeric($('#age').val())) {
abortSendWithError(event, "Your age can contain numbers only");
return;
}
if (isContainsDigits($('#firstName').val()) || isContainsDigitsc($('#lastName').val())) {
abortSendWithError(event, "Your name cannot contain digits");
return;
}
if ($("#email").val().indexOf("@") < 0 || $("#email").val().lastIndexOf(".") < 0) {
abortSendWithError(event, "Your email is not valid.");
return;
}
if ($("#firstName").val().length > 0 && $("#lastName").val().length > 0) {
abortSendWithError(event, "You may...