Validating form with JavaScript that is in a separate header - javascript

I have a phpwebsite that includes a header and footer on every page. On one of my pages I have a form called "orderForm" and onSubmit is equal to "return(validate())". In my header (which gets included on that page) I have a function called function validate().
My problem is trying to validate the order form from my header file. I know it partly works when my validate function consists of:
alert("Test");
return false;
As I get an alert when I submit the form.
But when I try something like:
if (document.orderForm.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false;
}
It doesn't validate it, despite orderForm and postcode being the correct names of the form fields. Is this because I am including the header file while having the form in a different file?
Cheers

If you want to test by name you can do this, assuming no other onload code in the page. The main point is to wait with assigning the validation until after the form exists on the page.
window.onload=function() {
document.orderForm.onsubmit=function() {
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false; //cancel submission
}
return true; // allow submission
}
}
To use preventDefault with my code you can try
window.onload=function() {
document.orderForm.onsubmit=function(e) {
var event=e?e:window.event;
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
event.preventDefault();
}
}
}

You need to add the «name» attribute in the form and the input tag.
In this scenario you must ensure that the fields are loaded on the page with window.onload.
You can assign a submit event to your form. In this context you can run your script to validate your field.
You must prevent the default action of the form with preventDefault().
This is the solution:
window.onload = function() {
var form = document.getElementById("orderForm");
form.addEventListener("submit", function(e) {
if (document.orderForm.postcode.value.length < 1) {
e.preventDefault(); // This prevents the default action to submit the form to the server.
alert("Postcode field cannot be empty.");
}
});
};
<form id="orderForm" name="orderForm">
<input id="postcode" name="postcode" type="text" />
</form>

Related

javascript form validate not preventing css .submitted from actioning

I have a form with a class="myfrm" and contains a fieldset made up of input fields. After the fieldset tag I have a div tag and assigned class="ack-msg" which contains an acknowledgement message.
In CSS I have
.myfrm.submitted fieldset {
display: none;
}
.myfrm.submitted .ack-msg {
display: block;
}
When the form is submitted the fieldset is replaced by the acknowledgement.
This works fine when the form is completed as expected but when the form validation fails a message is displayed but the acknowldgement class="ack-msg" kicks in and replaces the fieldset as if it passed.
The validation is carried out by a javascript function called by the onSubmit on the form. The javascript is listed below and to keep things simple I have a shorted version of the script that only passes the validation if the provided parameter value = 24.
function validateForm(v)
{
if(v.value != '24')
{
alert("Oops! Try agan!");
return false;
} else {
return true;
}
}
Also, if I inspect the page after validation fails and acknowledgement gets diaplayed form declaration has been updated from
class="my-frm"
to
class="my-frm submitted"
If I should be listing other details please let me know.
Any help welcome on this.
Thanks in advance,
Ned
Try to remove the submitted class using javascript, right after the alert.
If you have jQuery:
function validateForm(v)
{
if(v.value != '24')
{
alert("Oops! Try agan!");
$.(".my-frm").removeClass("submitted");
return false;
} else {
return true;
}
}

How do I use JavaScript or jQuery to submit a form by using the Enter key, when not the default form action

I have a page that has three "forms" that are apparent to the user. Under the hood, the page has only ONE form, using html:form as the JSP object controlling the entire page. When a user clicks on the image that is used for the individual submit buttons, it triggers an onClick() function, which bypasses the form's action and executes another action instead.
<html:form action="foo.do">
<html:text property="name" styleClass="input" />
<img src="bar.jpg" onClick="myFunction();" />
</html:form>
<script>
function myFunction(){
document.forms[0].action = "realPage.do";
document.forms[0].submit();
}
</script>
This script works, sending the user not to the default "foo.do" but rather to the destination of the function (realPage.do)
However, the problem is my users want to be able to submit the form just by hitting 'Enter' on their keyboard when in any one of the fields, of the particular "form" they want to submit. How can I use JavaScript or jQuery to recognize which "form" and, hence, which input field the user is in, detect the press of the 'Enter' key and submit using the same function as the button?
This should solve your problem
$(document).ready(function(){
$("input").keyup(function (e) {
if (e.keyCode == 13) {
// Submit your form here
}
});
});
I would probably arrest the form submit and detect which element has focus. Something like this, where each pseudo-form has an identified wrapper element:
$(function() { // document.ready
$('#myform').submit(function(event) {
event.preventDefault();
if ( $('#pseudoForm1 input').is(':focus') ) { ... }
else if ( $('#pseudoForm2 input').is(':focus') ) { ... }
else if ( $('#pseudoForm3 input').is(':focus') ) { ... }
});
});
You could start with this -
$('input').keypress(function(e) {
if(13 == e.keyCode) {
var closestForm = $(this).closest('form');
$(closestForm).submit();
}
});

how to add event handler for input text box

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.
$(document).ready(function() {
$('#submitIDSearch').bind('click', validateIDSearch);
$('#submitNameSearch').bind('click', validateNameSearch);
$('#searchLastName').bind('click', validateNameSearch);
$('#searchFirstName').bind('click', validateNameSearch);
$('#searchID').bind('click', validateIDSearch);
});
var validateNameSearch = function(event) {
var btnSrchLastName = getRef('searchLastName');
if (null != btnSrchLastName) {
var len = btnSrchLastName.value.length;
if (0 == len) {
alert('Last Name is a required field, please input Last Name.');
$('#searchLastName').focus();
return false;
}
}
return true;
}
var validateIDSearch = function(event) {
var btnSrchID = getRef('searchID');
if (null != btnSrchID) {
var len = btnSrchID.value.length;
if (0 == len) {
alert('ID is a required field, please input ID.');
$('#searchID').focus();
return false;
}
}
return true;
}
And I have the following HTML code:
<form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
<label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID"/>
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
<input id="submitNameSearch" type="submit" value="Search Name"/>
<hr />
</form>
The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.
I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.
May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?
Thanks a lot!
In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/
$(document).ready(function() {
$('#submitNameSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchLastName'), 'Last name field is required.')) {
$('#infoForm').submit();
}
});
$('#submitIDSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchID'), 'ID field is required.')) {
$('#infoForm').submit();
}
});
});
function validate(input, errorMsg) {
if (input.val() == null || input.val().length == 0) {
alert(errorMsg);
return false;
}
return true;
}
Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.
[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/
You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit
$('#infoForm').submit(function (event){
if (!validateIDSearch() && !validateNameSearch()){
event.preventDefault(); // Prevent the submit event, since didn't validate
}
// Will continue to the dafault action of the form (submit it)
});
You just need to set what button the user has selected and do validation based on that during form submit.
searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch
$(function () {
var validateFx = null; //none selected;
$('#submitNameSearch, #searchLastName, #searchFirstName')
.bind('click', function () {
validateFx = validateIDSearch;
});
$('#searchIDSearch, #searchRUID')
.bind('click', function () {
validateFx = validateNameSearch;
});
$('#infoForm').submit(function (event){
event.preventDefault();
if (validateFx != null && validateFx ()) {
$(this).submit();
}
});
});

Jquery one issue

My mark up
<form action="blah/foo" method="POST" id="frm1">
<input type="hidden" id="v" />
</form>
......
......
<!--after some code-->
<button id="btn1">test</button>
<input type="text" id="somevalue" />
My purpose is when i click the button btn1,Grab the value of somevalue and give it to the hidden value v and submit the form ,the form needs to submit (ONLY ONCE) so i used the jquery one method and thats working fine
Second thing is if somevalue is empty i dont want to submit
THE PROBLEM scenario
<script>
$('#btn1').one('click',function(){
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
$('#frm1').submit();
});
</script>
IF user first makes an empty input and try to submit the error msg will show..but after that even with a valid input the click event wont trigger(I know thats because of the one function)
Im looking for some alternative that the form will submit only once
var form_sent = false;
$('#btn1').click(function(){
if(form_sent == true){ return; }
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
form_sent = true;
$('#frm1').submit();
});
Instead of using 'one' so that the your handler is called only once, declare your handler as a named function and use jQuery's bind / unbind to remove the click handler if (and only if) the field has a valid value when the form is submitted. Otherwise keep listening on the click event. As such:
function onFormSubmitted (e) {
if($("#somevalue").val === "") { // If the field's value is invalid...
$('p#msg').html('Empty value'); // ... then show error message...
return; // ...and do nothing else - just keep on listening
}
// Ok, we have valid input so...
$('#btn1').unbind("click", onFormSubmitted); // ...stop listening...
$("#frm1").submit(); // ...and submit the form
}
// Start listening for the click event
$('#btn1').bind("click", onFormSubmitted);
Or, if you still want to use 'one' you can tweak the previous example, as such:
function onFormSubmitted (e) {
if($("#somevalue").val === "") { // If the field's value is invalid...
$('p#msg').html('Empty value'); // ... then show error message...
$('#btn1').one("click", onFormSubmitted); // ...re-attach one-time listener...
return; // ...and wait
}
// Ok, we have valid input so don't re-attach one-time listener...
$("#frm1").submit(); // ...just submit the form
}
// Add one-time listener for the click event
$('#btn1').one("click", onFormSubmitted);
try:
$('#btn1').one('click',function(){
callFunc();
});
function callFunc(){
if($('#somevalue').val() == ""){
$('p#msg').html('Empty value');
$('#btn1').one('click',function(){ callFunc(); });
return false;
}
$('#frm1').submit();
}
First off why not have your input in the form? Is there a specific reason to do it this way?
Also to do this in straight javascript rather than using jquery I would be doing something as follows:
<form action="blah/foo" method="POST" id="frm1" onsubmit="return validateForm();">
The validateForm just checks to see if the input is empty, if it is then it returns false, otherwise it returns true. Returning false to onsubmit will stop the form submitting.
Try bind event,
$('#btn1').bind('click',function(){
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
$('#frm1').submit();
});​

Preventing form submission when Enter is pressed [duplicate]

This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 6 years ago.
I have a form with a disabled submit button. Even though the user can't press this button, he can still hit Enter to submit the form. How do I prevent that?
If you want to completely disable the form submit (However I am wondering why the whole <form> element is then there in first place), then you need to let its submit event handler return false.
So, basically:
<form onsubmit="return false;">
You can add it using Javascript/DOM manipulation during onload as previous answerers pointed out.
If you only want to disable the Enter key to submit the form, then you need to let its keydown event handler return false when the key of the event matches Enter (this one is crossbrowser compatible and covers both the default Enter as well as the numpad Enter!).
<form onkeypress="return event.key != 'Enter';">
This however also disables the Enter key in any <textarea> elements in the form. If you have any of them and you would like to keep them functioning, then you'll need to remove the onkeydown from the <form> and copy it over all <input> and <select> elements. jQuery can be helpful in this:
$('input, select').keydown(event => event.key != 'Enter');
See also:
Prevent users from submitting a form by hitting Enter
Assuming HTML:
<form id="myForm"> ...
You can do this with JavaScript:
document.getElementById("myForm").onsubmit = function () {
return false;
};
Instead of implementing two methods of disabling form submitting, add an event handler to form's onsubmit which will check the disabled property of the button:
myForm.onsubmit = function () {
if (myForm.mySubmit.disabled)
return false;
}
Say you had a form with an id of "myForm":
<form id="myForm" action="some_file" method="post">
...
</form>
<script type="text/javascript">
document.getElementById( "myForm").onsubmit = function() {
return false;
};
//or with jQuery: $( '#myForm' ).submit( function() { return false; } );
</script>
If you don't want to edit the onsubmit event of the form, you can do it like this.
Add this to the text input:
onKeyPress="return noEnter(event)"
And this to the header:
function noEnter(e)
{
var key;
// firefox vs. ie
(window.event) ? key = window.event.keyCode : key = e.which;
(key == 13) ? return false : return true;
}
easier to pull of with jquery.
jQuery Solution:
$(document).ready(function(){
$('form[name="form"]').keypress( function(evt){
return !(evt.which==13 && evt.target.type!='textarea');
});
$('form[name="form"] input[type="submit"]').attr('tabIndex',-1); // this prevents submit also by spacebar (keyCode==32)
//$('form[name="form"]').submit(function(){ alert('test'); return false; }); // test
});
document.getElementById("myForm").onsubmit = function () {
return false;
};
These codes doesn't work on Chrome and Safari. It submits form to action url.
But <form onsubmit="return false;"> is useful.

Categories

Resources