Javascript validation function not being executed - javascript

I'm having to dip my toe back in the EE and javascript world after many years. What am I doing wrong here... a simple form being submitted, with a JS block to validate during the onsubmit event of the submit button. The alert("Here") message box does not appear when I submit the form, and the form gets submitted successfully, i.e. HelloForm gets displayed, with blank values, so I'm led to believe that validate() is not being called. I've tried this in both the Eclipse internal web browser as well as Chrome and see the same thing both times. I'm assuming that I don't need to explicitly activate javascript in either browser, as it would be on by default.
<html>
<head>
<script>
function validate()
{
alert("Here");
var x = document.forms["inputForm"].["first_name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inputForm" action="HelloForm" method="GET" onsubmit="return validate()">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit The Form" />
</form>
</body>
</html>

In this line will throw a syntax error:
document.forms["inputForm"].["first_name"].value
^^^
The statement is wrong, should be without dot between braces:
document.forms["inputForm"]["first_name"].value
//or
document.forms.inputForm.first_name.value
Working with Objects

You can use Html5 Validations.
<form name="inputForm" action="HelloForm" method="GET" >
First Name: <input type="text" name="first_name" required />
<br />
Last Name: <input type="text" name="last_name" required />
<input type="submit" value="Submit The Form" />
</form>
Working Demo

Related

My html form validation is not working

I'm a beginner, and I need some help with my assignment. I can't work out what I've done wrong. The label and submit button appear in html, but when I click on the submit button it doesn't validate the form.
My assignment is to produce a form to enter your name. Onsubmit a function to validate the name is called that will validate that the name cannot be blank and must be more than 6 characters.
<html>
<head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm()">
<p><label>First name (required) <input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
</form>
<input type="submit" name="S1" value="Submit response" />
<script>
function validateForm(){
var firstName=document.getElementById("firstName");
if (firstName.value.length<6){
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
</script>
</body>
</head>
</html>
Place submit button inside of form tag
function validateForm() {
var firstName = document.getElementById("firstName");
if (firstName.value.length < 6) {
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
<html>
<head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm()">
<p><label>First name (required)<input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
<input type="submit" name="S1" value="Submit response" />
</form>
</body>
</head>
</html>
The problem with your code is that you try to return a result to an event. Events do not accept any response. So try this;
<html>
<body>
<form name="myForm" autocomplete="on" onsubmit="validateForm()">
<p>
<label>First name (required)</label>
<input type="text" id="firstName" autofocus="autofocus" />
</p>
<input type="submit" name="S1" value="Submit response" />
</form>
<script>
function validateForm(){
var firstName=document.getElementById("firstName");
if (firstName.value.length<6){
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
document.getElementsByTagName("form")[0].submit()
}
</script>
</body>
</html>
Besides that, you put your body in your head, this can cause trouble with some browsers.
Your submit button is outside of form tag, that's why the onsubmit method is not gettting called.
Problem was in your code. Remember you have to put submit button under <form></form> tag. And always put JS code in <head></head> section.
Find below code and try hope this will work for you.
<html>
<head>
<script>
function validateForm() {
var firstName = document.getElementById("firstName");
if (firstName.value.length < 6) {
alert("Please enter your first name (6 characters or more)");
firstName.focus();
return false;
}
alert("Thank you for your submission");
return true;
}
</script>
</head>
<body>
<form name="myForm" autocomplete="on" onsubmit="return validateForm();">
<p><label>First name (required) <input type="text" id="firstName"
autofocus="autofocus" /> </label></p>
<input type="submit" name="S1" value="Submit response" />
</form>
</body>
</html>

AngularJS - Form Custom Validation - Check if at least one input is empty

Given a simple html form like this:
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
... submit input and all the other code...
</form>
I need your help to know how to check on validation time, if at least one of the inputs is empty. The desired validation is the following. The user must complete at least one a preference.
Using jQuery this:
if ( $("input").val() == "" ) {
Works ok, but would like to figure out how to do the same thing using angular.
Thanks so much in advance,
Guillermo
So the idea is to disable the submit button if all inputs are blank. You can do like this
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference1" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference2" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference3" />
<button type="submit" ng-disabled="!(!!shipment.userPreference1 || !!shipment.userPreference2 || !!shipment.userPreference3)">Submit</button>
</form>
!!str is to force to convert str to a boolean value. And both !!null and !!"" are evaluated to be false.
Demo
You can set the "required" in the input elements and style / code how you want to handle with $valid of a form. Check out http://dailyjs.com/2013/06/06/angularjs-7/
My solution was the following:
$scope.requiredInputsGroup = function () {
var isRequired = true;
if (!$scope.shipment) {
return true;
}
angular.forEach(["userPreference1", "userPreference2", "userPreference3"], function (input) {
if ($scope.shipment[input]) {
isRequired = false;
return false;
}
});
return isRequired;
};
You apply that method to a data-ng-required in each of the inputs...
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference1" ng-required="requiredInputsGroup()" />
<input name="userPreference2" type="text" ng-model="shipment.userPreference2" ng-required="requiredInputsGroup()" />
<input name="userPreference3" type="text" ng-model="shipment.userPreference3" ng-required="requiredInputsGroup()" />
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
And the last bit I applied was to make the button disabled with a simple myForm.$invalid

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

checking text field value length

I am trying to see if the text field length is at least a certain length. here is my code:
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="button" name="submit" value="submit" />
</form>
<script>
function validate() {
document.write("good");
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>
when I click submit, nothing happens.
Change your submit button to type="submit". The form is never getting submitted so the validate function isn't being called.
The input type needs to be "submit"
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="submit" name="submit" value="submit" /> <!--INPUT TYPE MUST BE SUBMIT -->
</form>
<script>
function validate() {
document.write("good");
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>
You probably want greater than or equal to (>=), instead of not equal to (!=) if you want "at least a certain length"
Your button should be
<input type="submit" name="submit" value="submit" />
otherwise the onsubmit event will not occur. Also, use console.log() for debugging, rather than document.write().
DEMO
There's a few issues that you have. 1) You need to make your input a submit button and 2) you need to remove your document.write() statement. Change your code to the following (or see this jsFiddle):
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
<script>
function validate() {
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>​​​​
You were pretty close, but you could use some clean-up on that code (Note: I did not provide any).
You should also add a maxlength attribute to your text input, it'll help the user.
<form name="form2" id="form2" onsubmit="return validate();">
<input type="text" name="t" id="t" maxlength="4"/>
<input type="submit" name="submit" value="submit"/>
</form>
<script type="text/javascript">
function validate()
{
if ( document.getElementById("t").value.length != 4 )
{
alert( "Invalid length, must be 4 characters" );
return false;
}
return true;
}
</script>
I've spotted various errors:
don't use document.write(), it will overwrite the currently open document
form2 is no property of document. You may use document.forms.form2, but document.getElementById("t") is simpler here
Your expression doesn't check for "at least 4", it checks for "exactly 4".
Your button won't submit anything. Change it to <button type="submit"> or <input type="submit" />
you could specify a pattern=".{4}" for the input or give it a required attribute
you can try this function
var a = txtTelNo1.value;
if (a.length != 10) {
alert('Phone number should be 10 characters');
return false;
}

Change value of input and submit form in JavaScript

I'm currently working on a basic form. When you hit the submit button, it should first change the value of a field, and then submit the form as usual. It all looks a bit like this:
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="DoSubmit()" />
</form>
And this is how far I've come with the JavaScript code. It changes "myinput"'s value to 1, but it does not submit the form.
function DoSubmit(){
document.myform.myinput.value = '1';
document.getElementById("myform").submit();
}
You could do something like this instead:
<form name="myform" action="action.php" onsubmit="DoSubmit();">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" />
</form>
And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:
function DoSubmit(){
document.myform.myinput.value = '1';
return true;
}
I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.
document.getElementById("myform").submit();
This won't work as your form tag doesn't have an id.
Change it like this and it should work:
<form name="myform" id="myform" action="action.php">
Here is simple code. You must set an id for your input. Here call it 'myInput':
var myform = document.getElementById('myform');
myform.onsubmit = function(){
document.getElementById('myInput').value = '1';
myform.submit();
};
No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.
Otherwise change the input type to a button and then define an onclick event for that button.
You're trying to access an element based on the name attribute which works for postbacks to the server, but JavaScript responds to the id attribute. Add an id with the same value as name and all should work fine.
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" id="myinput" value="0" />
<input type="text" name="message" id="message" value="" />
<input type="submit" name="submit" id="submit" onclick="DoSubmit()" />
</form>
function DoSubmit(){
document.getElementById("myinput").value = '1';
return true;
}
My problem turned out to be that I was assigning as document.getElementById("myinput").Value = '1';
Notice the capital V in Value? Once I changed it to small case, i.e., value, the data started posting. Odd as it was not giving any JavaScript errors either.
I have done this and it works for me.
At first you must add a script such as my SetHolderParent() and call in the html code like below.
function SetHolderParent(value) {
alert(value);
}
<input type="submit" value="Submit" onclick="SetHolderParent(222);" />
You can use the onchange event:
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="DoSubmit()" />
</form>
This might help you.
Your HTML
<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>
Your Script
<script>
function save(){
$('#myinput').val('1');
$('#form').submit();
}
</script>

Categories

Resources