Popup alert showing prematurely? - javascript

I'm working on a submission form that includes a few required fields, and I have a segment of code that allows a popup menu to appear once you hit the "submit" button, and from there once you hit "ok" on the alert you're redirected to the home page. Here's the code I have for the popup alert.
<div id="popup">
<button onclick="myFunction()">Submit</button>
<script>
function myFunction(){
alert("Thank you! \nYour sumbission has been
accepted and you will receive a conformation email shortly! \n
You will now be taken to the Home page.");}
</script> <input type="reset" value="Reset" />
</div>
And this is the beginning of the code for redirecting you to the homepage.
<div id="all">
<div id="text">
<h1>Your Information</h1>
<form id="contact_form" action="home.html" method="post">
<input type="hidden" name="redirect" value="home.html" />
(Note: I clipped the above segment of code because the following information is only the form input boxes)
And this works like you would imagine, the alert popping up once you hit the submit button. However my question is that I have a few required fields on my form, and if the fields are not filled out and you hit "submit", the popup alert appears, and once you hit "ok" on the alert, because you have yet to fill out these fields it takes you back to the form and a little box saying "this field is required" appears.
This is in the wrong order. I want the alert box for the required fields to show before the popup alert for the confirmation of form submission, so that if you have required fields and you hit submit it will tell you to fill out the required fields before the message appears thanking you for submitting.
This may be a simple fix of placement or adding a little code but I'm having a hard time figuring out how to do it or finding an example that could help me.
If you know what to do I'd really appreciate it, thanks!
Edit: This is the javascript file for the validation code.
window.onload = setForm;
function setForm() {
document.forms[0].onsubmit = function() {
if (this.checkValidity()) alert("No invalid data detected. Will
retain data for further testing.");
return false;
}
}

function Validation()
{
vak k = true;
k = function 1 validates field 1 AND returns true or False based On Validation
k = function 2 validates field 2 AND returns true or False based On Validation
k = function 3 validates field 3 AND returns true or False based On Validation
return k;
//At The End Of This Function You Need To Get "TRUE" To Truly Submit.
}
On Submit :
If(Validation() == true)
{
then Only Submit
}
Write Back If It Dosen't Works...

<html>
<body>
<div id="popup">
<textarea cols="30" rows="2" name="required" id="required"></textarea>
<input type="submit" id="click" value="Submit">
<input type="reset" value="Reset" />
</div>
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
var required = document.getElementById("required").value;
if (required===null || required==="") {
alert("Please make sure all required field are completed");
}
else {
alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
window.location.replace("http://stackoverflow.com", 5000);
}
});
</script>
</body>
</html>
http://jsbin.com/wuxahape/1/

Related

Google reCaptcha attribute 'data-callback' causing page refresh on alert

I have added Google reCaptcha v3 script to my form. The form also includes validation that alerts the user to complete the input field. Now when the user clicks on submit button directly, an alert is shown and when OK is clicked the page refreshes and form data is submitted in the backend. I have tried adding return false and e.preventdefault() in the function but the page still resets after the alert. If I try to add any additional condition to the data-callback function, the submit button stops working.
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
<script>
function validateForm() {
var fname = document.forms.WebForm.fname.value;
if (fname == "") {
alert("Please fill out all the fields");
return false;
}
}
</script>
</head>
<body>
</style>
<div class="container">
<form action="https://www.samepage.com" method="post" id="demo-form" name="WebForm">
<div>
<div>
<input name="fname" id="fname" type="text" placeholder="First name*" required/>
</div>
</div>
<div>
<div>
<input type = "submit" style = "font-weight: bold;" value="Submit" class="g-recaptcha button" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
data-callback='onSubmit'
data-action='submit'
onClick="return validateForm()"/>
</div>
</div>
</form>
</div>
</body>
</html>
Even the required attribute in the input tag doesn't work with the recaptcha script added. When I remove the data-callback attribute and the supporting script functions, the alert and form works as expected.

$myform.textinput.$isvalid is true when it should not

The whole form should not be valid until stuff[] has at least one item added to it. When the user enters in a value into the text box and then clicks add it then adds the value to stuff[], only at this point when a value has been added to stuff[] should the submit button be enabled. However, as soon as the user types anything into the text box without clicking add, and thus nothing in stuff[], it makes the form valid and enables the submit button.
<form ng-app="myApp" ng-controller="myCtrl" name="myForm" ng-submit="submit()" novalidate>
<div ng-repeat="things in stuff">
<table><tr><td>{{things}}</td></tr></table>
</div>
<input type="text" name="app" ng-model="input" ng-required="!stuff[0]" />
<button ng-disabled="!input" ng-click="add()">
<span> add</span>
</button>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid" />
<script>
angular.module('myApp', []).controller('myCtrl', function ($scope) {
$scope.stuff = [];
$scope.input = null;
$scope.add = function () {
var l = $scope.stuff.length;
$scope.stuff[l] = $scope.input;
$scope.input = null;
};
$scope.submit = function () {};
});
</script>
</form>
[EDIT]
To answer your question directly: !stuff[0] is TRUE when there is nothing in the array, and FALSE otherwise. When it is TRUE, then input is required, making the form 'initially' invalid. As soon as you type something into the input, then the requirement is now fulfilled, meaning that the form is valid, and you can now click the submit button. The condition actually has nothing to do with actually putting something into the array.
This is fixable by attaching a condition to stuff.length as proposed by my answer below. It won't make the form invalid (which you can easily do with this condition elsewhere) but it will at least disable the submit button.
[/EDIT]
I don't understand why you have ng-required there, as you are wanting to disable the submit button, meaning the logic should be attached to the submit button, not the input text box.
I would do this instead:
<input type="text" name="app" ng-model="input"/>
<button ng-disabled="!input" ng-click="add()">
<span> add</span>
</button>
<input type="submit" value="Submit" ng-disabled="stuff.length == 0" />
Which will disable the submit button if there is nothing in stuff.

Simple Javascript login form

<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).

using javascript to modify form action submits form without doing submit

I have an HTML form that I submit after changing the action with some javascript. Two different buttons can do the submit.
The interesting thing is that I was trying to debug it and inserted an alert after changing the action and before submitting the form. The form is submitted without the alert ever being displayed. To make sure it's actually performing the javascript, I added an alert before changing the action. That alert displays; the alert after changing the action does not.
<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>
<script type="text/javascript">
function SubmitForm(target){
alert("Action 1: " + document.FormSelect.action);
if (target=="class") {
document.FormSelect.action = "ClassAction.php";
} else {
document.FormSelect.action = "StudentAction.php";
}
alert("Action 2: " + document.FormSelect.action);
// document.FormSelect.submit();
}
</script>
Is that the expected sequence of events?
Any button placed inside form element will cause submit action. To prevent this you can add type="button" to button elements, or make you submit callback return false;
<button type="button" onclick="SubmitForm('class')">Submit</button
see http://jsfiddle.net/yD2Uu/
As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.
<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>
It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)
function SubmitForm(button){
button.form.action = button.formaction;
}
A better solution is to give the buttons a name each and submit to Action.php and let the server get the value of the named button
$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning
when you have
<form method="post" action="Actions.php">
<input type="submit" name="student" value="John Doe" />
<input type="submit" name="student" value="Jane Doe" />
<input type="submit" name="student" value="Whatever Doe" />
</form>
Otherwise if you must
Try this
<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>
<script type="text/javascript">
var actions = {
"class":"ClassAction.php",
"student":"StudentAction.php"
}
function SubmitForm(button){
button.form.action = actions[button.value];
button.form.submit();
}
</script>
Thanks to Yauhen Vasileusky's example, I started removing code between my 1st & 2nd alerts and found that the problem seems to be the following IF statement:
if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}
When I remove it, both alerts are displayed. So the answer to my question is that changing the action does not submit the form; it was some other error in my code that made it appear as if that was the case.

when I click submit, it goes straight onto another page

My form submits to another page when I do not want it to. The current page is known as create_session.php
I want the form to submit if all of the validation and the postback is met and even after that the user needs to click "Ok" when the confirmation box appears. Except this never happens. When the user clicks on the submit button, it takes the user straight to another page "QandATable.php", it doesn't care about about validation(), the postback() and the confirmation box doesn't appear.
So what I want to know is that when the user clicks on the submit button, how can I get it so that it checks for the validation(), postback() and confirmation box (showConfirm()) before even going onto the next page.
I believe the problem is the submit button and the form action. Below is the form:
<form action="QandATable.php" method="post" id="sessionForm">
<p><input type="text" id="txtMarks" name="textMarks" onkeypress="return isNumberKey(event)" maxlength="5" /><br/><span id="marksAlert"></span></p>
<p><strong>Room:</strong> <input type="text" id="room" name="roomChosen" value="<?php echo $roomChosen; ?>" />
<br/><span id="roomAlert"></span></p> <!-- Enter Room here-->
<p><input class="questionBtn" type="submit" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
</form>
Below is the javascript click handler where it checks for the validation(), postback() and then if both of those met then it will showConfirm().
function myClickHandler(){
if(validation()){
postback(function(message) {
if (message == "")
showConfirm();
});
}
}
You need to return false from your onClick handler to prevent the form from being submitted.
You need to make sure the default action isn't applied when the submit button is clicked. In this case, the default action is to submit the form.
Try adding a return false; such as
<input class="questionBtn" type="submit" value="Prepare Questions" name="prequestion" onClick="myClickHandler(); return false;"/>
Two changes; you need to pass the function, not the function's return value, and you need to return false:
<input class="questionBtn" type="submit" value="Prepare Questions" name="prequestion" onClick="myClickHandler" />
------------------------------------------------------------------------------------------------------------^ here
and
function myClickHandler(){
if(validation()) {
postback(function(message) {
if (message == "")
showConfirm();
});
}
return false;
}

Categories

Resources