I've got the input field, need to check the number only, if value of input is number - another div .hidden should display: block; Also I've got multiple eventlistener on four block- onclick this .hidden block is visible, if it possible combine this event with the form input event.
;
(function() {
var amount_list = document.querySelectorAll('.form-row .donate');
var amount_array = [].slice.call(document.querySelectorAll(".form-row .donate"));
var donerForm = document.getElementById('hidden');
var inputDonateField = document.getElementById('donate-price').value;
var inputNumber = /^[0-9]+$/;
var onClickFormVisible = function() {
donerForm.style.display = "block";
};
var amoutn_array = amount_array.map(function(e) {
return e.addEventListener('click', onClickFormVisible);
});
// var onclickInputNumberDonate = function() {
// // If x is Not a Number or
// if (isNaN(inputDonateField) && inputDonateField.length > 0) {
// console.log(inputDonateField);
// return onClickFormVisible();
//
// } else {
// return false;
// }
// };
function validateForm() {
if (inputDonateField === null || inputDonateField === "") {
alert("Name must be filled out");
return false;
}
}
})();
#hidden {
display: none;
}
<div class="form-row">
<label>Label</label>
<div class="donate">50kr</div>
<div class="donate">100kr</div>
<div class="donate">200kr</div>
<div class="donate">500kr</div>
</div>
<div class="form-row">
<div class="form-col doner-price">
<label for="donate-price">
only number
<input type="text" id="donate-price" name="name" value="">
</label>
</div>
</div>
<div id="hidden">TExt here</div>
Most browsers support type="number", can also have specified ranges with the min and max attributes, and can use the step attribute to accept only certain numbers (for example whole numbers).
<input type="number" min="0" max="50" step="1" />
On submit of the form, you'll still want to verify of course.
IsNan() is useful for filtering out some inputs. Comparing against a regex like new RegExp('^[0-9]+$'); is a safe bet.
As for:
if it possible combine this event with the form input event.
I don't quite know what you're asking.
If you are asking how to validate on both onclick and onsubmit events, just create a function for the validation, like validateInput() and call it for onclick and onsubmit.
element.onclick = function() {
if (isValidInput(inputValue)) {
// More code here
}
}
form.onsubmit = function() {
if (isValidInput(inputValue)) {
// More code here
}
}
function isValidInput(inputValue) {
// Check that input is valid
// Return true / false
}
It's working for me now with keyup input event.
(function() {
var amount_list = document.querySelectorAll('.form-row .donate'); //node-list
var amount_array = [].slice.call(document.querySelectorAll(".form-row .donate")); //node-list to array
var donerForm = document.getElementById('hidden');
var inputDonateField = document.getElementById('donate-price');
var inputNumber = /^[0-9]+$/;
var onClickFormVisible = function() {
donerForm.style.display = "block";
};
var onInputTypeNumber = function() {
if (inputNumber.test(inputDonateField.value)) {
donerForm.style.display = "block";
} else {
return false;
}
};
//onclick event for each amount images
var amoutn_array = amount_array.map(function(e) {
return e.addEventListener('click', onClickFormVisible);
});
//input event only if value === number
inputDonateField.addEventListener("keyup", onInputTypeNumber);
})();
.form-row{display:flex; margin:2rem;}
.donate{
background: #007DBD;
width: 75px;
height:50px;
padding: 1rem;
border: 1px solid black;
}
#hidden{
display:none;
width: 100px;
height:150px;
background: gray;
color: black;
text-align:center;
padding: 2rem;
}
<div class="form-row">
<label>Label</label>
<div class="donate">50kr</div>
<div class="donate">100kr</div>
<div class="donate">200kr</div>
<div class="donate">500kr</div>
</div>
<div class="form-row">
<div class="form-col doner-price">
<label for="donate-price">
only number
<input type="text" id="donate-price" name="name" value="">
</label>
</div>
</div>
<div id="hidden">Only if Input value === to number.You are see this block;</div>
Related
function validate(){
var cekLengthError = 0;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
$(this).children('input:first').focus();
cekLengthError = cekLengthError+1;
} else {
$(this).next().removeClass("show");
}
});
if(cekLengthError == 0){
alert("success")
}
}
When I click validate. Instead it checked the last element first. how to check the first element first? Maybe I was wrong when using this in each function.
Please Check in my fiddle: https://jsfiddle.net/dedi_wibisono17/a7be9zso/50/
Thank you
$(".add").click(function(){
$(".test").append(`
<div class="not-empty"><input type="text" placeholder="name" class="name" /><div class="error">error</div></div>
`)
})
function validate(){
var cekLengthError = 0;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
//$(this).children('input:first').focus();
if($("input.email").val() ==""){
$(".email").focus();
}else if ($("input.name").val() ==""){
$(".name").focus();
}else if ($("input.city").val() ==""){
$(".city").focus();
}else {
}
cekLengthError = cekLengthError+1;
}else{
$(this).next().removeClass("show");
}
});
if(cekLengthError == 0){
alert("success")
}
}
.error{
display:none;
}
.show{
display:block !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lala not-empty">
<input type="text" class="email" placeholder="email" requird>
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="city" placeholder="name">
<div class="error">Error</div>
</div>
<br>
<button class="add">add</button>
<button class="validasi" onclick="validate();">validate</button>
You are always focusing to an element when iterating over the element list. So if you have 5 elements with an error, you are one by one validating then and focusing on them as well due to which last item in the list is getting focus.
Update your code to fix so that you are focusing only on first invalid field:
function validate() {
let cekLengthError = 0;
let foundElemWithError = false;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
if (!foundElemWithError) { // only focus on first invalid field
foundElemWithError = true;
$(this).children('input:first').focus();
}
cekLengthError = cekLengthError + 1;
} else {
$(this).next().removeClass("show");
}
});
if (cekLengthError == 0) {
alert("success")
}
}
var inpts = $('.map-form .val-input');
var radio = $('.map-form .radio-input');
var counter = $('.filtr-map-count');
$('.detect-change').change(function() {
countInputs();
});
function countInputs() {
var click = 0;
$(inpts).each(function(){
if($(this).val() != ""){
click++;
}
counter.text(click);
});
$(radio).each(function() {
if($(this).val() != ""){
click++;
}
counter.text(click);
});
};
$(window).on('load', function() {
countInputs();
});
.filtr-map {
background-color: red;
width: 100px;
height: 40px;
color: #fff;
z-index: 99;
font-weight: bolder;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
margin-top: 50px;
}
.filtr-map-count {
font-size: 10px;
position: relative;
top: -5px;
left: 5px;
background-color: #000;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class='map-form'>
<div>
<h2>Search</h2>
<fieldset>
<label>Price</label>
<span>min</span>
<input type="text" class='val-input detect-change ' value="" />
<span>max</span>
<input type="text" class='val-input detect-change ' value="" />
</fieldset>
<fieldset>
<label>Category</label>
<div class="styled_select">
<select class='val-input detect-change '>
<option value="">Default</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</fieldset>
<fieldset>
<div class="styled_radio"><input class='radio-input detect-change' checked="checked" type="radio" id="Radio1" name="Radio" /><label
class="input" for="Radio1"><span class="circle"><span></span></span><span>Test One Test</span></label></div>
<div class="styled_radio"><input class='detect-change' type="radio" id="Radio2" name="Radio" /><label class="input"
for="Radio2"><span class="circle"><span></span></span><span>Test test</span></label></div>
</fieldset>
<input type="submit" value='Send'>
</div>
</form>
<div class="filtr-map">
Filter<span class='filtr-map-count'>0</span>
</div>
Hey, How to get counter when inputs, select etc. change in form? How to make a counter. If input/select/radio change in fieldset counter should increase, if back to default value decrease. The counter number should also works after page reload. I added a js code with im working on but something goes wrong.
---UPDATE---
I added working jquery code for this example, maybe will be helpful for someone else. Also I added classes that help with select the changed elements.
Ok so this becomes a little more complicated if you're considering all input types.
I have written the code below as a starting point. Yes, it does do what you need it to. BUT it hasn't been fully tested and it can be improved.
See a working example here: https://jsfiddle.net/hber3q0z/
The jQuery that's doing the heavy lifting...
var $form = $('.map-form');
var $counter = $('.filtr-map-count');
var changed = {};
// Listen for an `update` event on counter element
$counter.on('update', function() {
// Update the text value
$(this).text(function() {
var count = 0;
// Loop through the `changed` object and count if value has changed
$.each(changed, function(key, hasChanged) {
if (hasChanged) {
count++;
}
});
// Return count
return count;
});
});
// Find all form inputs
$form.find(':input').each(function(key) {
var $this = $(this);
// Get the input name, else create a temporary name
var name = $this.attr('name') || new Date().getTime().toString() + key;
// Store the original value
var original = $this.val();
// If the input is a checkbox
if ($this.is(':checkbox')) {
// Create a function to get checkbox group values
var checkboxValue = function() {
var values = [];
// Find all `checked` inputs with the same type and name
$form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').each(function() {
// Push values to array
values.push($(this).val());
});
// Join them for easier comparisom
return values.join(',');
};
// Store original group value
original = checkboxValue();
// Listen to checkbox events
$this.on('change keyup keydown mouseup', function() {
// Perform value changed check
changed[name] = checkboxValue() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
// If the input is a radio
else if ($this.is(':radio')) {
// Create a function to get radio group value
var radioValue = function() {
// Find the first `checked` input with the same type and name
return $form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').val();
};
// Store original group value
original = radioValue();
// Listen to radio input events
$this.on('change keyup keydown mouseup', function() {
// Perform value changed check
changed[name] = radioValue() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
// Catch-all other input types
else {
// Listen to input events
$this.on('change keyup keydown cut paste', function() {
// Perform value changed check
changed[name] = $this.val() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
});
The code is checking all inputs in the form for an actual changed value, not just a change event. I have also included support for checkbox and radio groups.
I'm having an issue calculating the difference of two variables that should change depending on input values and number of inputs.
The jQuery works fine adding/subtracting buttons it's the peoplePaid() function that I've been dealing with.
I'm trying to write the difference (.difference) of paidTotal minus each input of pCheck.
So the first question is how do I get the value for difference (paidTotal - pCheck) to write to .difference for each input on the page.
And if I have to loop iy what may need to be done.
Thank you!
$(document).ready(function () {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function (e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i = myNode.childNodes.length - 1;
if (i >= 0) {
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = document.getElementById('paidTotal');
var serviceQuality = document.getElementById('serviceQuality').value;
var difference = document.getElementsByClassName('difference');
var pCheck = 0;
for (var i = 0; i < personsCheck.length; i += 1) {
pCheck += parseFloat(personsCheck[i].value);
}
paidTotal.innerHTML = (checkTotal * serviceQuality) - pCheck;
for (var i = 0; i < personsCheck.length; i += 1) {
checkDifference = parseFloat(paidTotal - pCheck).value;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Check Total</h3>
$ <input type="text" id="check" value="" />
<h3>Tip%</h3>
<select name="tip" id="serviceQuality">
<option disabled selected value="1">-- Choose an Option --</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person" />
<p class="difference">$</p>
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
Disscrepancies
There were some discrepancies that should be addressed:
(Major) There are two functions called by onclick event handlers:
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
First of all, a quick run of this Snippet logs errors about these functions not existing. Secondly, you should never use on-event handlers when using jQuery, it's like using paddle (on-event handlers) on a speed boat (event delegation using .on()).
(Minor) If you store jQuery Objects in variables, do not wrap those variables in $(...) because they already wrapped in $(...) when you declared them:
var addButton = $('#plusOne');
$(addButton).on('click',... // That is like doing this: $($('#plusOne'))
addButton.on('click',...... // This is the cleaner way or...
var $addButton = $('#plusOne');
$addButton.on('click'...... /* This is a common practice which serves as an obvious
reminder that the variable is a jQuery Object */
Plain JavaScript Array Methods
(Core) The solution is to collect all of the input.customer' by gathering the <input>s into a NodeList with .querySelctorAll() and then converting it into an array with Array.from():
var customers = Array.from(document.querySelectorAll('.customer'));
Next, use .map() to extract each of the <input>'s values, and then return them as an array:
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
Finally, use .reduce() to add all of the values in the payments array into one number:
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
Demo
var max = 20;
var count = 1;
var paidTotal = 0;
var customerQty = $('#totalCustomers');
var add = $('#add');
var group = $('.group');
var paid = `
<li>
<input type="number" class="customer" step='0.01'/>
<button type="button" class="remove">-</button>
</li>`;
add.on('click', function(e) {
if (count < max) {
count++;
group.append(paid);
} else {
return false;
}
customerQty.val(count);
});
group.on('click', '.remove', function() {
if (count > 0) {
count--;
var subtract = parseFloat($(this).prev('.customer').val()).toFixed(2);
var total = parseFloat($('#paidTotal').val()).toFixed(2);
var newTotal = parseFloat(total - subtract).toFixed(2);
$('#paidTotal').val(newTotal);
var due = parseFloat($('#balanceDue').val());
$('#balanceDue').val((due + parseFloat(subtract)).toFixed(2));
$(this).parent().remove();
} else {
return false;
}
customerQty.val(count);
});
$('#bill').on('input', totalPaid);
function totalPaid(e) {
var check = $('#check').val();
var tip = $('#tip').val();
var total = $('#paidTotal');
var due = $('#balanceDue');
var customers = Array.from(document.querySelectorAll('.customer'));
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
//console.log('payments: '+payments);
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
$('#amountDue').val(parseFloat(check * tip).toFixed(2));
//console.log('paidTotal: '+paidTotal);
total.val(parseFloat(paidTotal).toFixed(2));
due.val(parseFloat((check * tip) - total.val()).toFixed(2));
}
html {
font: 400 16px/1.5 Consolas;
}
body {
font-size: 1rem;
}
fieldset {
width: 490px;
}
button,
label,
select,
input,
output {
display: inline-block;
font: inherit;
line-height: 1.5;
}
label {
margin: 5px;
}
input {
width: 12ex;
text-align: center
}
button {
cursor: pointer;
}
output {
margin-left: -5px;
}
#totalCustomers {
font-size: 1.2rem;
color: blue;
}
#tip {
padding: 5px 0;
margin-left: -5px;
}
.tip {
margin-left: -2px;
}
.customers {
height: fit-content;
min-height: 60px;
}
.group {
margin: -8% 10px auto -25px;
padding-left: 1.5em;
width: 40%;
list-style-position: inside;
}
.group li {
padding-left: 0.1em;
}
.add {
transform: translate(105%, -15%);
}
/*
For debugging purposes only (Optional)
*/
.as-console-wrapper {
width: 250px;
min-height: 100%;
margin-left: 50%;
background: #000;
color: lime;
}
.as-console-row.as-console-row {
background: #000;
}
.as-console-row.as-console-row::after {
content: '';
padding: 0;
margin: 0;
border: 0;
width: 0;
}
<form id='bill'>
<fieldset class='total'>
<legend>Total Amount Due</legend>
$ <input type="number" id="check" value="" step='0.01' min='0.00'>
<label class='tip'>Tip%</label>
<select id="tip">
<option disabled selected value="">Pick</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<label>Amount Due: $
<output id="amountDue">0.00</output>
</label>
</fieldset>
<fieldset class='customers'>
<legend>Total Customers:
<output id="totalCustomers">1</output>
</legend>
<label class='add'> Add a Customer
<button type="button" id="add">+</button>
</label>
<ol class='group'>
<li>
<input type="number" class="customer" step='0.01' min='0.00' />
<button type="button" class="remove">-</button>
</li>
</ol>
</fieldset>
<fieldset class='grandTotal'>
<legend>Total Balance</legend>
<label>Paid Amount: $
<output id="paidTotal">0.00</output>
</label>
<br>
<label>Balance Due: $
<output id="balanceDue">0.00</output>
</label>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Trying to create a form with pretty simple validation and I'm curious as to two things.
One; how do I check if a form is empty?
Two; on the phone number field how would I only accept numbers in this format:
xxx-xxxx (where X is a number)
Here is what I have done so far:
HTML:
<form onsubmit="return false" method="post" name="myForm">
<div class="form-block">
<label>Name: </label>
<input type="text" name="name" id="name" />
<span id="name-error" class="error"></span>
</div>
<div class="form-block">
<label>Phone Number: </label>
<input type="text" name="phone" id="phone" />
<span id="phone-error" class="error"></span>
</div>
<input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>
CSS:
a, p, h1, h2, h3, h4, h5, h6, li, label, span {
font-family: sans-serif;
}
#mysubmit {
display: block;
margin-top: 10px;
}
span.error {
color: red;
font-weight: bold;
}
.form-block {
display: block;
width: 100%;
margin: 10px 0;
}
label {
display: inline-block;
width: 150px;
text-align: right;
}
JS:
validate = function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
if(/^[a-zA-Z]*$/.test(name)) {
document.getElementById("name-error").innerHTML = "Good.";
} else {
document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
}
if(isNaN(phone)) {
document.getElementById("phone-error").innerHTML = "Can only contain numbers";
} else {
document.getElementById("phone-error").innerHTML = "Good.";
}
};
You can test if the value of a form element is empty by simply checking for an empty string.
I've already posted something that will help you access and iterate through form fields.
// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');
// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
i,
l = formElements.length;
for (; i < l; i++) {
if (formElements[i].value === '') {
containsEmptyField = true;
// do something in response to an empty field
// the break is to stop looping since you've found
// a match
break;
}
}
// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
if (element.value === '') {
containsEmptyField = true;
break;
}
}
I haven't tested it properly, but the regex for the phone number, might look something like this:
(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber)
// returns true if value matches or false if it doesn't
I have a very simple form. Full Name/Email. What I want to do is check with jquery to make sure that they entered AT LEAST 5 characters in the name field. And if they did not, then I don't want the form to be submitted, instead I want to print some HTML below the form showing a warning/error message. How can I accomplish this?
Also Can I add words manually to the script to make sure they were not entered in the name field? And if they were to make sure it prints errors again... For example, if they entered the word "bobby" or "stephanie" I don't want the form to be submitted if those EXACT words are entered. It is only like 5 or 6 words I want blocked, so I can enter them manually no problem in the script without bloating anything.
Thank you so much in advance.
Here is my HTML
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1">
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email">
</div>
And this is the added HTML I want printed if the jquery check is false
<div id="error">
<span class="error_message">Please enter your full name</span>
</div>
Let's assume your form has an id of myForm.
var words = ["bobby", "stephanie"];
jQuery('#myForm').on('submit', function(evt) {
var form = $(this);
var full_name = form.find('#full_name');
var name_length = full_name.val().length;
if( name_length < 5 ) {
jQuery('#error').show();
evt.preventDefault();
}
if( jQuery.inArray(full_name.val(), words) ) {
evt.preventDefault();
}
});
Here is my answer: there are two if statements that we can construct:
Test if length of input exceeds 5 characters, and
Test if the input matches a list of banned words (stored in an array for convenience and verbosity)
It is a little complicated with the second conditional statement, since we want an exact match (therefore, using 'bobby' will raise a flag, but not 'bobby123'. This involves the use of word boundaries, \b.
You can view the code in action in this fiddle: http://jsfiddle.net/teddyrised/kmMcC/
$('form').submit(function(e) {
var errorFlag = 0,
bannedWords = [
'bobby',
'stephanie'
],
bannedObj = new RegExp('\\b'+bannedWords.join('|')+'\\b', 'i');
if($('#full_name').val().length <= 5) {
errorFlag = 1;
}
if(bannedObj.test($('#full_name').val())) {
errorFlag = 1;
}
// Act on error flag, prevent form submission when one or more error flags are raised
if(errorFlag) e.preventDefault();
});
Assuming you put this all in a form element, and add an input type='submit' element to it, I would suggest setting the form's onsubmit attribute to "return Validate();", and add the below validation function.
First you'll want to hide the message on ready using: $('error').hide();
function Validate(){
var minLength = 5;
var blockedNames = ["bobby","stephanie"];
var fName = $('#full_name').val();
if(fName.length < minLength){
$('#error').show();
$('#full_name').focus();
return false;
}
for(var i = 0;i < blockedNames.length;i++){
if(fName == blockedNames[i]){
$('#error').show();
$('#full_name').focus();
return false;
}
}
return true;
}
JSFIDDLE DEMO: http://jsfiddle.net/softvar/hv6yB/2/
UPDATE:
HTML
<form onsubmit="return check()">
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1" />
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email" />
</div>
<input type="submit" value="Submit"/>
</form>
<div id="error" >
<span class="error_message">Please enter your full name</span>
</div>
CSS
#error {
color:red;
display: none;
border: 1px solid #D9534F;
background: #FDF7F7;
width: 80%;
height: 25px;
padding: 5px;
}
JS
function check() {
var bannedWords = ['bobby','stephen'];
var name= $('#full_name').val();
if(name){
if(name.length>5){
for(var i=0;i<bannedWords.length;i++) {
if(bannedWords[i] ==name){
$('#error').text('Its a banned word');
$('#error').css('display','inline-block');
return false;
}
}
alert('form is going to be submitted');
return true;
}
else{
$('#error').text('Name is shorter');
$('#error').css('display','inline-block');
return false;
}
}
$('#error').text('Name cant be blank');
$('#error').css('display','inline-block');
return false;
}