JS validation on form - javascript

I have a form which I am trying to validate with JS. Problem is for the life of me I can’t get it to work.
Can anybody tell me where I’m going wrong? In the example below I am just rying to validate the Email field.
Regards,
Marc
function validateEmail() {
var x = document.forms["myForm"]["Email"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
#contact-area {
width: 500px;
max-height:200px;
margin-top: 0px;
float:left;
}
#contact-area input, #contact-area textarea {
padding: 3px;
width: 520px;
font-family:'Lato', sans-serif;
font-size: 14px;
margin: 0px 0px 0px 0px;
border: 1px solid #ccc;
}
#contact-area textarea {
height: 90px;
}
#contact-area textarea:focus, #contact-area input:focus {
border: 1px solid #ffc423;
}
#contact-area input.submit-button {
width: 100px;
float: left;
background-color:#ffc423;
color:black;
margin-top:13px;
cursor:pointer;
}
#contact-area input.submit-button:hover {
background-color:#002b51;
color:white;
}
label {
float:left;
text-align:left;
margin-right:15px;
width:100px;
padding-top:10px;
padding-bottom:5px;
font-size:15px;
color:#ffc423;
font-weight:700;
}
textarea {
resize: none;
}
<div id="contact-area">
<form method="post" action="contactengine.php" name="myForm" onsubmit="return contact-validation()">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name">
<label for="Company">Company:</label>
<input type="text" name="Company" id="Company">
<label for="Email">Email:</label>
<input type="email" name="Email" id="Email">
<label for="Message">Message:</label>
<textarea name="Message" rows="20" cols="20" id="Message" title="Your message | max 300 characters"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button">
</form>
<div style="clear: both;"></div>
</div>

This is wrong:
onsubmit="return contact-validation()">
You have no JavaScript method called contact-validation().
Even if you did, dashes are not valid in function names.
Try this instead:
onsubmit="return validateEmail()">

Change
x = document.forms["myForm"]["Email"].value;
to
x = document.getElementById("Email").value;
It targets the element directly by its id so if the DOM structure changes your JavaScript will still work. Also, the validation is checking the Email input, but the error message is for Name. You may want to leverage HTML5 validation with the required attribute as well.
You should also avoid the onsubmit attribute as it tightly couples the HTML and JavaScript. This can be achieved by the following:
<!-- use a button instead of an input for buttons, it is more semantically correct -->
<button id="btn-submit">Submit</button>
<script>
document.getElementById("btn-submit").addEventListener("click", function(evt){
evt.preventDefault();
if (validateEmail()) {
document.getElementById("myForm").submit();
}
});
</script>
Remove the onsubmit= from the form tag if you use this approach.

Related

How to sync typing between a span and an input?

I'm making a new I found way to sync typing between a span and an input ("https://stackoverflow.com/questions/8803416/synchonise-2-input-fields-can-it-be-done-using-jquery") and it works but I've come across a problem.
What I'm trying to do is create a multi-line title in WordPress using the classic editor and the input requires any text entered to be set in value="". It looks like this below:
<input type="text" name="post_title" size="30" value="" id="title" spellcheck="true" autocomplete="off">
So how do I sync typing between a span and an input but text is in value=""?
This is the code I've done so far (yes the code works, look at it in debug mode and you'll see the text showing up at the end of the input):
$("<span class='titlebox' role='textbox' contenteditable='true'></span>").insertAfter("#title");
$("span.titlebox").bind("keyup paste", function() {
$("input#title").text($(this).text());
});
.titlebox {
ont-size: 2.7em;
letter-spacing: -0.5px;
font-weight: 600;
display: block;
width: 100%;
overflow: hidden;
resize: none;
word-wrap: break-word;
border: 1px solid #000
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="post_title" size="30" value="" id="title" spellcheck="true" autocomplete="off">
$("input#title").text() never works. Instead you need to use $("input#title").val() to fill it.
$("<span class='titlebox' role='textbox' contenteditable='true'></span>").insertAfter("#title");
$("span.titlebox").on("input", function() {
$("input#title").val($(this).text());
});
.titlebox {
ont-size: 2.7em;
letter-spacing: -0.5px;
font-weight: 600;
display: block;
width: 100%;
overflow: hidden;
resize: none;
word-wrap: break-word;
border: 1px solid #000
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="post_title" size="30" value="" id="title" spellcheck="true" autocomplete="off">

Form Element Resizing After Submission

I am working on a system that makes use of a form to enter some data into a database. The system works as expected except for an issue with the display of the form after it has been submitted. When the form is submitted the page reloads and will show the info submitted as placeholder text inside of the form fields, and the "Save Changes" button will display as "Changes Saved!" for a few seconds. However, some of the input fields width property gets altered as well. Specifically my half-width form elements.
The width for these elements is defined as width: calc(50% - 24px), which is 265px. Additionally, there is a 5px padding and 2px border for these elements. This comes out to a total width of 279px, as expected. However, when the form is submitted and the page is reloaded the total width of the element comes out as 265px, retaining the 5px padding and 2px border, but dropping the internal width to 251px. Nowhere in my code is there anything that changes the width ever, and checking with dev tools shows that the width, padding, and border I defined are still there. This has the rather annoying effect of shifting both elements over after the form is submitted. Navigating to another page and back resolves the issue.
I have tried using !important and have checked over all of the code (JavaScript) echoed out from PHP when the submission is successful that interacts with the form in a capacity for changing things, and nothing should have this impact. I only change the color and text of the submit button.
Any help would be greatly appreciated!
Edit 1:
The code below is a snippet of the entire form, excluding the PHP. I have modified the code so that clicking save changes does not submit the form but will show the change for the submit button, as otherwise submitting makes the form vanish. The error does not occur in the snippet of code however as a result of not "reloading" the page.
function success() {
var button = document.getElementById('clientInfoBtn');
var normalColor = button.style.backgroundColor;
var normalValue = button.value;
button.style.backgroundColor = '#33cc33';
button.value = 'Changes Saved!';
setTimeout(function() {
button.style.backgroundColor = normalColor;
button.value = normalValue;
}, 3000);
return false;
}
.standardFormBox {
margin-bottom: 20px;
width: 600px;
}
.standardFormBoxInner {
border: 1px solid silver;
padding: 10px;
display: flex;
flex-wrap: wrap;
}
.standardFormHeading {
font-family: "Helvetica";
font-size: 16pt;
color: white;
background-color: #1975FF;
margin: 0;
padding: 10px;
}
.standardFormBtn {
color: white;
font-size: 14pt;
background-color: #1975FF;
border: none;
padding: 10px 10px;
margin-bottom: 15px;
}
.standardFormBtn:hover {
cursor: pointer;
background-color: #0052cc;
}
.standardFormInput {
font-size: 14pt;
font-family: "Trebuchet MS";
margin-bottom: 10px;
padding: 5px;
}
.sfiMultiLabel {
font-size: 14pt;
font-family: "Trebuchet MS";
}
.sfiHalf {
width: calc(50% - 24px);
}
.sfiText {
font-size: 14pt;
margin: 0;
}
.sfiTextHalf {
width: calc(50% - 10px);
}
.sfiTextFull {
width: 100%;
}
.sfiFull {
width: 100%;
}
.sfiLeft {
margin-right: 20px;
}
<form name="accountInfoForm" method="POST">
<div class="standardFormBox">
<p class="standardFormHeading">Business Billing Information</p>
<div class="standardFormBoxInner">
<p class="sfiText sfiTextHalf">Business Name</p>
<input type="text" name="cBusiness" placeholder="" class="standardFormInput sfiFull">
<p class="sfiText sfiTextHalf">Name On Bank Account</p>
<input type="text" name="cName" placeholder="" class="standardFormInput sfiFull">
<p class="sfiText sfiTextHalf">Billing Email</p>
<input type="email" name="cEmail" placeholder="" class="standardFormInput sfiFull">
<p class="sfiText sfiTextHalf">Street Address</p>
<input type="text" name="cStreet" placeholder="" class="standardFormInput sfiFull">
<p class="sfiText sfiTextHalf">City</p>
<input type="text" name="cCity" placeholder="" class="standardFormInput sfiFull">
<p class="sfiText sfiLeft sfiTextHalf">State</p>
<p class="sfiText sfiTextHalf">ZIP</p>
<input type="text" name="cState" placeholder="" class="standardFormInput sfiLeft sfiHalf">
<input type="text" name="cZip" placeholder="" class="standardFormInput sfiHalf">
<p class="sfiText sfiTextHalf">Phone Number</p>
<input type="text" name="cPhone" placeholder="" class="standardFormInput sfiFull">
</div>
</div>
<input type="submit" name="clientChangeInfo" value="Save Changes" class="standardFormBtn" id="clientInfoBtn" onclick="return success()">
</form>

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>

How can I make the website remember last shown form?

I have two forms inside one div:
Login form
Register form
Register form is hidden while login form is shown as default when you load the page. Im using js script to animate between those two forms by clicking anchor tag.
This causes problems for example while trying to register and you don't go through validation process correctly.
Hypothetical situation:
You've filled all the inputs, click submit button and it turns out that username you've provided is too short. The page will reload and it will show the default form again which is login form. You then again need to click "Register" a tag in order to switch between forms and then you see the error with validation.
I've been trying to read up about ways of doing that for days but seems like I can't specify my problem well enough in a short phrase. Can you guys explain what kind of method should I use and explain how to use it?
HTML:
<div class="login-page">
<div class="form">
<form class="register-form" method="POST">
<input type="text" name="nick" placeholder="username"/>
<input type="password" name="password1" placeholder="password"/>
<input type="password" name="repassword" placeholder="repeat password"/>
<input type="text" name="email" placeholder="e-mail adress"/>
<button>Create</button>
<p class="message">Already have an account? Log in!</p>
</form>
<form class="login-form" method="POST" action="login.php">
<input type="text" name="login" placeholder="username"/>
<input type="password" name="password" placeholder="password"/>
<button>log in</button>
<p class="message">Don't have an account yet? <a id="createacc" href="#">Sign up!</a></p>
</form>
JS:
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow"});
I want the website to remember which form you were filling before the page reloaded instead of always showing the default one (which is login form).
EDIT: In case anyone wondering. Yes, I did create similiar post about this yesterday but I realised that I didn't explain this well enough. Hope this goes through well.
You could make use of sessionStorage, a similar mechanism to cookies that persist only for the current session. When switching the visibility of your forms, set accordingly which one is also shown:
window.sessionStorage.setItem('lastOpenedForm', 'register');
And once the page loads again, fetch the value from there and display that form:
window.sessionStorage.getItem('lastOpenedForm');
Adapted code in snippet below:
var lastOpenedForm = window.sessionStorage.getItem("lastOpenedForm");
// By default show login form; check if we should show register and toggle visibilities
if (lastOpenedForm === "register-form") {
console.log('last opened form was register form');
$(".form form").toggleClass("active-form");
$(".login-page").toggleClass("bigger");
}
$(".message a").click(function() {
$(".form form").toggleClass("active-form");
var activeForm = $('.active-form').eq(0).attr('id');
window.sessionStorage.setItem('lastOpenedForm', activeForm);
console.log('last active form is ' + activeForm);
$(".login-page").toggleClass("bigger");
});
// $("#createacc").click(function() {
// window.sessionStorage.setItem("lastOpenedForm", "register-form");
// });
.login-page {
width: 600px;
height: 290px;
background: #333333;
border-radius: 50px;
margin-left: auto;
margin-right: auto;
margin-top: 10px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.5), 0 10px 10px 0 rgba(0, 0, 0, 0.24);
transition: all 1s;
}
.login-page.bigger {
height: 420px;
}
.form {
position: relative;
max-width: 360px;
margin: auto;
padding: 45px;
text-align: center;
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
border-radius: 5px;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #666666;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
cursor: pointer;
border-radius: 5px;
}
.form button:hover,
.form button:active,
.form button:focus {
background: #808080;
}
.form .message {
margin: 15px 0 0;
color: white;
font-size: 16px;
}
.form .message a {
color: #1a8cff;
text-decoration: none;
}
.form form {
/* display: none; */
visibility: hidden;
opacity: 0;
height: 0;
transition: 0.5s easy-in-out all;
}
.form .active-form {
visibility: visible;
opacity: 1;
height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="login-page">
<div class="form">
<form id="register-form" method="POST">
<input type="text" name="nick" placeholder="username" />
<input type="password" name="password1" placeholder="password" />
<input type="password" name="repassword" placeholder="repeat password" />
<input type="text" name="email" placeholder="e-mail adress" />
<button>Create</button>
<p class="message">Already have an account? Log in!</p>
</form>
<form id="login-form" method="POST" class="active-form" action="login.php">
<input type="text" name="login" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<button>log in</button>
<p class="message">Don't have an account yet? <a id="createacc" href="#">Sign up!</a></p>
</form>
</div>
Also available in this codepen.
If you're relying on JavaScript then you have a few possible routes.
Use localStorage to set and get the state. https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Use a cookie to set and get the state. https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
Use a query string parameter as part of your url and use the Location api to get it. https://developer.mozilla.org/en-US/docs/Web/API/Location
Javascript has no way of remembering state so you must make use of a strategy such as the above. Personally I would opt for localStorage as it has a nice simple API.
You can use localStorage to store the state in your browser.
<div class="login-page">
<div class="form">
<form class="register-form" method="POST" id="register">
<input type="text" name="nick" placeholder="username"/>
<input type="password" name="password1" placeholder="password"/>
<input type="password" name="repassword" placeholder="repeat password"/>
<input type="text" name="email" placeholder="e-mail adress"/>
<button>Create</button>
<p class="message">Already have an account? Log in!</p>
</form>
<form class="login-form" method="POST" action="login.php" id="login">
<input type="text" name="login" placeholder="username"/>
<input type="password" name="password" placeholder="password"/>
<button>log in</button>
<p class="message">Don't have an account yet? <a id="createacc" href="#">Sign up!</a></p>
</form>
var fo;
$(document).ready(function(){
console.log(localStorage.getItem('form'))
$('form').click(function(){fo=$(this).attr('id');
localStorage.setItem('form',fo);
})
})
Working fiddle
You might consider using a URL fragment at the end of your form action attribute--e.g. <form action="example.com/#register">.
URL fragments are typically used to jump to different sections on a page. So in this case, they're probably more semantically meaningful than other options like session storage, cookies, or query strings.
You just need to listen to the document's load event to determine which form is being targeted. Something like this:
$(function () {
if (window.location.hash == "register") {
// show registration form here
}
});

How to pass value to directive attributes?

I have a text box, a submit button and a directive.
<input type="text" />
<input type="submit" />
<my-dir name=""></my-dir>
Every time I type something in the box and submit, I hope the string can be passed to the "name" attribute of my-dir. How to achieve it?
Shouldn't be any problems using document.querySelector or document.getElementsByTagName. Here's a quick example...
my-dir:after {
display: block;
margin: 10px 0;
border: 1px solid #666;
background-color: #eee;
min-height: 1em;
padding: 5px;
border-radius: 2px;
content: attr(name);
}
<form onsubmit="document.querySelector('my-dir').setAttribute('name', this.text.value); return false">
<input name="text" type="text" />
<input type="submit" />
</form>
<my-dir name=""></my-dir>

Categories

Resources