I am currently using the dotmailer to generate a new form (simple textbox and submit button) that automatically adds the email address to the dotmailer address book.
When someone submits an email address - they can be taken to a webpage.
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
I have been trying to work out a way to present an alert box saying "submitted" and not take take the user to a thank you page.
Solution?
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
But all this does, it displays an alert box and then redirects to the following url (even when the value is inserted or not).
http://dmtrk.net/undefined?result=success
404 The page you are looking for could not be found
Is there anyway i can adjust this so it submits the email but does not redirect.
Full Code:
<script language="javascript">
<!--
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
var els = frm.getElementsByTagName('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].className == 'text' || els[i].className == 'date' || els[i].className == 'number')
{
if (els[i].value == '')
errorString = 'Please complete all required fields.';
}
else if (els[i].className == 'radio')
{
var toCheck = document.getElementsByName(els[i].name);
var radioChecked = false;
for (var j = 0; j < toCheck.length; j++)
{
if (toCheck[j].name == els[i].name && toCheck[j].checked)
radioChecked = true;
}
if (!radioChecked)
errorString = 'Please complete all required fields.';
}
}
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
var isError = false;
if (errorString.length > 0)
isError = true;
if (isError)
alert(errorString);
return !isError;
}
//-->
</script>
HTML:
<form name="signup" id="signup" action="http://dmtrk.net/signup.ashx" method="post" onsubmit="return validate_signup(this)">
<input type="hidden" name="addressbookid" value="">
<input type="hidden" name="userid" value="41929">
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
<input type="text" name="Email" onfocus="if(this.value=='Email')this.value='';" class="blueTextBox">
<input type="Submit" name="Submit" class="submit">
</form>
To send information without doing a full page reload you need to use AJAX. It's easiest to use an existing javascript library, for example jQuery.
Check out these pages:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/on/
Related
I currently have a form with a few variables like username, password, and email which sends the data to a node.js server. Before sending the data, I have a few checks such as whether the inputs are valid and whether the email already exists in my file. The checking aspect of my code works, however the javascript function which I use to check returns before opening the file to check for duplicate emails. I feel that if I could somehow make the onsubmit function asynchronous, that would help.
Here is my code and the segment where I check for duplicate emails is near the end:
<html>
<body>
<form id='form' action="/signup.html" method="POST" onsubmit="return submitIt();">
<div style="text-align:center">
<label for="name">Full Name</label><br>
<input type="text" size="100" id="name" name="name" placeholder="Enter Your Full Name: "><br><br>
<label for="email">Email</label><br>
<input type="text" size="100" id="email" name="email" placeholder="Enter Your Email: "><br><br>
<label for="password">Password</label><br>
<input type="text" size="100" id="password" name="password" placeholder="Enter Your Password: "><br><br>
<button type="submit" id="submit">Submit</button>
</div>
</form>
</body>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var ret = true;
async function submitIt() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
if (name == "" || name.length < 4) {
document.getElementById("name").value = "";
document.getElementById("name").placeholder = "Please enter a real name";
ret = false;
}
if (email == "" || email.length < 4) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
if (ret) {
let found = false;
for (let i = 0; i < email.length; i++) {
if (email[i] == '#') {
found = true;
}
}
if (!found) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
}
if (password.length < 5) {
document.getElementById("password").value = "";
document.getElementById("password").placeholder = "Password must be atleast 5 characters.";
ret = false;
}
await $.ajax({
type:"POST",
url:'/getUsers',
dataType: "text",
success: function(content) {
let contents = content.split('\n');
for (let i = 0; i < contents.length; i += 3) {
if (contents[i] == email) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Email already in use.";
ret = false;
}
}
}
});
return ret;
}
</script>
</head>
</html>
Any help would be greatly appreciated!
Have you tried moving onSumbmit call from form to the button?
const submitButton = document.getElementById(***)
submitButton.addEventListener('click', () => {your code})
Another way could be preventing default behavior of the submit form.
async function submitIt(event) {
event.preventDefault;
event.stopImmediatePropagation;
....your code....
}
I don't have access to a PC right now to check it, but one of the provided solutions should work. Cheers!
The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>
The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.
I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.
http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.
js validation works perfectly when I step through it, but fails at "normal speed." SPECIFICALLY: if a dup email is caught but the other fields are filled in correctly, the form can be submitted (but no error is forthcoming when stepping through the code). Has anyone seen this before? I know I could just code it a different way, but I cannot simply walk away from this simple problem that's even become a bottle kneck without first understanding why this isn't working.
My approach is to validate onblur and onsubmit. I am using the jquery selector only for convenience and then again for an ajax call, but otherwise i'm using js. I am doing a loop through the fields but only operating on text and password fields.
checking for blanks
checking for no numbers in name
checking for email address properly formatted
and then checking for unique email in the email field
annotated code below for js and form below:
//registration validation
$('.validate').blur(function() {
var theForm = document.registerNewUserForm;
//removes error messages from html before the run
clearAllErrors(theForm);
var msg = "";
var mdiv;
theForm.submit.disabled=true;
document.getElementById("submitButton").disabled = true;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
mdiv.innerHTML = msg;
break;
}
}
if(msg == "") {
theForm.submit.disabled=false;
document.getElementById("submitButton").disabled = false;
}
});
$('#registerNewUserForm').submit(function() {
var theForm = document.registerNewUserForm;
clearAllErrors(theForm);
var msg = "";
var mdiv;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
break;
}
}
if (msg != ""){
mdiv.innerHTML = msg;
return false;
} else {
theForm.submit();
}
});
function validateField(theField) {
msg = "";
//all fields are required
if (theField.type == "text" || theField.type == "password") {
if (theField.value == "") {
msg = "The " + theField.name + " field is required.";
}
}
//name fields are non-numeric
if (theField.name == "fullName"){
if (hasNumber(theField.value) == true){
msg= "The Name field is non-numeric.";
}
}
//email must be correctly formatted
if (theField.name == "email") {
msg = emailCheck (theField.value);
if (msg == "") {
//email address must also be unique
chkEmail();
msg = document.getElementById('emailMessage').innerHTML;
}
}
return msg;
}
function chkEmail() {
emailAddr = document.getElementById("email").value;
$.ajax({
url: '/chkEmail',
type: 'POST',
data: 'emailAddr=' + encodeURIComponent(emailAddr),
dataType: "xml",
context: document.body,
success: function(data) {
document.getElementById('emailMessage').innerHTML = $(data).find("message").text();
}
});
}
<form name="registerNewUserForm" id="registerNewUserForm" action="/register" method="post">
<br/>
<div>Create an Account and join the fun!</div>
<div><input class="validate" type="text" id="fullName" required placeholder="Full Name" name="fullName" value="" size="30"></div>
<div id="fullNameMessage" class="error"></div>
<div><input class="validate" type="text" id="email" required placeholder="Email Address" name="email" value="" size="30"></div>
<div id="emailMessage" class="error"></div>
<div><input class="validate" type="password" id="passWord" required placeholder="Password" name="passWord" value="" size="30"></div>
<div id="passWordMessage" class="error"></div>
<div style="position:relative;left:173px;"><input id="submitButton" type="submit" value="Signup for PastelPlanet"></div>
<input type="hidden" name="formName" value="registerNewUserForm">
<input type="hidden" name="urlDestination" value="">
</form>
Your "chkEmail" function involves a call to the server, and it's asynchronous. The call to the server will not be complete when the function returns, when you're running at "full speed".