Html Form If statement in OnSubmit Field - javascript

I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!
<script type="text/javascript">
function checkform()
{
var myForm=document.frmhot;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
return false;
myForm.status.focus();
}
if (myForm.line.value==""){
alert("Please select a line.");
return false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
return false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
return false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
return false;
}
return true;
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
confirm('Do you want to submit the form?');
}
>
<input class="button_text" type="submit" value="Submit" name="submit" onclick= "checkform();" />
</form>

Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
function checkform(evt) {
var myForm = document.frmhot;
var condition = true;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
myForm.status.focus();
condition = false;
}
if (myForm.line.value==""){
alert("Please select a line.");
condition = false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
condition = false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
condition = false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
condition = false;
}
if(condition){ condition = confirm('Do you want to submit the form?'); }
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
<input type="text" name="status"/>
<input type="text" name="line"/>
<input type="text" name="reason"/>
<input type="text" name="partnum"/>
<input type="text" name="badgescan"/>
<input class="button_text" type="submit" value="Submit"/>
</form>

You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
if(checkform()) {
if (confirm('Do you want to submit the form?')) {
// submit the form
}
}
And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">

Related

Unable to stop form from submitting with empty inputs

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

Get Error for submit button before send data to Server side(php)

i have a text box or input to save Phone number, i want that Users Can Only be able to Enter 11 Numbers and Just can accept Numbers Not Characters.
how Check and show message.
how this is possible in client side Like JavaScript And then Sending To Server Side.
my code that it`s Incorrect:
<script language="JavaScript" type="text/javascript">
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
and in submit section:
<input type=submit border=0 value=" " Onclick=code(getElementById("Phone").value) />
Thanks
you should use return false after alert in validate condition, try this code
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
}
UPDATE
If you want to accept only 11 number then try with RegEx
function code(input){
if(input.match(/^[0-9]{11}$/)){
return true;
}
alert("Enter a Valid Phone Number");
return false;
}
submit button change Onclick to onClick with quote and use document.getElementById("Phone").value instead of getElementById("Phone").value
<input type=submit border=0 value=" "
onClick='return code(document.getElementById("Phone").value)' />
<script>
function code(inputd)
{
var phoneno = /^\d{11}$/;
if(inputd.match(phoneno))
{
return true;
}
else
{
alert("error");
return false;
}
}
</script>
<form>
<input type="text" id='Phone'>
<input type="submit" onclick=return code(document.getElementById("Phone").value);>
</form>
Please try this hope it is helpful.
Use jQuery Keypress event to disallow user to enter any character other than number (0-9).
jQuery(function(){
jQuery("#Phone").keypress(function(){
var value = jQuery(this).val();
value = value.replace(/[^0-9]+/g, '');
jQuery(this).val(value);
});
});
Now, in your validation script, check the length
function code(input){
if(input.length != "11"){
alert("Enter a Valid Phone Number");
return false;
}
else {
return true;
}
}
Using jquery is very easy. Try with:
<input type='text' id='phoneNum' border=0 value="" />
<input type='submit' id='submitBtn' border=0 value="" />
<script language="JavaScript" type="text/javascript">
$('#submitBtn').click(function(){
var phoneNum = $('#phoneNum').val();
code(phoneNum);
// other code
});
function code(input){
if(input.length != "11"){
//return false;
alert("Enter a Valid Phone Number");
} else {
return true;
}
}
</script>

How can I validate with javascript and then submit data with php?

<button type="button" onclick="submitForm()">Submit</button>
When I press this button it runs a javascript validation function that returns true or false based on whether some data is formatted properly.
What I need to do next is: if true submit the validated data to mySql database using a php script.
I am stumped at how I can accomplish this. I hope I am clear. Thanks.
Also, I can't use ajax.
In the php file you can do all the mysql verifications needed.
The submit can be something like this
<form action="update.php" method="post"> <button type="submit" onclick="return submitForm()">Submit</button> </form>
Notice the return in the function call.
The verification is returning false when validation fails.
function submitForm() {
if(validation) { // fails
alert("your message");
return false;
}
}
Do your button type to submit and send to the form ex like this
<form action="update.php" method="post">
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}
use type = "submit" instead of button. try with -
<button type="submit" onclick="submitForm()">Submit</button>
js validation
function submitForm() {
//your validation codes
//if validates
return true
//else
return false;
}
if validation succeeds the the form will be submitted else will not be submitted.
HTML:
<button type="button" onclick="submitForm()">Submit</button>
JS:
function submitForm() {
if(){ //condition to validate
return true;
}else{
return false;
}
}
Also (as a suggestion) you can add a specific function to validate each type of value so then just call it in your function submitForm() by those types
You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
^
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}
Do your button type to submit and send to the form
ex like this
<form action="index.php" method="post">
....
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
Hope this will help you
You need to add more detail from your html page. For instance the html form itself.
However just a hunch of what you are looking for.... you can use the folling command in your submitForm() function:
document.getElementById("myForm").submit();
We can't much help if we don't see your code. But in a nutshell you would submit the form by
document.getElementById('formId').submit();
What I need to do next is:
1->perform form.submit()
2->send all data's to database from your action file (action="action.php")
document.getElementById("form").submit()
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(zip, "Please enter a valid zip code")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>CA</option>
<option>TX</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>

Validating PHP Form Data Using Java Script

I am validating php form data using java script, but the form send the data without validating. Am I making any mistake in creating this form validation. HTM code is:
<form name="form1" action="sendmail.php" onSubmit="return validateform1();" method="post">
<table>
<tbody>
<tr><td><input id="name" class="w200" name="name" type="text" value="Your Name" onFocus="if(this.value=='Your Name')this.value=''" onBlur="if(this.value=='')this.value='Your Name'"></td></tr>
<tr><td><input id="cname" class="w200" name="cname" type="text" value="Company Name" onFocus="if(this.value=='Company Name')this.value=''" onBlur="if(this.value=='')this.value='Company Name'"></td></tr>
<tr><td><input class="w200" name="email" type="text" value="Your Email ID" onFocus="if(this.value=='Your Email ID')this,value=''" onBlur="if(this.value=='')this.value='Your Email ID'"></td></tr>
<tr><td><input class="w200" name="mno" type="text" value="Mobile No." onFocus="if(this.value=='Mobile No.')this.value=''" onBlur="if(this.value=='')this.value='Mobile No.'"></td></tr>
<tr><td><input class="w200" name="country" type="text" value="Country" onFocus="if(this.value=='Country')this.value=''" onBlur="if(this.value=='')this.value='Country'"></td></tr>
<tr><td><textarea class="w200n h60" name="message" cols="23" rows="4" onFocus="if(this.value=='Requirements')this.value=''" onBlur="if(this.value=='')this.value='Requirements'">Requirements</textarea></td></tr>
<tr><td><input type="submit" value="Submit"><input name="reset" type="reset" value="Reset"></td></tr>
</tbody>
</table>
</form>
And the java script for this form validation is:
<script language="javascript">
function validateform1() {
if($document.form1.name.value=="") {
alert("Enter Name");
return false;
}
if($document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
if($document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
if($document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
if($document.form1.country.value=="") {
alert("Please enter country");
return false;
}
}
</script>
There's no need to use $ in "$document"
You should use "document" only
This is what you should be try:
<script language="javascript">
function validateform1()
{
if(document.form1.name.value=="")
{
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="")
{
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="")
{
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="")
{
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="")
{
alert("Please enter country");
return false;
}
else
{
return true;
}
}
</script>
and call the validateform1() on "onSubmit" event of the form.
simply do this for all fields, because you already have the value assigned for the input type as Your Name, we need to check if it is either Your name or null
if(document.form1.name.value=="Your Name" || document.form1.name.value=="")
If none of the conditions trigger and return false, you need to return true; at the end before your last closing squiggly bracket ( } ).
To clarify: I would write the function like this:
function validateform1() {
if(document.form1.name.value=="") {
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="") {
alert("Please enter country");
return false;
}
return true;
}

How to get `form.field.value` in jQuery?

in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin:
https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this represents the form element so you could just do this.uName.value and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val() is jquery method, and in plain javascript you would use value and in this case that should be sufficient enough.
This will help you:
jQuery(function($) {
var $username = $('#uName'),
$password = $('#passKey');
$('form').submit(function() {
if ($username.val() == '') {
alert('Please enter username');
$username.focus();
} else if($password.val() == '') {
alert('Please enter username');
$password.focus();
} else {
return true;
}
return false;
});
});
Some points you need to keep in mind:
If you will work with the DOM you should wrap your code inside a jQuery(function() { ... }); block.
If you want to access a DOM element with jQuery you need to select it before using $(...).

Categories

Resources