Disable input button when field.value is empty - javascript

I've seen this answered in jquery, but I'd like to know how I can do it in javascript. So far I came up with the following, but I understand it is not capturing the nameF.value properly.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
if (nameF.value == "") {
formButton.classList.add("notclickable");
}
}
go();
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button">
https://stackoverflow.com/questions/ask#
How can I do it without jQuery, just using vanilla?
Thank you!

All you need is an event handler assigned to nameF, and to .toggle() the class instead of add().
The .toggle() receives an optional second argument where you tell it if it should add or remove the class, so you'll pass the string comparison there.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.classList.toggle("notclickable", nameF.value == "");
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#
Also, be aware that you don't need a class to disable the button. You can use the disabled property with the :disabled selector. This disables its functionality too instead of just fading it.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.disabled = nameF.value == "";
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
}
#form-button:disabled {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#

Try something like that!
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function onChangeContent(e) {
formButton.disabled = e.target.value !== '' ? false : true;
}
nameF.addEventListener('keyup', onChangeContent);
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button" disabled>

Related

How to use javascript to detect whether there is a value in the input box that contains a blank string, and if so, make the button clickable [duplicate]

I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.
I tried the code below but did not work.
any advice?
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if ((a == null || a == "") && (b == null || b == "") && (c == null || c == "") && (d == null || d == "")) {
alert("Please Fill In All Required Fields");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():
function isEmpty(str) {
return !str.trim().length;
}
Example:
const isEmpty = str => !str.trim().length;
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME is invalid (Empty)" )
} else {
console.log( `NAME value is: ${this.value}` );
}
});
<input id="name" type="text">
See the working example here
You are missing the required <form> element. Here is how your code should be like:
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
Add an id "question" to your input element and then try this:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
See #Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
You can loop through each input after submiting and check if it's empty
let form = document.getElementById('yourform');
form.addEventListener("submit", function(e){ // event into anonymous function
let ver = true;
e.preventDefault(); //Prevent submit event from refreshing the page
e.target.forEach(input => { // input is just a variable name, e.target is the form element
if(input.length < 1){ // here you're looping through each input of the form and checking its length
ver = false;
}
});
if(!ver){
return false;
}else{
//continue what you were doing :)
}
})
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
if(document.getElementById("question").value == "")
{
alert("empty")
}
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
Customizing the input message using HTML validation when clicking on Javascript button
function msgAlert() {
const nameUser = document.querySelector('#nameUser');
const passUser = document.querySelector('#passUser');
if (nameUser.value === ''){
console.log('Input name empty!');
nameUser.setCustomValidity('Insert a name!');
} else {
nameUser.setCustomValidity('');
console.log('Input name ' + nameUser.value);
}
}
const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
.container{display:flex;max-width:960px;}
.w-auto {
width: auto!important;
}
.p-3 {
padding: 1rem!important;
}
.align-items-center {
-ms-flex-align: center!important;
align-items: center!important;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.d-inline-block {
display: inline-block!important;
}
.col {
-ms-flex-preferred-size: 0;
flex-basis: 0;
-ms-flex-positive: 1;
flex-grow: 1;
max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
margin-right: .5rem!important;
}
label {
font-family: "Oswald", sans-serif;
font-size: 12px;
color: #007081;
font-weight: 400;
letter-spacing: 1px;
text-transform: uppercase;
}
label {
display: inline-block;
margin-bottom: .5rem;
}
.x-input {
background-color: #eaf3f8;
font-family: "Montserrat", sans-serif;
font-size: 14px;
}
.login-input {
border: none !important;
width: 100%;
}
.p-4 {
padding: 1.5rem!important;
}
.form-control {
display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
overflow: visible;
margin: 0;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
padding-right: 5px;
padding-left: 5px;
}
.col-lg-12 {
-ms-flex: 0 0 100%;
flex: 0 0 100%;
max-width: 100%;
}
.mt-1, .my-1 {
margin-top: .25rem!important;
}
.mt-2, .my-2 {
margin-top: .5rem!important;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.btn-petroleo {
background-color: #007081;
color: white;
font-family: "Oswald", sans-serif;
font-size: 12px;
text-transform: uppercase;
padding: 8px 30px;
letter-spacing: 2px;
}
.btn-xg {
padding: 20px 100px;
width: 100%;
display: block;
}
.btn {
display: inline-block;
font-weight: 400;
color: #212529;
text-align: center;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: transparent;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
-webkit-writing-mode: horizontal-tb !important;
text-rendering: auto;
color: -internal-light-dark(black, white);
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: textfield;
background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
-webkit-rtl-ordering: logical;
cursor: text;
margin: 0em;
font: 400 13.3333px Arial;
padding: 1px 2px;
border-width: 2px;
border-style: inset;
border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
border-image: initial;
}
<div class="container">
<form name="myFormLogin" class="w-auto p-3 mw-10">
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="nameUser">Usuário</label><br>
<input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
name="nameUser" placeholder="Name" required>
</div>
</div>
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="passUser">Senha</label><br>
<input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
name="passUser" placeholder="Password" required>
<div class="help">Esqueci meu usuário ou senha</div>
</div>
</div>
<div class="form-row d-flex align-items-center">
<div class="col-lg-12 my-1 mt-2 mb-2">
<button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
</div>
</div>
<div class="form-row align-items-center d-flex">
<div class="col-lg-12 my-1">
<div class="nova-conta">Ainda não é cadastrado? Crie seu acesso</div>
</div>
</div>
</form>
</div>
My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with var.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js file
Combining all the approaches we can do something like this:
const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
if (checkEmpty.value && // if exist AND
checkEmpty.value.length > 0 && // if value have one charecter at least
checkEmpty.value.trim().length > 0 // if value is not just spaces
)
{ console.log('value is: '+checkEmpty.value);}
else {console.log('No value');
}
});
<input type="text" id="checkIt" required />
Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.
The following code worked for me perfectly:
<form action = "dashboard.php" onsubmit= "return someJsFunction()">
<button type="submit" class="button" id = "submit" name="submit" >Upload to live listing</button>
</form>
<script type="text/javascript">
function someJsFunction(){
const input = document.getElementById('input1');
if(input.value === ""){
alert ("no input?"); // This will prevent the Form from submitting
return false;
}else{
return true; // this will submit the form and handle the control to php.
}
}
</script>

Displaying all changes to a <input type=“text”> (immediately) using JQuery

I am working in a website project, Which want to display what we editing in <input type="text" id="input" /> tag.
But problem is result only displaying in <div class="result"></div>.
I want to display it in <input type="text" class="reult" /> and <textarea class="result"></textarea> .
I tried many times to fix it. I also created a codepen page for it.. https://codepen.io/coderco/pen/abNNVyw . Please check codes below.
input[type=text],select,textarea{display:block;width:27em;color:#000!important;background:#fff!important;margin-top:1em;height:34px;font-size:1.2em;font-family:"sans-serif";border:2px solid #000;padding:2px 10px;font-family:arial;font-size:18px}
textarea{display:block;width:27em;margin-top:4em;height:125px;font-size:1.2em;font-family:"sans-serif";border:2px solid #000;padding:2px 10px;font-family:arial;font-size:18px;color:#000!important;background:#fff!important;margin-bottom:10px}
.result{margin-top:20px;width:20em;height:5em;float:left;font-family:arial;font-size:18px;background:#333;color:#fff;margin-right:1em;padding:10px}
<input type="text" id="input" placeholder="Edit Here" />
<div class="result"></div>
<div class="result"></div>
<textarea class="result" placeholder="Display Result Here"></textarea>
<input type="text" class="result" placeholder="Display Result Here"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="js/script.js"></script>
// Choose relevant input elements
var inputs = $('input,select,textarea')
// Bind a new event to the inputs
.bind("newInput", function(){
// Abbreviate
var $t = $(this);
// Log the results
$('.result')
.text( $t.val() );
});
(function scan(){
inputs.each(function() {
$t = $(this);
if ( $t.data('oldVal') !== $t.val() ) {
$t.trigger('newInput');
$t.data('oldVal',$t.val());
}
});
setTimeout(scan,100);
})();
You are over complicating things. Here is simple JS to the job.
Div element takes no value parameter, it takes inerHTML, and texatera and input takes value.
document.querySelector('#input').addEventListener('keyup', val, false);
function val() {
[...document.querySelectorAll('.result')].forEach(el => {
el.value=this.value;
el.innerHTML=this.value;
})
}
JS EXAMPLE:
document.querySelector('#input').addEventListener('keyup', val, false);
function val() {
[...document.querySelectorAll('.result')].forEach(el => {
el.value=this.value;
el.innerHTML=this.value;
})
}
input[type=text],
select,
textarea {
display: block;
width: 27em;
margin-top: 4em;
height: 34px;
font-size: 1.2em;
font-family: "sans-serif";
border: 2px solid #000;
padding: 2px 10px;
font-family: arial;
font-size: 18px;
}
.result {
margin-top: 20px;
width: 20em;
height: 5em;
float: left;
font-family: arial;
font-size: 18px;
background: #333;
color: #fff;
margin-right: 1em;
padding: 10px;
}
<input type="text" id="input" placeholder="Edit Here" />
<div class="result"></div>
<div class="result"></div>
<textarea class="result"></textarea>
<input type="text" class="result" />
If you want to do this in jQuery:
You have to use .text() or .html() for divs, and .val() for input and textarea
$("#input").keyup(function(){
let inValue=$(this).val();
$(".result").each(function(){
$(this).text(inValue);
$(this).val(inValue);
});
});
jQuery EXAMPLE:
$("#input").keyup(function(){
let inValue=$(this).val();
$(".result").each(function(){
$(this).text(inValue);
$(this).val(inValue);
});
});
input[type=text],
select,
textarea {
display: block;
width: 27em;
margin-top: 4em;
height: 34px;
font-size: 1.2em;
font-family: "sans-serif";
border: 2px solid #000;
padding: 2px 10px;
font-family: arial;
font-size: 18px;
}
.result {
margin-top: 20px;
width: 20em;
height: 5em;
float: left;
font-family: arial;
font-size: 18px;
background: #333;
color: #fff;
margin-right: 1em;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input" placeholder="Edit Here" />
<div class="result"></div>
<div class="result"></div>
<textarea class="result"></textarea>
<input type="text" class="result" />

Controlling Element Height With jQuery - Why Isn't This Working?

I'm trying to change the height of a div element with a function triggered by "onmouseover" in jQuery. However, when I hover over the element, nothing happens. There are no errors in the console and as far as I can see this should be working. Any suggestions would be much appreciated. Thanks for your help.
function lowerRaise() {
var getHeiggt = document.getElementsByClassName('searchItem')[0];
var tehHeiegt = jQuery(getHeiggt).height();
var allTIms = document.getElementsByClassName('searchItem');
if (tehHeiegt > 0) {
for (i = 0; i < allTIms.length; i++) {
jQuery(allTIms[i]).height("9px");
jQuery(allTIms[i]).css("padding-top", "3px");
jQuery(allTIms[i]).css("padding-bottom", "10px");
}
} else {
for (i = 0; i < allTIms.length; i++) {
jQuery(allTIms[i]).height("0px");
jQuery(allTIms[i]).css("padding-top", "0px");
jQuery(allTIms[i]).css("padding-bottom", "0px");
}
}
}
.searchItem {
height: 9px;
transition: 0.3s;
background-color: white;
color: black;
padding: 3px 0px 10px 6px;
border-bottom: 1px solid lightgrey;
cursor: pointer;
}
.searchItem a {
display: block;
color: black;
text-decoration: none;
}
.searchItem a:hover {
display: block;
color: black;
text-decoration: none;
}
.searchItem:hover {
background-color: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onmouseover="lowerRaise()" role="search" method="get" class="search-form" action="/">
<label>
<span class="screen-reader-text">Search for:</span>
<input autocomplete="off" type="search" class="search-field" placeholder="Search …" value="" name="s">
</label>
<input type="submit" class="search-submit" value="Search">
</form>
<div id="searchDrop" style="transition: 0.5s;">
<div class="searchItem"><a style="" href="/?s=dress">Dresses</a></div>
<div class="searchItem">Sweaters</div>
<div class="searchItem">Blouses</div>
<div class="searchItem">Pants</div>
<div class="searchItem">Tops</div>
<div class="searchItem">T-Shirts</div>
<div class="searchItem">Skirts</div>
<div class="searchItem">Shirts</div>
<div class="searchItem">Blazers</div>
</div>

How to Submit Form after Modal fadeOut?

I try to make my form submitted after the modal has finished fading out, then to submit the form to mail to refreshform.php the email file is ready,
but after the modal has faded out the form does not submit or post something to php file so send it to email , its just fade out and did not submit
this is my files
thank you for your help !
$(document).ready(function() {
$('#questionWrapper .question').first().show(); //show first questionblock
$("#questionWrapper .answer" ).click(function( event ) {
event.preventDefault();
$(this).parent('.question').hide();
if ($(this).parent().next('.question').length) {
$(this).parent().next('.question').fadeIn();
} else {
startCheck();
}
});
});
function startCheck() {
var overlay = $('.overlay-checker'),
points = $('.overlay-checker-points > li');
// Initially, hide all the points so we can show them one by one
points.hide();
// Fade in the overlay
overlay.fadeIn();
// Loop points.lenght times (so through every point)
for (i = 0; i < points.length; i++) {
setTimeout(function () {
$('.overlay-checker-points').find(':hidden').first().fadeIn();
}, 1500 * (i + 1));
}
// After all items have been faded in, redirect
setTimeout(function () {
('.overlay-checker').fadeOut('500', function(
$('form').submit();) {
});
}, 1500 * points.length + 2000);
}
function toggleDiv(target) {
$(target).toggle();
}
.countWrapper {
display: block;
clear: both;
font-size: 12px;
margin: 5px;
}
.rulesBox {
width: 80%; background-color: #ffffff; margin: 10px 0 15px 0; padding: 20px;
-moz-border-radius: 15px;
border-radius: 15px;
}
.centerIt {
margin:0px auto;
text-align:center;
margin-top: 125px;
}
.centerIt a {
margin:0px auto;
}
.overlay-checker {
display: none;
background: #fff;
background: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
}
.overlay-checker {
color: #fff;
font-size: 35px;
font-weight: bold;
}
.overlay-checker-points {
max-width: 700px;
font-size: 20px;
padding: 0;
}
.overlay-checker-points li{list-style: none;}
.overlay-checker-points li img{height: 21px;}
<form class="form" method="post" id="form" action="refreshform.php">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="country">
<input name="country" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Country" id="country" />
</p>
<p class="apps">to ensure your not a bot <strong>you must download 2 FREE Apps</strong> and only after the GiftCard will be Sent.</p>
<div class="kapot">
<input type="button" name="go" onclick="startCheck()" id="submit" value="Go"/>
<div class="ease"></div>
</div>
</form>
There is a syntax error here:
// After all items have been faded in, redirect
setTimeout(function () {
('.overlay-checker').fadeOut('500', function(
$('form').submit();) {
});
Also another syntax here with '.overlay-checker'
I corrected those below...
**EDIT: I also removed the ID of your button from being called id="submit" because that seems to be creating a conflict for submitting the form.
NB: as the overlay markup is not in this example, I added a condition to submit otherwise.
$(document).ready(function() {
$('#questionWrapper .question').first().show(); //show first questionblock
$("#questionWrapper .answer" ).click(function( event ) {
event.preventDefault();
$(this).parent('.question').hide();
if ($(this).parent().next('.question').length) {
$(this).parent().next('.question').fadeIn();
} else {
startCheck();
}
});
});
function startCheck() {
var overlay = $('.overlay-checker'),
points = $('.overlay-checker-points > li');
// Initially, hide all the points so we can show them one by one
points.hide();
// Fade in the overlay
overlay.fadeIn();
// Loop points.lenght times (so through every point)
for (i = 0; i < points.length; i++) {
setTimeout(function () {
$('.overlay-checker-points').find(':hidden').first().fadeIn();
}, 1500 * (i + 1));
}
// After all items have been faded in, redirect
setTimeout(function () {
console.log('Timer started.');
if(jQuery('.overlay-checker').length){
jQuery('.overlay-checker').fadeOut('500', function() {
console.log('Fade out complete. Submitting form.');
jQuery('#form').submit();
});
}else{
console.log('Fade selector not found. Submitting form immediately.');
jQuery('#form').submit();
}
}, 1500 * points.length + 2000);
}
function toggleDiv(target) {
$(target).toggle();
}
.countWrapper {
display: block;
clear: both;
font-size: 12px;
margin: 5px;
}
.rulesBox {
width: 80%; background-color: #ffffff; margin: 10px 0 15px 0; padding: 20px;
-moz-border-radius: 15px;
border-radius: 15px;
}
.centerIt {
margin:0px auto;
text-align:center;
margin-top: 125px;
}
.centerIt a {
margin:0px auto;
}
.overlay-checker {
display: none;
background: #fff;
background: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
}
.overlay-checker {
color: #fff;
font-size: 35px;
font-weight: bold;
}
.overlay-checker-points {
max-width: 700px;
font-size: 20px;
padding: 0;
}
.overlay-checker-points li{list-style: none;}
.overlay-checker-points li img{height: 21px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" method="post" id="form" action="refreshform.php">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="country">
<input name="country" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Country" id="country" />
</p>
<p class="apps">to ensure your not a bot <strong>you must download 2 FREE Apps</strong> and only after the GiftCard will be Sent.</p>
<div class="kapot">
<input type="button" name="go" onclick="startCheck()" value="Go"/>
<div class="ease"></div>
</div>
</form>

Form validation button without submitting the form

I have a form, and I want to check validation ( if the inputs are correct) without submitting that form. How is that possible?
The validations in this example is as follows:
If the user enters and for first name and jkp for last name and clicks on the validate button, the document.write function will print success without submitting the form.
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{document.write("Correct answer");}
else{document.write("Incorrect answer");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>
make validate but not a submit type
Changes i have made:
in js
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
in html
<input id="vali" style="background:red" type="button" value="Validate">
DEMO:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
#vali{
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<input type="submit" value="Submit">
<input id="vali" style="background:red" type="button" value="Validate">
</form>
You can also try AJAX requests supposing you will do the validation on the server side, also hiding the business logic from the client.
Another solution is to create a javascript method for validation that is called after focus lost/key up which takes the elements by their id and passes them to this function.
You can simply add event.preventDefault() to the submit event if the validation fails:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp") {
alert("Success");
}
else {
event.preventDefault();
alert("failed");
}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>
Not checked but you can use onchange(),
The change event occurs when the value of an element has been changed (only works on input, textarea and select elements).
The change() method triggers the change event or attaches a function to run when a change event occurs.
$( "#myform" ).change(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp"){
alert("Your answers are correct!");
}
else{
alert("Your answer is not correct");
}
}

Categories