Why 'alert('animation not finished yet !')' fires every time after input received focus ?
var slidable_blocks = $('.header-internals .slidable');
var header_search = $(slidable_blocks[1]).find('input[type="search"]');
var scroll_content = function(target_node) {
if ($(target_node).is(':animated') === true) {
alert('animation not finished yet !');
return false;
}
if (typeof $(target_node).data('scrollDirection') === 'undefined') return false;
var margin_amount = ($(target_node).data('scrollDirection') == 'up') ? $(target_node).parent().height() * -1 : 0;
$(target_node).animate({
marginTop: `${margin_amount}px`
}, 'slow', '', function() {
var direction = ($(this).data('scrollDirection') == 'up') ? 'down' : 'up';
$(this).data('scrollDirection', direction);
if (direction == 'down') $(header_search).focus();
});
};
$('#search-toggle').on('click', function(e) {
scroll_content(slidable_blocks[0]);
e.preventDefault();
});
<div class="container header-internals">
<div class="slidable" data-scroll-direction="up">
<a href="#" class="site-logo">
<img src="assets/img/header_logo.png" alt="site logo">
</a>
<h1>Just another <span class="underline_accent">Minimalist</span> blog</h1>
</div>
<div class="slidable header-search">
<form method="get" action="" role="search">
<input type="search" placeholder="Type keyword(s) + Enter" maxlength="30" spellcheck="false" autocomplete="off">
</form>
</div>
</div>
Related
I have a section containing some radio buttons and other HTML elements.
When scrolling the page reached to the section, I need to like disable the scroll of the page and instead show some styles on the radios. After reaching to last radio button, enable to scroll the page.
var enabaled = true;
window.onload = function() {
function checkVisibilityOfDiv() {
var target = $(".scene44").offset().top;
if ($(window).scrollTop() >= target ) {
return true;
}
return false;
}
function enableScroll() {
window.onscroll = function () {
};
}
function disableScroll() {
// Get the current page scroll position
scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
scrollLeft =
window.pageXOffset || document.documentElement.scrollLeft,
// if any scroll is attempted,
// set this to the previous value
window.onscroll = function () {
window.scrollTo(scrollLeft, scrollTop);
};
}
let amount = 0;
let current = 1;
let max = 7;
var lastScrollTop = 0;
document.addEventListener('scroll', () => {
if (checkVisibilityOfDiv() ) {
var st = window.pageYOffset || document.documentElement.scrollTop;
amount++;
if (amount >= 9) {
amount = 0;
if (st > lastScrollTop ) { //detect scroll direction
// downscroll code
console.log(" down, " + current);
if(current===1 && enabaled=== true){
disableScroll();
enabaled=false;
}
document.getElementById('r' + current).checked = false;
//If you reach the last radio element you reset the counter
if (current === max) {
document.getElementById('r' + current).checked = true;
} else {
current += 1;
document.getElementById('r' + current).checked = true;
}
} else {
// upscroll code
console.log(" up, " + current);
amount = 0;
document.getElementById('r' + current).checked = false;
//If you reach the first radio element you reset the counter
if (current === 1) {
document.getElementById('r' + current).checked = true;
} else {
if (current === max) {
current -= 1;
if( enabaled=== true){
disableScroll();
enabaled=false;
}
} else {
current -= 1;
document.getElementById('r' + current).checked = true;
}
}
}
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}else {
enableScroll();
}
}, false);
};
<div class="scene44" id="scene44">
<input type="radio" name="buttons" id="r1" checked>
<input type="radio" name="buttons" id="r2">
<input type="radio" name="buttons" id="r3">
<input type="radio" name="buttons" id="r4">
<input type="radio" name="buttons" id="r5">
<input type="radio" name="buttons" id="r6">
<input type="radio" name="buttons" id="r7">
<p class="discp">
We discover your potential.
</p>
<div class="controls">
<label for="r1"><span></span>
<div>LAB & Process Development</div></label>
<label for="r2"><span></span><div>Quality & Regulatory</div></label>
<label for="r3"><span></span><div>Engineering & Project Management</div></label>
<label for="r4"><span></span><div>EHS</div></label>
<label for="r5"><span></span><div>Specialized Services</div></label>
<label for="r6"><span></span><div>Data Science LAB</div></label>
<label for="r7"><span></span><div>Technology & Science LAB</div></label>
</div>
<div class="container" >
<div class="leftimage-container">
<div class="box topleft"></div>
<div class="box backleft"></div>
<div class="box bottomleft"></div>
<div class="box frontleft" ></div>
</div>
<div class="centerimage-container">
<div class="box frontcenter"></div>
<div class="box backcenter"></div>
<div class="box bottomcenter"></div>
<div class="box topcenter"> </div>
</div>
<div class="rightimage-container">
<div class="box topright"></div>
<div class="box backright"></div>
<div class="box bottomright"></div>
<div class="box frontright"></div>
</div>
</div>
</div>
I've faced 2 problems; First, it's not working correctly as you can see.
Second, I logged some text and realized that the snippet code detecting the scroll direction does not work exactly.
How can I fix them?
I am very new to the UI part, i have one form which contains input type as number that field should accept only 10 digits only once the condition match i want to enable the submit button can you please help me did i miss anything ?
$(document).ready(function() {
$('#pnum').on('keypress', function(e) {
var $this = $(this);
var regex = new RegExp("^[0-9\b]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
// for 10 digit number only
if ($this.val().length > 9) {
e.preventDefault();
return false;
}
if (e.charCode < 54 && e.charCode > 47) {
if ($this.val().length == 0) {
e.preventDefault();
return false;
} else {
return true;
}
}
if (regex.test(str)) {
$('#submitButton').prop('disabled', false);
return true;
}
e.preventDefault();
return false;
});
});
<!-- CSS only -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="exampleInputEmail3">Phone Number</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">+ 91</span>
</div>
<input type="number" class="form-control" id="pnum" name="phone_number" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="10" required>
</div>
</div>
<input type="submit" name="submit" disabled id="submitButton" value="Submit" class="btn btn-primary mr-2">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="exampleInputEmail3">Phone Number</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">+ 91</span>
</div>
<input type="number" class="form-control" id="pnum" name="phone_number" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="10" required>
</div>
</div>
<input type="submit" name="submit" disabled id="submitButton" value="Submit" class="btn btn-primary mr-2">
<script>
$(document).ready(function() {
$('#pnum').on('keypress', function(e) {
const value = e.target.value
var $this = $(this);
var regex = new RegExp("[0-9]{9}");
// for 10 digit number only
if (value.length > 9) {
e.preventDefault();
return false;
}
if (regex.test(value)) {
$('#submitButton').prop('disabled', false);
return true;
}
});
});
</script>
for disable and enable based on string length if its 10 than
$(document).ready(function() {
$('#submitButton').prop('disabled', true);
$('#pnum').on('keypress', function(e) {
var $this = $(this);
if ($this.val().length == 10) {
$('#submitButton').prop('disabled', false);
}else{
$('#submitButton').prop('disabled', true);
}
});
});
i am trying to make an add to cart button and i am not having any errors but the button is not showing anything when i press it as i was testing it with the alert function and the increment and decrement buttons for the quantity are not working either so i think there is a problem with the whole jquery code but i can't know what is it
<div class="row mt-2">
<div class="col-md-3">
<input type="hidden" value="{{$products->id}}" class="prod_id">
<label for="Quantity"> Quantity</label>
<div class="input-group text-center mb-3 " style="width: 110px">
<button class="input-group-text decrement-btn">-</button>
<input type="text" name="quantity " class="form-control qty-input text-center" value="1"/>
<button class="input-group-text increment-btn">+</button>
</div>
</div>
<div class="col-md-9">
<br>
<button type="button" class="btn btn-success me-3 float start"> Add to wishlist</button>
<button type="button" class="btn btn-success me-3 addtoCartbtn float-start"> Add to cart</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<hr>
<h3>Description</h3>
<p class="mt-3">
{!! $products->desc!!}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function {
$('.addtoCartbtn').click(function (e) {
e.preventDefault();
var product_id= $(this).closest('.product_data').find('.prod_id').val();
var product_qty= $(this).closest('.product_data').find('.qty-input').val();
alert(product_id);
alert(product_qty);
});
$(".increment-btn").click(function (e) {
e.preventDefault();
var inc_value=$(".qty-input").val();
var value= parsint(inc_value,10);
value= isNaN(value) ? '0': value;
if(value < 10){
value++;
$(".qty-input").val(value);
}
});
$('.decrement-btn').click(function (e) {
e.preventDefault();
var dec_value= $('.qty-input').val();
var value= parsint(dec_value,10);
value= isNaN(value) ? '0': value;
if(value > 1){
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
Add missing () after function like below:
$(document).ready(function(){
//Write here
})
Correct spelling for 'parsint' to 'parseInt'.
$(document).ready(function() {
$('.addtoCartbtn').click(function (e) {
e.preventDefault();
var product_id= $('.prod_id').val();
var product_qty= $('.qty-input').val();
alert(product_id);
alert(product_qty);
});
$(".increment-btn").click(function (e) {
e.preventDefault();
var inc_value=$(".qty-input").val();
var value= parseInt(inc_value,10);
value= isNaN(value) ? '0': value;
if(value < 10){
value++;
$(".qty-input").val(value);
}
});
$('.decrement-btn').click(function (e) {
e.preventDefault();
var dec_value= $('.qty-input').val();
var value= parseInt(dec_value,10);
value= isNaN(value) ? '0': value;
if(value > 1){
value--;
$('.qty-input').val(value);
}
});
});
You should probably look at the console.
#section('scripts')
<script>
$(document).ready(function() { // changes
$('.addtoCartbtn').click(function (e) {
e.preventDefault();
var product_id= $(this).closest('.product_data').find('.prod_id').val();
var product_qty= $(this).closest('.product_data').find('.qty-input').val();
alert(product_id);
alert(product_qty);
});
$(".increment-btn").click(function (e) {
e.preventDefault();
var inc_value=$(".qty-input").val();
var value= parseInt(inc_value,10);
value= isNaN(value) ? '0': value;
if(value < 10){
value++;
$(".qty-input").val(value);
}
});
$('.decrement-btn').click(function (e) {
e.preventDefault();
var dec_value= $('.qty-input').val();
var value= parseInt(dec_value,10);
value= isNaN(value) ? '0': value;
if(value > 1){
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
you are assigning value to jquery array
$('.qty-input').val();
This should be changed to
$('.qty-input')[0].val()
Fixed Typos :)
I am trying to debug a function call in my JSP program and really confused on the ordering of how things worked. I am using NetBeans. When I run the project in debug mode, it goes into my '$("#searchEFT").mouseup(function ()' function and trace through all of it. 'searchEFT' is a button that I am using to access my servlet. When I process the page and then click the 'searchEFT' button, it hits the function call based on getting the right alert but doesn't trace in the debug. Why is it doing that? Is the first call of the function on load setting up the check when the user does the mouseclick?
This function is outside of the '$(document).ready(function ()' at the top and the function call is after the button declaration in the JSP.
EDIT: here is the JSP code:
<head>
<script>
$(document).ready(function ()
{
$(function ()
{
$("#CMDCreationDate").datepicker({
dateFormat: "yy-mm-dd"
});
});
}) ;
window.onbeforeunload = confirmExit;
function confirmExit()
{
alert("Alert-- leaving this page.");
}
function numbersonly(myfield, e, dec) {
//function to check that only numeric values are entered
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
myfield.form.elements[dec].focus();
return false;
} else
return false;
}
</script>
</head>
<body>
<header>
<?audit suppress oracle.ide.xml.validation-error?>
<div class="floatL appTTL">SAMS - EFT Schedule Number Search/Update Screen</div>
<div id="navWrap">
<nav class="floatR">
<ul>
<li>
Home
</li>
<li>
Search
</li>
<li>
Help
</li>
<li>
Help
</li>
</ul>
</nav>
</div>
<div class="clear"></div>
</header>
<main class="mainWrapper">
<form id="formID" method="POST" action="EFTscreen?action=searchEFT" >
<div class="commandcontainer">
<div id="divBox">
<h1 class="formTTL">Please Enter Schedule Number/Contract Year or either Schedule
Status/Creation Date value</h1>
<label class="labelTTL">Schedule Number</label>
<label class="labelTTL3">Contract Year</label>
<label class="labelTTL3">Status</label>
<label class="labelTTL">Creation Date</label>
<br/>
<input id="CMDScheduleNumber" name="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
value="${ScheduleNum}" onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" name="CMDContractYear" type="number" class="textsmall" maxlength="4"
value="${ContractYear}" onKeyPress="return numbersonly(this, event)"/>
<select size="1" id="CMDSchedStatus" name="CMDSchedStatus" class="combosmall">
<c:forEach items="${statusList}" var="current">
<option value="${current}"
<c:if test="${current == Status}"> selected="selected"</c:if>
>${current}</option>
</c:forEach>
</select>
<input id="CMDCreationDate" name="CMDCreationDate" type="text" class="textsmall"
value="${CreationDate}" maxlength="10"/>
<br/>
<button id="searchEFT" class="btn smBtn">Search</button>
</div>
<div id="divButton">
<button id="searchMEFTS" type="submit" formaction="EFTscreen?action=searchMEFTS&screen=mainEFT"
class="btn midBtn">Update Schedule Status</button>
<button id="clearMenu" type="submit" formaction="EFTscreen?action=clearMenu"
class="btn midBtn Space">Return to Menu</button>
</div>
<div id="clear"></div>
</div>
<article class="divBoxdet">
<fmt:formatNumber var="trdettotal" value="${detResults.getTOTAL_AMOUNT()}" pattern="$##,###,##0.00"/>
<label class="labelTTLdet floatL">
Schedule Number
<input id="txtScheduleNumber" type="number" class="textdet"
value="${detResults.getSCHEDULE_NUMBER()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Contract Year
<input id="txtContractYear" type="number" class="textdet"
value="${detResults.getEFT_CONTRACT_YEAR()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Date Created
<input id="txtCreationDate" type="text" class="textdet"
value="${detResults.getCREATION_DATE()}" readonly/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Num of Records
<input id="txtNumRecords" type="number" class="textdet"
value="${detResults.getNUM_OF_PAY_RECORDS()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Status
<br/>
<input id="txtStatus" type="text" class="textdet"
value="${detResults.getSTATUS()}" maxlength="2"/>
</label>
<label class="labelTTLdet floatL">
Status Date
<input id="txtStatusDate" type="text" class="textdet"
value="${detResults.getSTATUS_DATE()}" maxlength="10"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Schedule Total
<input id="txtScheduleTotal"
type="text" class="textdet" value="${trdettotal}" readonly/>
</label>
<label class="labelTTLdet floatL">
Schedule Post Date
<input id="txtPostDate" type="text" class="textdet"
value="${detResults.getSCHEDULE_POST_DATE()}" maxlength="10"/>
</label>
<label class="labelTTLdet floatL">
Reel Number
<input id="txtReelNumber" type="text" class="textdet"
value="${detResults.getREEL_NUMBER()}" maxlength="8"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<button id="pullMEFTD"
class="btn largeBtn Space floatL">Update Schedule Payment Status</button>
<script>
$("#searchEFT").mouseup(function ()
{
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
var schedLen = Cmd_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Cmd_Contract_Year = $('#CMDContractYear').val();
var yearLen = Cmd_Contract_Year.length;
//var Cmd_Status = document.getElementById("CMDSchedStatus").value;
var Cmd_Status = $('#CMDSchedStatus').val();
var statStr = Cmd_Status.replace(/\s/g, "");
var statLen = statStr.length;
//var Cmd_Creation_Date = document.getElementById("CMDCreationDate").value;
var Cmd_Creation_Date = $('#CMDCreationDate').val();
var createLen = Cmd_Creation_Date.length;
if ((schedLen > 0 && yearLen === 0) || (schedLen === 0 && yearLen > 0))
{
alert("Schedule Number and EFT Contract Year must be both populated");
}
;
if ((statLen === 0) && (createLen === 0) && (schedLen === 0) && (yearLen === 0))
{
var r = confirm("Are you sure you want to pull all EFT schedule numbers?");
if (r === false)
{
alert("Please enter information in any of the command line fields");
return false;
}
else
{
$('#formID').submit();
}
} ;
});
$("#pullMEFTS").mouseup(function ()
{
var Det_Sched_Number = $('#txtScheduleNumber').val();
var detschedLen = Det_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Det_Contract_Year = $('#txtContractYear').val();
var detyearLen = Det.length;
var Det_Status = $('#txtStatus').val();
if (detschedLen > 0)
{
alert("Schedule Number not found. Please investigate");
}
;
if ( holdStatus.matches("RP") ||
holdStatus.matches("VP") ||
holdStatus.matches("CP") )
{
alert("User can only update schedule number in NP status");
}
});
</script>
</article>
</form>
</main>
</body>
Thanks
The line:
$("#searchEFT").mouseup(function ()
is the function call that sets the mouseup handler; it is not the mouseup handler itself.
If you want to break inside the mouseup handler then you need to set a breakpoint somewhere inside the handler function itself, e.g.,
// First executable line of the mouseup handler
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
Unrelated, but I would break up the handler function into much smaller pieces, roughly:
function getFormData() {
return {
number: $('#CMDScheduleNumber').val().trim(),
year: $('#CMDContractYear').val().trim(),
status: $('#CMDSchedStatus').val().replace(/\s/g, '').trim(),
date: $('#CMDCreationDate').val().trim()
};
}
function invalidNumberAndYear(formData) {
return ((formData.number !== '') && (formData.year === '')) ||
((formData.year !== '') && (formData.number === ''));
}
function isPullAll(formData) {
return formData.number === '' &&
formData.year === '' &&
formData.status === '' &&
formData.date === '';
}
function searchEftMouseup(e) {
e.preventDefault();
var formData = getFormData();
if (invalidNumberAndYear(formData)) {
alert('Schedule Number and EFT Contract Year must be both populated');
return;
}
if (isPullAll(formData)) {
if (confirm('Are you sure you want to pull all EFT schedule numbers?')) {
$('#formID').submit();
} else {
alert('Please enter information in any of the command line fields');
}
}
}
$('#searchEFT').on('mouseup', searchEftMouseup);
This allows small stuff to be thought about easily, and begins to reveal your validation needs, and suggests a shape for your remaining code.
(Most of which, btw, was not relevant to the question–it's good to post only the minimum amount necessary to help people understand the issue :)
I'm trying to use form validation using JavaScript, however I don't seem to get any response, not even an alert even though it's there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="2013.php" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>
use === or == for condition checking in javascript.
if(document.getElementById('name').value === ""){
alert("enter something valid");
return false;
}
You have to use == for comparison.= is used for assigment
if(document.getElementById('name').value == ""){
alert("enter something valid");
return false;
}
Working Demo
Here Your issue is regarding if condition only! You must use == OR === in JavaScript for comparison.
Below is corrected script!
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
If you remove Or avoid return false, form will postback Even if Validation fails! So, return false means, exiting from function after if is must, and which is missed out in another answer!!
You are using = that is assignment operator, use == comparison operator that's work fine
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
I can't believe I've never realised this until now, although if you attach your Javascript to the form submission event, instead of the button submit event; the normal browser verification works (ie. input[type="email], required="required", etc.).
Works in Firefox & Chrome.
// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
e.preventDefault();
console.log ("Submitted! Now serialise your form and AJAX submit here...");
})
I have done a better way to do form validation using bootstrap. You can take a look at my codepen http://codepen.io/abhilashn/pen/bgpGRw
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\#[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;
function initFormElements(sValidElems) {
var inputElems = document.getElementsByTagName('textarea');
for(var i = 0; i < inputElems.length; i++) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
/* Add the code for the input elements */
inputElems = document.getElementsByTagName('input');
for(var i = 0; i < inputElems.length; i++) {
if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
}
/* submit handler */
com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
/* Add the default focus handler */
document.getElementsByTagName('input')[0].focus();
/* Add the event handlers for validation */
com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}
function highlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = g_FocusBackColor;
}
}
function unHightlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = "";
}
}
function validateAddress() {
var formField = document.getElementById('address');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpAddress');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
}
return ok;
}
}
function validateFirstName() {
var formField = document.getElementById('firstName');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpfirstName');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
}
return ok;
}
}
function validateEmailAddress() {
var formField = document.getElementById('email');
var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
var grpEle = document.getElementById('grpEmail');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
}
}
return ok;
}
function validateCellPhone() {
var formField = document.getElementById('cellPhone');
var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
var grpEle = document.getElementById('grpCellPhone');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
}
}
return ok;
}
function validateAllfields(e) {
/* Need to do it this way to make sure all the functions execute */
var bOK = validateFirstName();
bOK &= validateEmailAddress();
bOK &= validateCellPhone();
bOK &= validateAddress();
if(!bOK) {
alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
com_abhi.EVENTS.preventDefault(e);
}
}
com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<h1 class="text-center">Interactive form validation using bootstrap</h1>
<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
<div id="grpfirstName" class="form-group">
<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
<span id="firstNameIcon" class=""></span>
<div id="firstNameErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
</div>
<div id="grpEmail" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<span id="EmailIcon" class=""></span>
<div id="emailErrorMsg" class="text-danger"></div>
</div>
</div>
<div id="grpCellPhone" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
<span id="cellPhoneIcon" class=""></span>
<div id="cellPhoneErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group" id="grpAddress">
<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
<div class="col-sm-10">
<textarea id="address" class="form-control"></textarea>
<span id="addressIcon" class=""></span>
<div id="addressErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div> <!-- End of row -->
</div> <!-- End of container -->
Please check my codepen to better understand code.