Can not submit a form using javascript - javascript

The hyper link as a submit button is not working.
I think the error may be this <a href="javascript:subForm('myform')">.
I don't know whether this line accept string 'myform' as parameter.
Thanks for your help.
JS
function valid(form) {
if (form.passwd1.value == "") {
alert("Please enter the password")
form.passwd1.focus()
return false
}
if (form.passwd1.value != form.passwd2.value) {
alert("Passwords do not match");
form.passwd1.focus()
form.passwd1.select()
return false
}
return true
}
function subForm(form){
if( valid(document.form)){
document.form.submit();
}
}
Form
<form action="abc.html" name="myform">
Your name: <input type="text" size="30" />
<p>Choose a password: <input type="password" name="passwd1" /></p>
<p>Verify password: <input type="password" name="passwd2" /></p>
<img src="images/submit.jpg"/>
</form>

Instead of passing the form through as a parameter just validate the fields directly in valid(), i.e.
if (myform.passwd1.value == "") ...

For getting form by formName, you should use document.forms[formName]. Your subForm function should change to:
function subForm(formName) {
var form = document.forms[formName];
if (typeof form !== 'undefined' && valid(form)) {
form.submit();
}
}

Related

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

html form with javascript window.location not working

I added this code to my website:
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location = "member.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
}
</script>
<form action="">
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>
However, after i inserted the correct password & name, i only see the link became:
http://tool-box.weebly.com/test.html?loginname=jamie&loginpwd=198237645
What should i do? if i change window.location="member.html" to document.write("Password Correct!"), it worked correctly.
Please help.
You need to cancel the click action so the form does not submit
onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value); return false;"
I hope you realize this is NOT secure.
Couple of error in code
a) onclick of submit button doesn't return anything hence the form is submitted each time
b) use window.location.href
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location.href = "memeber.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
return false;
}
</script>
<form action="" >
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick = "return checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

Javascript Form validation not working on any fields

Below is form validation using JavaScript but it's not working.
function validate()
{
var n=document.frm.name.value();
if(!n.match(/^[a-zA-Z]+$/))
{
alert("Enter valid Name");
document.frm.name.value="";
document.frm.name.focus();
return false;
}
var b=document.frm.mob.value();
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
return false;
}
var y=document.frm.nn.value();
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
return false;
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
return false;
}
}
<body>
<form name="frm" action="#" method="post" onsubmit="return validate()">
Name :<input type="text" name="name"/>
Mobile No:<input type="text" name="mob" />
Not Null :<input type="text" name="nn"/>
Email Id:<input type="text" name="email"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
First off, don't name your fields with reserved words (like "name")
Second, value is a property, not a method, so,
var b=document.frm.mob.value;
(without the brackets)
Please,place return false outside the function.
var b=document.frm.mob.value;
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
}
var y=document.frm.nn.value;
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
}
return false;
}
Instead of calling the function validate() in form tag on event onsubmit, better use it in submit button
<input type="submit" name="submit" value="submit" onClick="return validate()" />
It will work better and outputs as required.

Categories