Triggoring Form focus with logic to another field [duplicate] - javascript

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>

Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>

I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

Related

Javascript multiple fields validating

First, I have to validate that id and password textboxes are not empty(That one's working). Then I have to validate on the same form that id on textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work). Any ideas on what's wrong with my code?
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID;
custID = document.getElementsByName("idtb").valueOf();
if (custID !== isNan) {
alert("Customer ID needs to be numeric");
return false;
}
if (custID < 3000) {
alert("ID must be above 3000");
return false;
}
if (custID > 3999) {
alert("ID must be below 3999");
return false;
}
}
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID = document.getElementById('idtb').value;
if (Number.isNaN(parseInt(custID))) {
alert("Customer ID needs to be numeric");
return false;
}
if (parseInt(custID) < 3000) {
alert("ID must be above 3000");
return false;
}
if (parseInt(custID) > 3999) {
alert("ID must be below 3999");
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form action="#" onsubmit="return validatefunctions()" method="post">
Customer ID: <input type="text" name="idtb" id="idtb"><br /><br />
Password: <input type="text" name="pwtb" id="pwtb"><br /><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work)
Why don't use input type number specifying the min and max attribute:
<form>
<input type="number" name="quantity" min="3000" max="3999" value="3000">
<input type="submit">
</form>

jQuery validation is not working in contact form

I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance
You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});

The below jsp file doesn't validate from radio button onwards

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation Form</title>
<script type="text/javascript">
function validate()
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var atposition=email_str.indexOf("#");
var dotposition=email_str.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address")
return false
}
if ((!document.getElementById("a").checked)&&(!document.getElementById("b").checked))
{
alert("no button is selected");
return false
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length)
return alert("No box is checked");
var group2 = document.getElementById.dd;
var index_opt = group2.options[group2.selectedIndex].value;
if(index_opt==Select)
{
alert("select course")
return false
}
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name="my_form" onsubmit="validate()">
<strong>Name:&nbsp&nbsp&nbsp</strong>
<input type=text name=name><br/>
<strong>Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=pwd><br/>
<strong>Retype Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=repwd><br/>
<strong>Age:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=age><br/>
<strong>Phone No:&nbsp&nbsp&nbsp&nbsp</strong>
<input tupe= text name=ph><br/>
<strong>Email:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=email><br/><br/>
<strong>Sex:&nbsp&nbsp&nbsp&nbsp</strong>
<input type= "radio" name="gender" id="a" value="Male">Male&nbsp&nbsp&nbsp&nbsp
<input type= "radio" name="gender" id="b" value="Female">Female&nbsp&nbsp&nbsp&nbsp<br/><br/><br/>
<strong>Hobby:</strong>
<input type="checkbox"name= "hobby" id="1" value="singning">Singning<br/>
<input type="checkbox"name= "hobby" id="2" value="reading">Reading<br/>
<input type="checkbox"name= "hobby" id="3" value="tv">TV<br/>
<br/>
<strong>Country</strong>
<select name="mymenu" id="dd">
<option value ="Select">Select</option>
<option value ="India">India</option>
<option value ="China">China</option>
<option value ="SriLanka">SriLanka</option>
</select>
<input type="submit" value=Submit>
<input type="reset" value=Reset><br/>
</form>
</body>
</html>
The code doesn't validate from the radio button on wards. but if i run the radio button code and the other validation codes after the radio button code it works and when compiled in a single form it doesn't works. the drop down menu validation doesn't works at all. please help me. Thanks in advance.
It's not a problem with your radio button check. In your code, you can use one variable like x, that's the problem. kindly refer below code :
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
That above code x variable doesn't declare and doesn't assign any where in your code. So that line error occurred and terminated.
You change this x to email_str, As per your code should be like below,
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email_str.length)
It's working fine.
First of all you should change your on submit Event like below
<form name="my_form" onsubmit="return validate(this.form)">
Here your complete Javascript
<script type="text/javascript">
function validate(form)
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var email = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
var gender=document.my_form.gender.value;
if((gender=="null")||(gender=="")){
alert("Please Select Gender");
return false;
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length){
alert("No box is checked");
return false;
}
var country=document.my_form.mymenu.value;
if(country=='Select'){
alert("You must Select your Country");
return false;
}
}
</script>

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Textarea Empty check

HTML
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
Javascript
function validate()
{
if(document.getElementById('details').value == '')
{
alert("Please Provide Details!");
document.getElementById('details').focus();
return false;
}
else if(document.getElementById('name').value == '')
{
alert("Please Provide Name!");
document.getElementById('name').focus();
return false;
}
else
return true;
}
OR
function validate()
{
if(document.myForm.details.value == '')
{
alert("Please Provide Details!");
document.myForm.details.focus();
return false;
}
else if(document.myForm.name.value == '')
{
alert("Please Provide Name!");
document.myForm.name.focus();
return false;
}
else
return true;
}
I have seen the codes from previous Stack Overflow but as I am using these and it is not working. Will anyone help to solve check empty Value on Textarea using Javascript but not jquery.
The Reference I have used
how to check the textarea content is blank using javascript?
And
How to check if a Textarea is empty in Javascript or Jquery?
I think you may have space problem on your textarea. Use a trim function to reduce that. Here is the example following. I hope it may solve your problem.
JavaScript Add this function
function trimfield(str)
{
return str.replace(/^\s+|\s+$/g,'');
}
And your JavaScript function
function validate()
{
var obj1 = document.getElementById('details');
var obj2 = document.getElementById('name');
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
OR
function validate()
{
var obj1 = document.myForm.details;
var obj2 = document.myForm.name;
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
And HTML with PHP
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
You can use following jQuery to escape white spaces.
if($("#YourTextAreaID").val().trim().length < 1)
{
alert("Please Enter Text...");
return;
}

Categories