JavaScript validation for empty input field - javascript

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>

Related

Why does my javascript contact-form not work?

I have tried adapting a contact formula I found online but no matter what I do it simply will not function (It does not need to be fully functional but I need it for a live-RPG session so it needs to "feel" real). I have checked (with a validation script) and JavaScript works fine on my page, so something must be wrong with the contact forms code itself. I will be the first to admit I am not that skilled at JavaScript so I was hoping someone could take a look and see if they can spot the error, because I have spent hours and still can not get this form to work at all.
The form I am basing all this on (and thus the "finished" version is this one: https://codepen.io/cool_lazyboy/pen/QRjwpG
My own code is below
function validation() {
var name = document.getElementById("name").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message");
var error_message = document.getElementById("error_message");
var text;
if (name.lenght <3){
text = "Angiv venligst dit navn";
error_message.innerHTML = text;
return false;
}
return false;
}
.wrapper-kontakt{
width: 100%;
background: #fff;
padding: 25px;
border-radius: 5px;
box-shadow: 0 1px 5px rgba(104, 104, 104, 0.8);
}
.wrapper-kontakt h2{
text-align: center;
margin-bottom: 20px;
text-transform: uppercase;
letter-spacing: 3px;
color: #332902;
}
.wrapper-kontakt .input_field{
margin-bottom: 10px;
}
.wrapper-kontakt .input_field input[type="text"],
.wrapper-kontakt textarea{
border: 1px solid #e0e0e0;
width: 100%;
padding: 10px;
}
.wrapper-kontakt textarea{
resize: none;
height: 80px;
}
.wrapper-kontakt .btn input[type="submit"]{
border: 0px;
margin-top: 15px;
padding: 10px;
text-align: center;
width: 100%;
background: #fece0c;
color: #332902;
text-transform: uppercase;
letter-spacing: 5px;
font-weight: bold;
border-radius: 25px;
cursor: pointer;
}
#error_message{
margin-bottom: 20px;
background: #fe8b8e;
padding: 0px;
text-align: center;
font-size: 14px;
transition: all 0.5s ease;
}
<div class="wrapper-kontakt">
<h2>Contact us</h2>
<div id="error_message"></div>
<form action="" id="myform" onsubmit = "return validation();">
<div class="input_field">
<input type="text" placeholder="Name" id="name">
</div>
<div class="input_field">
<input type="text" placeholder="Subject" id="subject">
</div>
<div class="input_field">
<input type="text" placeholder="Email" id="email">
</div>
<div class="input_field">
<textarea placeholder="Message" id="message"></textarea>
</div>
<div class="btn">
<input type="submit">
</div>
</form>
</div>
Here the spelling of length is wrong :
Also check action="" on form . This attribute can also be problem
function validation() {
var name = document.getElementById("name").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message");
var error_message = document.getElementById("error_message");
var text;
if (name.lenght <3){
text = "Angiv venligst dit navn";
error_message.innerHTML = text;
return false;
}
return false;
}
You have a spelling mistake in your JS in the if
name.lenght <3
Should be:
name.length < 3

Why is the input value undefined after validation?

I have a simple problem that I cannot seem to fix. I simply want to be able to display the value of the input Name field after entering your name and clicking submit. However, undefined seems to occur.
Can someone explain why this happens and how to fix? The code is below:
var name = document.querySelector('#withJS input:first-of-type'),
date = document.querySelector('#withJS input:not(:first-of-type)'),
errorMsg = document.querySelector('#withJS .errorMsg');
errorMsg.style.display='none';
function validateForm() {
alert(name.value);
/*
if(name.length == 0){
errorMsg.style.display='block';
errorMsg.textContent='Enter Name';
}
*/
}
#noJS, #withJS {
background: lightgreen;
max-width: 300px;
padding: 10px;
border: 5px solid #ccc;
}
#withJS {
background: lightblue;
margin-top: 10px;
}
.errorMsg {
background: red;
padding: 10px;
margin-top: 10px;
color: #fff;
text-transform: uppercase;
}
<div id='withJS'>
<form>
Name:<br>
<input type="text">
<br>
Date:<br>
<input type="date">
<br><br>
<input type="submit" value="Submit" onclick='validateForm()'>
</form>
<div class='errorMsg'>error message here</div>
</div>
Thanks for any help here.
The global variable name you've declared clashes with the window attribute name. Change the name of that variable, i.e: fname.
var fname = document.querySelector('#withJS input:first-of-type'),
date = document.querySelector('#withJS input:not(:first-of-type)'),
errorMsg = document.querySelector('#withJS .errorMsg');
errorMsg.style.display='none';
function validateForm() {
alert(fname.value);
/*
if(name.length == 0){
errorMsg.style.display='block';
errorMsg.textContent='Enter Name';
}
*/
}
#noJS, #withJS {
background: lightgreen;
max-width: 300px;
padding: 10px;
border: 5px solid #ccc;
}
#withJS {
background: lightblue;
margin-top: 10px;
}
.errorMsg {
background: red;
padding: 10px;
margin-top: 10px;
color: #fff;
text-transform: uppercase;
}
<div id='withJS'>
<form>
Name:<br>
<input type="text">
<br>
Date:<br>
<input type="date">
<br><br>
<input type="submit" value="Submit" onclick='validateForm()'>
</form>
<div class='errorMsg'>error message here</div>
</div>

Display date and time in input

I currently have the code below. I added a script in the HTML to display time and date in the Interview Start time input (Interview End Time not added yet.
For some reason this does not work and only shows the time for a split second before automatically deleting it.
I tried changing the location of the script, but that didn't work. How would I make the start time stay there, and also output on submit?
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
In HTML button elements are by default of type submit.
If you click on this button, you immediately submit the form:
<button id='1' onClick="show(this.id)">Click Amber</button>
To make this button only performs the action defined on click, without submitting the form, just give it a type of button.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
Ok so to keep your content from disappearing remove the form tags. From what I see your have to form element present but you're not using it for their intended purpose. The form tag is trying to do a POST (which is why everything looks like it disappearing) when you click your "Click Amber" button. The form thinks that your button is there to do a "Submit".
Here is more information about html form elements:
https://www.w3schools.com/html/html_forms.asp
You can add type="button" to the "Click Amber" button to prevent your form from submitting on that press. As been said, your form is submitting which is clearing out your page.
Your output code already works correctly.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>

i want to display error message in my multiple step form in jquery

I want to display an error message in my multiple step form in jquery if
I click on next button with out filling any value it should gives error message as soon as enter value error message disappear.if i click on next bttton with out filling any value it should gives error message as soon as enter value error message disappear
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use jQuery Steps plugin for these multiple steps form. This will be very easy to handle.

HTML5 validations not working

I have made a contact form. In this form I have added input validations like email for email text box and maximum length for phone number 10 in the contact textbox. But these validations are not working in my case.
What I'm doing wrong?
AJAX Call
function myformsubmit() {
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var contact = document.getElementById("contact").value;
var reason = document.getElementById("reason").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&mail1=' + mail + '&contact1=' + contact+ '&reason1=' + reason;
if (name == ''||mail == ''|| reason == ''||contact == ''){
alert("Please Fill all fields");
}else{
// AJAX code to submit form.
$.ajax({
type : "POST",
url : "http://test1.com/wp-content/themes/suave/theme_option/1.php",
data : dataString,
cache : false,
success : function(html) {
alert(html);
window.location="http://test1.com";
}
});
}
return false;
}
#media screen and (max-width: 972px) and (min-width: 100x) {
.exitpopup-modal-window {
display: none;
}
}
#exitpopup-modal .modal-body {
padding: 0px;
}
.modal-body {
padding: 0px;
}
.second img {
width: 369px;
height: 404.6px;
margin-top: -1%;
}
.first form {
display: table;
margin-left: 34px;
margin-top: 43px;
}
.row1 {
font-size: 10px;
font-family: inherit;
display: table-row;
border: 2px solid red;
}
.row1 #name,
#mail,
#contact {
color: black;
width: 260px;
height: 34px;
padding: 6px 12px;
border-radius: 3.9px;
border-color: #777;
display: table-cell;
}
.row1 textarea {
width: 260px;
height: 110px;
color: black;
border-color: #777;
display: table-cell;
}
.row1 #submit {
width: 152px;
height: 44px;
margin-left: 15%;
background-color: #337ab7;
color: white;
border-color: none;
}
.row1 #submit:hover {
width: 152px;
height: 44px;
margin-left: 15%;
background-color: white;
color: #337ab7;
border-color: none;
}
.second,
.first {
float: left;
}
.clearfix {
clear: both
}
.first span {
margin-left: 25%;
font-family: inherit;
font-size: 15px;
padding-top: 3px;
}
<div class="exitpopup-modal-window">
<div class="second">
<img src="http://www.buildzar.com/listing-assets/images/home-new/get-quote/bg-lead-form-web.png">
</div>
<div class="first">
<span>We are there to help you</span>
<form id="form" name="theform">
<div class="row1">
<input id="name" type="text" placeholder="Your name *" required>
<br>
<br>
</div>
<div class="row1">
<input type="email" id="mail" placeholder="Your email *" required>
<br>
<br>
</div>
<div class="row1">
<input id="contact" type="number" maxlength="10" placeholder="Your phonenumber*" required>
<br>
<br>
</div>
<div class="row1">
<textarea id="reason" rows="5" placeholder="Any reason to leave ?*" required></textarea>
<br>
<br>
</div>
<div class="row1">
<input id="submit" onclick="myformsubmit()" type="button" value="Submit">
</div>
</form>
</div>
<div class="clearfix"></div>
Your button type should be submit.
<input id="submit" type="submit" value="Submit">
And within for tag you should have action
<form id="form" name="theform" action="javascript:myformsubmit()">
Make New function and call this from your function myformsubmit.
function checkvalidate() {
var flag = false;
if (name == ''||mail == ''|| reason == ''||contact == ''){
flag = false;
}
else
{
flag = true;
}
return flag;
function myformsubmit() {
var flag = checkvalidate();
if(flag == true)
{
success code.
}
else
{
error message
}
}

Categories

Resources