I have the following validation script that works fine, but I don't understand how it works and need your help with it.
The HTML,
<form action="xyz.php" method="post">
<div class="form-group">
<label class="sr-only" for="id">Enter ID</label>
<input type="text" class="form-control" name="id" id="id" required>
</div>
<button onclick="return validateID()" type="submit" name="submit" class="btn">Submit</button>
</form>
And this is the JS,
<script>
function validateID() {
var id = document.getElementById("id").value;
var regL= new RegExp("^([0-9][0-9][0-9])$");
if (!( (regL.test(id)) )) {
window.location.href = "index-iderror.php";
return false;
} else {
return true;
}
}
</script>
Some questions that I have about this,
What happens when false or true is returned to onclick? Does it decide whether the form data is or is not sent to xyz.php?
How does the execution continue till the line return false after window.location.href? Shouldn't window.location.href direct to a new page stopping execution? The script does not work if return false is removed i.e. the unchecked form data is sent to xyz.php.
Related
I have been practicing basic programming with Bootstrap, HTML, CSS, and JavaScript and for the moment I'm doing a website that starts with a landing page that asks for a password and then sends you to another page.
The thing is that the form and the JavaScript validation aren't working together and I don't know why and what I'm doing wrong, so If someone could help me it would be awesome! Thanks!
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
</form>
</div>
<script type="text/javascript">
function isValid(password)
{
var pass ="seahorse";
var password = document.getElementById("password");
if (password.value.toUpperCAse().match(pass))
{
window.location.href = "HappyChristmas.html";
return true;
}
else
{
alert('Nope, try again');
return false;
}
}
</script>
You're not calling isValid() when submitting the form.
You're transforming your input value toUpperCase() and checking if it matches a lowercase password "seahorse".
Check the snippet I made according to your code and it's running fine and dandy.
I added onclick call on your submit button so that it calls your isValid() function.
Also it's worth mentioning that you're passing a parameter to your isValid() function, but you don't need to because you're retrieving the password element and its value directly inside the function.
Another thing worth mentioning is that you're returning a boolean for the function but you don't really need to because you're not doing conditions in your script and when changing location on window.location or alert() the code will be stopped.
function isValid()
{
var pass = "seahorse";
var password = document.getElementById("password");
if (password.value.match(pass))
{
window.location.href = "HappyChristmas.html";
}
else
{
alert('Nope, try again');
}
}
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
</form>
</div>
First Add the event to the form to call your javascript function
<form name="PasswordField" action="/where/to/go" onsubmit="return isValid()">
Second remove the argument from the function definition function isValid(password){ ... } because you are overwriting it with the dom node (var password = document.getElementById("password");)
Third this can be changed
if (password.value.toUpperCAse().match(pass)){
to this
if (password.value.toUpperCase() == pass.toUpperCase()){
Two reasons:
1. You're not calling the isValid function from anywhere and 2. You don't have a argument password to add into the function. Give this a try:
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<-- Add an ID to the button -->
<button type="submit" id="submitBtn" class="btn btn-default">Submit</button>
</form>
<script type="text/javascript"
const pass ="seahorse"
const password = document.getElementById("password");
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", e=>{
e.preventDefault();
isValid();
})
function isValid() {
if (password.value.toLowercase().match(pass)){
window.location.href = "HappyChristmas.html";
return true;
}
else{
alert('Nope, try again')
return false;
}
}
</script>
My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">
I have a form
onclick confirm , i need to direct it to a particular url
function submitdata() {
if(confirm("Are You Sure You Want To Proceed?")) {
location.replace("http://www.w3schools.com");
} else {
alert("Cancelling");
}
}
</script>
After submitting this form submitdata() is called.
then i am getting an alert.
BUT MY FORM is not getting redirected
<form id="registration_form" action="" method="post" onsubmit="return submitdata();">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
if(confirm("Are You Sure You Want To Proceed?")) {
return true;
location.replace("http://www.w3schools.com");
}
return returns from the surrounding function. Nothing after it will be executed. You need to swap the two lines.
I got it
<script>
function submitdata() {
var r = confirm('Are you sure?');
if (r == true) {
window.open('http://www.google.com');
} else {
alert('it didnt work');
}
return false;
}
</script>
If you want the form to actually submit to that location, then the form data won't get sent with that redirect. You can submit the data by setting the action attribute of your form tag to the URL you want, and changing the form submit event to something like this:
function submitData(event) {
if(confirm('Are you sure you want to proceed?') == false){
event.preventDefault();
return false;
}
}
So instead of redirecting when the user clicks 'ok', you basically just cancel the form submit if the user doesn't click 'ok'.
If you didn't want to submit the data, then you just need to move your return statement, like melpomene suggested.
Note: I always write both event.preventDefault() and return false; but I think usually only return false; would work as well. But, better safe than sorry :)
I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>
Got a form that requires users to input an amount to donate. On clicking submit, a function is called and the function is meant to display the amount specified and prompt the user to confirm if the amount typed is the actual amount or not.
The Cancel option in the Confirm() keeps submitting the form instead of returning false.
function donationFormSend(){
get_donation_amount = document.getElementById("get_donation_amt").value;
if(get_donation_amount != ''){
return confirm("You have specified "+get_donation_amount+" as the amount you wish to donate. \n\n Are you sure you want to proceed with the donation?");
}
else{
alert("Amount must be specified to process your donation.");
return false;
}
}
<form method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input name="donation_submit" type="submit" id="Submit" value="Proceed" onclick="return donationFormSend();" />
</form>
Jsfiddle link
Would be pleased getting help with this.
I updated your jsfiddle so it's in the expected format (loading the js in the head) and returning the confirm result
return confirm('blah blah')
works perfectly well for me in FF! Just make sure you clear your cache and reload your page.
A way to do do it might be:
form :
<form id='test' method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input type="submit" value="submit" onClick="form_submit(this.value)">
<input type="submit" value="cancel" onClick="form_submit(this.value)">
</form>
javascript:
document.getElementById('test').addEventListener('submit',function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
})
form_submit= function (submited_by) {
if(submited_by == 'submit'){
alert('Submited')
}else if (submited_by == 'cancel'){
alert('cancelled')
}
}
I'd rather use a switch statement to make it expandable in the future but this should work.
Also I'm using jquery mostly because I'm not sure how to stop default action without it.
here's a JSFiddle with the code running.
EDIT: Updated to not use Jquery.
EDIT: well, I feel stupid now, realised it wasn't cancel button in a submit form but in a confirmation form.
In your HTML use : onclick="return donationFormSend();"
In Your Javascript: return confirm("Are you sure ....blah blah blah")