JavaScript validate, then print and submit - javascript

I have a submit function to validate form inputs, then optionally (checkbox) print as part of the submit process.
The problem is that when printed, form submission never completes, without printing form submission works correctly.
<INPUT class=checkboxes id="Place order" onclick="return checkfields()" type=submit value=SUBMIT name="Place order">
The validation always works correctly (AFAIK).
function checkfields() {
var missinginfo="Please fill the following information";
var bres = true, qty=0, elem;
var tqty = document.getElementById('bottles').value;
if (tqty ==0){alert("No wine selected");bres=false;return bres;}
if (tqty %6 !=0){
alert("Orders need to be in 6 bottle packs please add " + (6 -(tqty %6)) + " Bottles to order");
bres=false;
return bres;
} //end if
for (i=1; i<30; i++) {
elem = document.getElementById('f'+i);
if(elem !=null){
if(elem.value== ""){ // ||
//(document.form.website.value.indexOf("http://") == -1) ||
//(document.form.website.value.indexOf(".") == -1)) {
bres = false; missinginfo += "\n " + (document.getElementById('f'+i).name);
} //end if
} //end if
} //end for
if(!bres){alert (missinginfo );}
// end of validation here, print if checkbox checked
if(bres && document.getElementById('cprint').checked==true){window.print();}
document.getElementById('doc').value = "";
return bres;
} //end function
Any suggestions on how to remedy, or am I doing something completely wrong?

Use onsubmit instead of onclick:
<INPUT class="checkboxes" id="Place order"
onsubmit="return checkfields();"
type="submit" value="SUBMIT" name="Place order">

Related

onclick for radio button using javascript

I am trying to write this program for this survey I want a user to answer, after they have completed the survey they would go to click on submit and it would display confirmation of their choices. I can't get this to work for the life of me.
Here's my code:
<!DOCTYPE html>
<title> Satisfaction Survey </title>
<script Language ="Javascript">
function testpage() {
errmsg = " ";
confirmmsg = " ";
errflag = false;
if ( document.form1.rdservice[0].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very satsified" ;
}
if ( document.form1.rdservice[1].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is satisfied" ;
}
if ( document.form1.rdservice[2].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is neutral" ;
}
if ( document.form1.rdservice[3].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is unsatsified" ;
}
if ( document.form1.rdservice[4].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very unsatsified" ;
}
if ( (doucment.form1.rdservice[0].checked == false) &&
(doucment.form1.rdservice[1].checked == false) &&
(doucment.form1.rdservice[2].checked == false) &&
(doucment.form1.rdservice[3].checked == "false") &&
(doucment.form1.rdservice[4].checked == false)) {
errflag = true;
errmsg = errmsg + "<br> You forgot to select an option";
}
}
</script>
<body>
<form name=form1 method="post">
<fieldset>
<legend> Please take a few moments to complete this satisfaction survey. </legend>
<fieldset>
<legend> Overall, how satisfied were you with the product / service? </legend>
<input type="radio" name="rdservice" value="v"> Very Satisfied
<br>
<input type="radio" name="rdservice" value="s"> Satisfied
<br>
<input type="radio" name="rdservice" value="n"> Neutral
<br>
<input type="radio" name="rdservice" value="un"> Unsatisfied
<br>
<input type="radio" name="rdservice" value="vu"> Very Unsatisfied
</fieldset>
<fieldset>
<input type="submit" name="subm1" value="Submit" onclick="testpge()">
<input type="Reset" name="Res1" value="Reset Form">
</fieldset>
</fieldset>
</body>
</form>
</html>
The code is a bit mess, can I suggest to use jquery(https://jquery.com/download/)? It will make your life a lot of easier!
here is the jquery code that you need:
var confirmmsg = "";
var errflag = false;
var errmsg = "";
$.each($('form input[type=radio]'), function() {
if($(this).is(":checked")) {
confirmmsg += "<br> Overall is " + $(this).text();
} else {
errflag = true;
}
});
if (errflag) {
errmsg = "<br> You forgot to select an option";
}
This code takes each input radio element and check if it's checked and then make the confirmmsg and also if one of them it's not checked then the errflag becomes true and also you set up the errmsg
btw, I think you need checkbox instead of radio inputs here
(non jquery approach)
Form inputs that are "button" are simply buttons. You can attach event to those inputs, but they aren't related to submitting form. If you want to make button which will send form you should set "type" attribute to "submit". And then you can verify your form in JavaScript by adding event "onsubmit" to <form> tag, not the button. You can also use "onreset" to catch event if someone press button which cleans form. If you are adding "onsubmit" function, like:
onsumit="return testpage(this);"
you can easy decide inside that function, if form should be send or not. You can do this by returning value. If you return true, form will be send, and if you return false form will not be send. You can also disable sending form by setting "action" attribute of <form> tag to "javascript:void(0);"
In your code i would add "onsubmit" event to <form> tag and i would remove "onclick" from submit button (you are calling function and then posting form) and i also would change function code to:
function testpage(frm)
{
var radioBoxSelected = false;
for(var i=0; i < frm.elements.length;i++)
{
if (frm.elements[i].type == 'radio' && frm.elements[i].checked) {
radioBoxSelected = true;
val = frm.elements[i].value;
// You can move messages to attribute "value" of radio boxes
alert('You have selected: ' + val);
// Below line sets some tag inner content to radiobox "value" attribute
document.getElementById("satisfied_value").innerHTML = val;
// Uncomment if you want send form here
//return true;
}
}
if (!radioBoxSelected) {
alert('Please select option!');
return false;
}
}

How to alert user for blank form fields?

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}

Form using javascript make field required?

I have a form that uses a javascript file items.js to add new items. So each time form.php is used and the 'add items' buttons is clicked then the new row of fields show to add details.
So for example some of the code is the following to add field item name.
newCell = newRow.insertCell(3);
newCell.innerHTML = '<input class="item_text_area item_name" type="text" name="0_item_' + new_item + '" id="0_item_' + new_items + '" size="20" maxlength="250" />';
How can I edit this .js file to make the Item name field required?
Any help would be appreciated.
Per Jeevan: As you cannot be sure how many items the user submits, I would choose for an approach where all new items have unique class, say dynamicAddedItems.
As Jeevan already said, you can add the following to the form tag to prevent it from submitting if it returns false.
<form onsubmit="return validate();"></form>
With javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
This script will add the error class if a field is empty and prevent the form from being submitted. It's up to you how you want to display a field with such a class.
You can use jquery for this. Add a class, in this case 'requiredAttr' to the required fields and then validate on form submit.
<form onsubmit="return validate();">
First Name*: <input class="requiredAttr" type="text" /><br/>
Last Name: <input type="text" /><br/>
<input type="submit" />
</form>
function validate(){
$(".requiredAttr").each(function(){
if($(this).val().length < 1){
alert("please fill in all the required fields.");
$(this).focus();
return false;
}
else{
return true;
}
});
return false;
}
Here is a working fiddle. It also brings the focus on the first un-filled field after the validation alert:
http://jsfiddle.net/YG6mk/2/

Javascript alert on submit if text field is empty

So i want to alert the user if they submit the form with an empty text field
HTML:
<form id="orderform">
<input type="text" name="initials" id="initials" maxlength="3">
<p class="center">
<input type="image" src="#" id="submitbutton" name="submit" value="Place Order">
</p>
</form>
Javascript:
$('#orderform').submit(function() {
if($('#initials').length == 0){
alert('Please fill out your initials.');
}
});
Just make sure you return false in there somewhere-
$('#orderform').submit(function() {
if($('#initials').val() == ''){
alert('Please fill out your initials.');
return false;
}
});
$('#initials').length will check if the element exists. Try this:
$('#orderform').submit(function() {
if($('#initials').val().length == 0){
alert('Please fill out your initials.');
}
});
as lewsid pointed out, you should also return false if you want to cancel the submit
$('#orderform').submit(function(e) {
e.preventDefault();
if(!$.trim((this + ' input').val()).length){
alert('Please fill all the fields');
return false;
}
return true;
});
but is better if you do this with pure JS not jQuery
function funnjsTrim(input) {
return input
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '')
.replace(/([\s]+)/g, '-');
}
validate_form = function(form, mssg){
mssg = form_errors[mssg] || 'Error: empty field';
var form_to = form.name,
elems = document.forms[form_to].getElementsByTagName("input");
for(var i = 0; i < elems.length + 1; i++) {
if(elems[i].type != 'submit') {
var string = funnjsTrim(elems[i].value);
if(!string.length) {
alert(mssg);
error = 'error';
return false
}
}
}
if(typeof error == "undefined"){
alert('Valid');
return true;
}
}
so in your html
<form onsubmit="return validate_form(this)">
in this line: if(elems[i].type != 'submit') add || elems[i].class != 'your input class' to add exceptions
I'd use e.preventDefault() instead of return false. Return false also prevents events from bubbling and can have unintended consequences if you don't understand this. Also nest that preventDefault within your if, no reason to stop submission if things are good.
$('#orderform').submit(function(e) {
if(!$.trim($(this).find('input[type="text"]').val()).length){
e.preventDefault();
alert('Please fill all the fields');
}
});

form still submitted after return false javascript

I'm having a little problem with a validation thing in javascript.
<form action="insert.php" id="form" name="form" method="post"
onSubmit="return validate()">
<pre>
Vul hier de/het E-mail adres(sen) in
<textarea name="email" rows="5" cols="50"></textarea><br>
Typ hier de E-mail
<textarea name="text" rows="5" cols="50"></textarea><br>
<input type="submit" name="Submit" value="Submit">
</pre>
</form>
As you can see here, I've got two textareas. In the upper one, you're supposed to enter one or multiple email addresses underneath eachother, and in the bottom textarea you're supposed to compose the email itself. Then, when you click on submit, it'll send the email to all those specified email addresses.
Now, I've made a validation for both textareas:
function explodeArray(emailID, delimiter) {
tempArray = new Array(1);
var Count = 0;
var tempString = new String(emailID);
while (tempString.indexOf(delimiter) > 0) {
tempArray[Count] = tempString.substr(0, tempString.indexOf(delimiter));
tempString = tempString.substr(
tempString.indexOf(delimiter) + 1,
tempString.length - tempString.indexOf(delimiter) + 1
);
Count = Count + 1
}
tempArray[Count] = tempString.replace("\r", "");
return tempArray;
}
function validate() {
var emailID = document.form.email;
var delimiter = "\n";
var emailArray = explodeArray(emailID.value, delimiter);
var textID = document.form.text;
var length = emailArray.length,
element = null;
for (var i = 0; i < length; i++) {
emailVar = emailArray[i];
if (emailVar == null) {
alert("Email-adres bestaat niet")
emailID.focus()
return false
}
if (emailVar == "") {
alert("Email-adres veld is leeg")
emailID.focus()
return false
}
if (checkEmail(emailVar) == false) {
emailVar.value = ""
alert("Ongeldig E-mail adres");
emailVar.focus()
return false
}
}
if ((textID.value == null) || (textID.value == "")) {
alert("E-mail textveld is leeg")
textID.focus()
return false
}
document.getElementById("form").submit();
return true
}
function checkEmail(hallo) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(hallo)) {
return true
}
return false
}
(I probably copied lots of irrelevant code as well, sorry for that, just copied the whole thing just in case...)
Now what does work is:
-it won't submit when both textareas are empty;
-it won't submit when the email addresses are valid but the bottom textarea is empty;
What doesn't work is:
-the form still submits when the email addresses are invalid, even when the bottom textarea is still empty.
I've been trying to figure out for hours what could possibly be wrong here, I googled and checked stackoverflow, but I really could not find anything. Could anybody tell me what I'm doing wrong here?
Thanks in advance.
You were using emailVar.focus(); which won't execute.
Here, fixed: Live Demo
if (checkEmail(emailVar) == false) {
alert("Ongeldig E-mail adres");
emailID.focus();
return false;
}

Categories

Resources