Process a form with javascript and use it in pop up? - javascript

Theres a form on a website I'm trying to make and I was wondering if there was a way to click the submit button for the form and then have a pop up use that information
sorry for the newb question, code is kind of like this:
<form name="myform" onsubmit="submitform()" type="POST">
Username: <input type="text" name="username">
<a>
<input type = "submit" value = "Submit"
</a>
</form>
<script type="text/javascript">
function submitform()
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
</script>

Yeah, there's a few issues with your code, but you're close.
Submit buttons shouldn't be inside of <a> tags. You're also missing the closing carrot here.
You're using type, but I'm guessing you meant method.
In your JavaScript, you're getting an array of elements with getElementsByName and never getting the value.
Put that all together, and:
<form name="myform" onsubmit="submitform()" method="POST">
Username: <input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
<script>
function submitform()
{
username = document.getElementsByName("username")[0].value
window.alert("hi:" username)
return false;
}
</script>

You can try this:
<form name="myform" onsubmit="submitform(this) return false;" type="POST">
then in your function:
function submitform(form)
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
Then use the form object your passing in.
if ($(form).valid())
{
var fields = $(form).serializeArray();
$(fields).each(function ()
{
if (this.name !== undefined)
{
var propertyName = this.name;
var propertyValue = this.value;
//Do something
}
});
}

Related

Javascript form validation not loading PHP page

I have the following form in a PHP page
<form action="login.php" method="post">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<input type="button" name="loginSubmit" value="submit" onclick="return validateLogin()">
</form>
My validation looks like this
function validateLogin() {
var school = document.getElementsByName("schoolInput")[0].value
var username = document.getElementsByName("usernameInput")[0].value
var password = document.getElementsByName("passwordInput")[0].value
var failed = false;
if(!school){
document.getElementById("erschool").innerHTML = "No school entered";
failed = true;
}
if(!username){
document.getElementById("eruser").innerHTML = "No username entered";
failed = true;
}
if(!password){
document.getElementById("erpass").innerHTML = "No password entered";
failed = true;
}
if(failed){
return failed;
}
return true;
}
The JS in the validation works as it activates the error messages. However, if the form is completed correctly, it doesn't load login.php as it should.
I'm running the app on Heroku for testing.
What am I doing wrong?
You need to use <button type=submit"> to submit the form. Also, you can move the validation into the form. i.e.:
<form action="login.php" method="post" onclick="return validateLogin()">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<button type="submit" name="loginSubmit" value="submit">
</form>
Also, your validation function is wrong - it will always return true (so the form will always be submitted):
if(failed){
return failed; // if failed is true, then return TRUE...
}
return true; // ....otherwise return TRUE!!
I presume you mean to return !failed so if failed is true then you return false?
You don't actually need to check the value for failed either- you can just return !failed:
if failed is true, then !failed will return false so the form is not submitted
if failed is false, then !failed will return true so the form is submitted
How to make it work
What you probably wanted to achieve is:
<button type="button" onclick="if(validateLogin()) this.form.submit()">
This way, your form only gets submitted if the function returns TRUE. (Which, as #FluffyKitten pointed out, will always be the case so you have to fix the validation function too.)
There are more than one ways to validate a form. My favorite is giving the form an onsubmit handler, and the syntax you used on the button looks like you were trying to mix this technique with the button-click validation method. Form onsubmit way looks like this:
<form onsubmit="return validateLogin()">
...
...
<button type="submit">
</form>
These are 2 separate ways.
Method 1: form onsubmit=return valid() + button type=submit
Method 2: form + button type=button onclick=if(valid()) submit()
Improve validateLogin
I'd suggest some refactoring here, both for readability and ease of use.
function validateLogin() {
var checkEmpty = function(name) {
var element = document.getElementsByName(name+"Input")[0];
if(element.value !== "") return false; // return if not empty
var errorField = document.getElementById("er"+name);
errorField.innerHTML = "No value for "+name;
return true;
}
if(checkEmpty("school" )) return false;
if(checkEmpty("username" )) return false;
if(checkEmpty("password" )) return false;
return true;
}

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>

Javascript - how to prevent form from sending with multiple validation checks?

It seems that you can prevent a form from sending if your validation check returns false.
I have:
<form name="registration" action="registration.php" onsubmit="return validate()">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
My validate() function in my javascript is made of multiple different checks though.
function validate() {
checkUsername();
checkPassword();
checkFirstname();
checkLastname();
checkBirthdate();
checkEmail();
checkPhone();
}
There might be a case where the user inputs valid data for all of them except one. If that's the case, how do I tell validate() to still send 'false' back to the form, so that it doesn't submit?
Edit: If anyone is still reading this, for some reason my form is still sending. I even changed my validate() function so the only statement is "return false;" Do I have a syntax error or something?
Edit2: I found another solution that is simple, even if a little archaic. It overcame an issue I had where the function was only evaluating the first check and returning.
function validate() {
var truth1 = checkUsername();
var truth2 = checkPassword();
var truth3 = checkFirstname();
var truth4 = checkLastname();
var truth5 = checkBirthdate();
var truth6 = checkEmail();
var truth7 = checkPhone();
return (truth1 && truth3 && truth5 && truth2 && truth4 && truth6 && truth7);
}
all your individual field validation functions should return a boolean.
then your overall form validation function will be
function validate() {
var checks = [
checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone,
].map(function(check) { return check(); });
return (checks.indexOf(false) === -1);
}
now ur validate function will return false if any field is invalid. true if all fields are valid
You can use Array.prototype.every() to call each function, if any function returns false, false will be returned from .every() call
<form name="registration" action="registration.php">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
function validate() {
return [checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone].every(function(check) {return check()});
}
document.querySelector("[name=registration]")
.onsubmit = function(event) {
event.preventDefault();
if (validate()) { this.submit() }
else { // notify user which fields are invalid }
}
The "validate" function needs to return a "true" boolean result only when ALL of the individual check functions return a "true" result.
One way to do this is to modify each line in the current "validate" function to something like the following code.
bUsernameSts = checkUsername();
if !bUsernameSts { return false };
...
<other checks>
...
return true;
The only way the new "validate" function can return "true" is if all of the individual input validation checks were successful.

I want the user to not be able to advance to the next screen if he/she doesn't enter the required information

The function receives the username and password of the user. If either are left empty, nothing happens and they won't be linked to google.ca if they click the "Go" button. If they filed in the required sections then they will be directed to google.ca. For some reason, if any of the text boxes are left unfilled and the Go button is pressed, it brings me to a 404 error page when I want it to just stay on that page until the user fills the textbox. What is causing this problem? This is the HTML file.
<form action="index.php" method="get" id="form" onsubmit="return go(document.getElementById('username'), document.getElementById('password'))">
<table>
<tr><td>Username: <input type="text" name="username" maxlength="16" id="username" onKeyUp="updateLength('username', 'usernameLength')" onblur="checkTextField(this);"/> <span id="usernameLength"></span></td></tr>
<tr><td>Password: <input type="password" name="password" maxlength="50" id="password" onKeyUp="updateLength('password', 'passwordLength')"> <span id="passwordLength" onblur="checkTextField(this);"></span></td></tr>
<tr><td><input type="submit" value="Go" id="goButton" onclick="go(username, password)"/></td></tr>
</table>
</form>
And here is the js file
function loginFunction() {
var url = "login.html";
window.open(url);
}
function createAccountFunction() {
var url2 = "createAccount.html";
window.open(url2);
}
function go(username, password) {
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
function updateLength(field, output) {
var curr_length = document.getElementById(field).value.length;
var field_mLen = document.getElementById(field).maxLength;
document.getElementById(output).innerHTML = curr_length + '/' + field_mLen;
}
function checkTextField(field) {
if (field.value == '')
alert("Field is empty");
}
You aren't stopping the default event of the onsubmit. You can do that by changing your go function to:
function go(username, password) {
return function(event) {
event.preventDefault();
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
}
You also don't need the return in the HTML. Just call the function.
I didn't understand your code logic, but maybe I can offer you a way to fix your code by yourself.
You have a form and a button. If you click on the button you execute the go() function. Because the button is a submit button, on the same click you execute one more time the go() function.
My advice is to create a new function, you may name it validate():
function validate() {
var username = document.get........
var password = document.get........
// more logic here, if need
if(!username || !password) {
return false;
}
return true
}
and now, your submit button looks like:
<input type="submit" value="Go" id="goButton" onclick="return validate()"/>
The form won't submit if the validate() function returns false.
Hope this helps.

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Categories

Resources