Javascript won't stop php form submission - javascript

Javascript gives error window, but it won't stop the form submission. I'm stumped at this point and can't find an exact answer. Here is the code, thanks:
function newNameValidate() {
var x = document.forms["checkIn"]["newName"].value;
if (x==null || x=="") {
alert("Tech name must be filled out");
return false;
}
return true;
}
Here is the HTML:
<form name="checkIn" onsubmit="newNameValidate(checkIn)" action="check_in_complete.php" method="POST">
<input type ="submit" class="input" value="CHECK IN">

You must return the value of the function, onclick="return foo();"

As others have said, you need to return the value returned from the function, but a better option is to use unobtrusive JavaScript:
<form name="checkIn" action="check_in_complete.php" method="POST">
Script:
window.onload = function() {
document.forms["checkIn"].onsubmit = newNameValidate;
}

It can be done like:
<form name="checkIn" id="checkIn" action="check_in_complete.php" method="POST">
<input type ="button" class="input" value="CHECK IN" onclick="newNameValidate()">
</form>
<script>
function newNameValidate() {
var x = document.forms["checkIn"]["newName"].value;
if (x==null || x=="") {
alert("Tech name must be filled out");
return false;
}else{
checkIn.submit();
}
}
</script>

Related

How do i make a js code that redirects to a certain html page with a certain input?

let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>

javascript onsubmit event for multiple functions check doesn't work

In mi validation form I have two input fields in order to write email and confirm it.
Before the submit informations, two confirms are needed:
1-email must seems an email,
2-email one must match the email two.
I can handle these statements each one using two separate javascript functions but i fail when I try to check them all in the onsubmit event attribute. If I write a correct email adress, the form reach the action destination, even if the confirm email doesn't match.
Looking around the web doesn't help me.
Here u are the code (html/javascript):
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Email Validation</title>
<script type="text/javascript">
function isEmail(email, output) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById(email).value;
if (regex.test(email)) {
return true;
} else {
document.getElementById(output).innerHTML = 'wrong email';
return false;
}
}
function compareEmail(email, emailToCompare, output){
var email = document.getElementById(email).value;
var emailToCompare = document.getElementById(emailToCompare).value;
if(emailToCompare == email){
document.getElementById(output).innerHTML = 'ok!';
return true;
}else{
document.getElementById(output).innerHTML = 'emails dont match!';
return false;
}
}
function check(){
return isEmail() && compareEmail();
}
</script>
</head>
<body>
<form action="file.php" method="post" onSubmit="return check()">
<p>Email</p>
<input type="text" name="email" maxlength="50" id="email">
<div id="email_result">
</div>
<br/>
<p>Confirm email</p>
<input type="text" onpaste="return false;" autocomplete="off" name="email" maxlength="50" id="confirm_email" onKeyUp="return compareEmail('email', 'confirm_email', 'confirm_email_result')">
<div id="confirm_email_result">
</div>
<input type="submit" name="submit" value="Register" onclick="return isEmail('email', 'email_result');">
</form>
</body>
The double control doesn't work with the follow script too:
function check(){
if (isEmail() && compareEmail()){
return true;
}else{
return false;
}
}
Nothing changes if I use:
onSubmit="return check()"
or
onSubmit="check()"
in the form event attribute.
You are missing the parameters in the function calls:
function check(){
return isEmail('email', 'email_result') && compareEmail('email', 'confirm_email', 'confirm_email_result');
}
Side note: You have declared variables in the functions with the same name as the parameters. It still works at it is, but the variables are not actually created but will overwrite the parameter values, so the code is a bit confusing.

validate multiple URL input fields

I have following Javascript validation function that should check that the URL posted to my php are OK - if not display a message to correct the entry.
I must have done a mistake somewhere because it is not working and my console.log says: ReferenceError: Can't find variable: $
validateFormbasic.html:12
onsubmitbasic.html:24:95
Could you tell me how to fix it please? Thanks a lot!
<form method="POST" name="inputLinks" onsubmit="return validateForm();">
<input type="text" name="web1" id="url1" placeholder="domain.com">
<input type="text" name="web2" id="url2" placeholder="domain.com">
<input type="text" name="web3" id="url3" placeholder="domain.com">
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
function validateURL(web1, web2, web3) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#url1", "#url2", "#url3").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
}
return false;
}
</script>
As Alberto's comment mentions, it looks like jQuery isn't loaded at the point of calling the function. It also looks to me as if you're syntax for selecting the URL values isn't quite right.
I would use something along the lines of:
<form method="POST" name="inputLinks">
<input type="text" name="web1" id="url1" class="url" placeholder="domain.com" />
<input type="text" name="web2" id="url2" class="url" placeholder="domain.com" />
<input type="text" name="web3" id="url3" class="url" placeholder="domain.com" />
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
$(function(){
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
$('form').submit(function(e){
var isValid = true;
$('.url').each(function(){
isValid = validateURL($(this).val());
return isValid;
});
if (!isValid){
e.preventDefault();
alert("Please enter a valid URL, remember including http://");
}
});
});
</script>
Update
Demo JS Fiddle

How to retrieve the values from an form to another html?

My code is ...
<form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" />
<input type="submit" value="Login"/>
So, when I pressed the Login it will call method validateForm() and returns the boolean
function validateForm()
{
var x=document.forms["myForm"]["StuserID"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
}
Firstly, if the userId is null it should show an alert "Name must be filled out" and return false. In my case, it is succeeding and move to demo_form.html. How can I make it so that form submission and continuing to demo_form.html is only done when function returns true?
Secondly, how do I get the userid in demo_form.html from the form when pressing the login button?
you have to use php file to retrieve data from html form.your html code form should be
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" required />
<input type="submit" value="Login"/>
and then
function validateForm()
{
var x=document.getElementById["StuserID"].value;
if (x=="")
{
alert("Name must be filled out");
return false;
}
else
{
return true;
}
}
your should use following code for demo_form.php file
<?php
$user = $_GET['StuserID'];
echo $user;
?>
1) Because false prevent the default behavior of form submit.
2) Create a session and use userid in session variable
I did't got exact error but in my case this following code works you can try this also
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
alert("sdfdfsf");
// return false;
var x=document.forms["myForm"]["StuserID"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" />
<input type="submit" value="Login"/>
</form>
</body>
</html>
and you can use jquery function also
Like .submit

Check box and text field validation javascript

I have a text field and a checkbox on a mobile website that needs to be required before submitting the form. One is a zip code search that needs to be required to go on, and also a check box for a terms and conditions.
Right now i have the textfield validation working...
<script>
function validateForm() {
var x=document.forms["searchform"]["fromAddress"].value;
if (x==null || x=="") {
alert("Oops! You forgot to enter a location.");
return false;
}
}
</script>
but i cant figure out how to add in the checkbox...
below is the code for the form:
<form name="searchform" method="post" action="list.php" onsubmit="return validateForm()">
<input type="hidden" name="search" value="1" />
<input class="txtfield" type="search" id="search" name="fromAddress" onfocus="this.value=''" />
<div class="terms-container">
<div class="terms-checkbox-container">
<input class="acceptterms" type="checkbox" name="agree" value="agree_terms">
</div>
<div class="terms-text-container">
I Agree to the Terms and Conditions
</div>
</div>
<input class="btn-submit" type="submit" id="submit" value="Go!"/>
</form>
any help would be great. Thanks!
I believe you can check the checkbox's checked property:
var checked = document.forms["searchform"]["agree"].checked;
if (!checked) {
alert("Oops! Please check the checkbox!");
return false;
}
You can get the state of the checkbox using checked attribute. So, you can do something like this.
<script>
function validateForm() {
var x=document.forms["searchform"]["fromAddress"].value;
var y=document.forms["searchform"]["agree"].checked;
if (x==null || x=="") {
alert("Oops! You forgot to enter a location.");
return false;
}
if (y === false) {
alert("Oops! You forgot to agree to the terms and Conditions");
return false;
}
}
</script>
Use below code:
var agreeCheckbox = document.forms["searchform"]["agree"];
if(!agreeCheckbox.checked) {
alert('You need to accept terms to submit');
return false;
}
return true;
You can use that
function validateForm()
{
var x=document.forms["searchform"]["fromAddress"].value;
if (x==null || x=="")
{
alert("Oops! You forgot to enter a location.");
return false;
}
var checkbox = document.forms['searchform']['agree'];
if (!checkbox.checked) {
alert('Oops! You must agree with Terms');
return false;
}
return true;
}
http://jsfiddle.net/KkYmX/5/
you can use this answer for form validation in the checkbox
//checkbox
var m=document.getElementById("client");
console.log(m)
if(!m.checked){
document.getElementById("bekar").innerHTML="please agree term & condition ";
document.getElementById("bekar").style="color:red";
return false;
}
else{
document.getElementById("bekar").innerHTML="";
}
<input type="checkbox" class="form-check-input" id="isclient" required>
<label class="form-check-label" for="isclient"> I want you to work on a project with me</label><br><span id="bekar"></span>

Categories

Resources