I have a code javascript:
<form onsubmit="return false;" action="">
<input type="radio" name="type" id="type0" value="0" onclick="toggleSet(this)" checked />type 0
<input type="radio" name="type" id="type1" value="1" onclick="toggleSet(this)" />Type 1
</form>
<script>
function toggleSet() {
for(var i=0; i<document.form.type.length; i++) {
if(document.form.type[i].checked) {
var type = document.form.type[i].value;
}
}
alert(type);
}
</script>
ouput error: document.form is undefined, how to fix it ?
asked Jan 17, 2012 at 9:58
0
The form property of document
does not exist. You’re probably confused with the document.forms
HTML collection:
document.forms[0]; //First <form> element
document.forms['name_of_form']; //Points to <form name="name_of_form">
Fixed code:
function toggleSet() {
var form = document.forms[0];
var type; //Declare variable here, to prevent a ReferenceError at the end
for(var i=0; i<form.type.length; i++) {
if(form.type[i].checked) {
type = form.type[i].value;
break; // After finding an occurrence, break the loop:
// You expect only one value
}
}
alert(type);
}
answered Jan 17, 2012 at 10:00
Rob WRob W
340k83 gold badges789 silver badges677 bronze badges
0
Just define the name parameter in the form tag like < form name=»form1″ …> and call it through array value as below.
e.g var type = document.form1.type[i].value;
answered Jan 21, 2013 at 13:15
KingkKingk
1,00511 silver badges13 bronze badges
There is no property document.form
.
document
has a property forms
which is an array of the forms the document contains. You access the desired form this way:
document.forms[0] // first form
document.forms['theForm'] // form with name="theForm"
answered Jan 17, 2012 at 10:02
Didier GhysDidier Ghys
30.3k9 gold badges74 silver badges81 bronze badges
document.form
is not standard as far as I know. document.forms
(note the ‘s’) is. Documents can have multiple forms.
answered Jan 17, 2012 at 10:08
sirlarksirlark
2,1771 gold badge18 silver badges28 bronze badges
I am using the following code:
var frontPic = e.target.files[0]
var frontPicName = frontPic.name
var salonId=$("#salonId").val()
upload = new Upload(frontPicName, salonId)
upload.resize(frontPic)
To call the following code
function Upload(filename, salonId){
var form = new FormData()
form.append("filename", filename)
form.append("salonId", salonId)
};
Upload.prototype.resize = function(file){
$.canvasResize(file,
{
width: 400,
height: 0,
crop: false,
quality: 100,
callback: function (data)
{
alert(data)
// Add file data
this.form.append("file", $.canvasResize('dataURLtoBlob', data));
$('body').css("background", "url("+data+")")
}
});
}
My alert(data) seems to work fine, so the actual resizing action looks fine.
However I am getting the error this.form is undefined
for the line this.form.append("file", $.canvasResize('dataURLtoBlob', data));
What would be the correct syntax?
Answer by Alena Bryan
The ng-messages and ng-model attribute directives do not exist in Angular 2+. I would recommend reading into Angular Forms, ReactiveForms, and Template Syntax.,Angular Form Validation template Driven Model,
Outdated Answers: results from flagging exercise and next steps
onSubmit(form : NgForm) {
console.log(form);
}
<form #form="ngForm" (ngSubmit)="onSubmit(form)"
[ngClass]="{'was-validated': form.invalid && (form.dirty || form.touched)}">
<div class="" ngModelGroup="User">
<h2 class="text-center">Registration page</h2>
<br />
<div class="form-group">
<input type="text" class="form-control" placeholder="First Name" name="firstname" required
ngModel #firstname="ngModel">
<span class="help-bpx" *ngIf="firstname.touched && !firstname.valid ">Please enter the
firstname</span>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Last Name" name="lastname" required ngModel
#lastname="ngModel">
<span class="help-bpx" *ngIf="lastname.touched && !lastname.valid ">Please enter the
lastname</span>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" name="email" email
required ngModel #email="ngModel">
<span class="help-bpx" *ngIf="email.touched && !email.valid ">Please enter the Email
Value</span>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" required ngModel name="file" #file="ngModel">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<br />
<div class="align-center">
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Register</button>
</div>
</div>
</form>
Answer by Ayden Middleton
You want something like this:
f.email.errors?.required
Or even:
f.email?.errors?.required
Answer by Remy Nielsen
Answer by Eden McKinney
Answer by Lennox Solis
Template-Driven Forms,
Template-Driven Forms
,How to submit and reset a form in the template-driven approach.
@Component({
selector: 'template-form',
template: `
<form novalidate>
<fieldset>
<div class="form-group">
<label>First Name</label>
<input type="text"
class="form-control">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text"
class="form-control">
</div>
</fieldset>
<div class="form-group">
<label>Email</label>
<input type="email"
class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password"
class="form-control">
</div>
<div class="form-group">
<label>Language</label>
<select class="form-control">
<option value="">Please select a language</option>
<option *ngFor="let lang of langs"
[value]="lang">
{{lang}}
</option>
</select>
</div>
</form>
`
})
class TemplateFormComponent implements OnInit {
langs:string[] = [
'English',
'French',
'German',
];
ngOnInit() {
}
}
Answer by Hayden Lucas
How to add validation error messages to the form to give hints to the user about why the field isn’t passing a validation check.,
How to add validation error messages to the form to give hints to the user about why the field isn’t passing a validation check.
,Finally, we can add validation error messages so the user knows how to make the form valid again.
import { FormGroup, FormControl, Validators } from '@angular/forms';
.
.
.
class ModelFormComponent implements OnInit {
myform: FormGroup;
ngOnInit() {
myform = new FormGroup({
name: new FormGroup({
firstName: new FormControl('', Validators.required), (1)
lastName: new FormControl('', Validators.required),
}),
email: new FormControl('', [ (2)
Validators.required,
Validators.pattern("[^ @]*@[^ @]*") (3)
]),
password: new FormControl('', [
Validators.minLength(8), (4)
Validators.required
]),
language: new FormControl() (5)
});
}
}
Answer by Alberto Curtis
More info can be found in the Angular docs under Form Validation: Built-in Validators.,In a reactive form, you can always access any form control through the
get method on its parent group, but sometimes it’s useful to define
getters as shorthands for the template.,A getter will allow you to access a form field directly, avoiding the redundant use of myForm.controls[‘fieldNameGoesHere’]. with ngIf in the examples above.
You should use it like this:
<span class="help-block form-error text-danger small"
*ngIf="myForm.controls['company_address2'].errors?.required &&
myForm.controls['company_address2'].touched">Company Address 2 is Required </span>
As an example, For company_address2
add the following after your ngOnInit()
method:
get company_address2() { return this.myForm.get( 'company_address2' ); }
This will give your component HTML direct access to the company_address2
, give this a try instead:
<textarea class="form-control" placeholder="Address" rows="2" [readonly]="disabled" id="companyaddress2"
formControlName="company_address2">
</textarea>
<span class="help-block form-error text-danger small"
*ngIf="company_address2.hasError('required')">
Company Address 2 is Required.
</span>
Answer by Zendaya Lowery
Building easy-to-use forms requires design and user experience skills, as well as a framework with support for two-way data binding, change tracking, validation, and error handling such as Angular.
,
Angular Forms Fundamentals
,
Real time validation: It means validating as you type. These are super handy and are the default for Angular Validators.
The following is an example which shows a FormControl
for the ‘name’ property which should not be empty.
this.username = new FormControl('agustin', Validators.required);
<ion-input type="text" formControlName="username"></ion-input>
FormGroup
: it tracks the value and validity state of a FormBuilder
instance group. It aggregates the values of each child FormControl
into one object, using the name of each form control as the key. It calculates its status by reducing the statuses of its children. If one of the controls inside a group is invalid, the entire group becomes invalid.
this.user_data = new FormGroup({
username: new FormControl('agustin', Validators.required),
city: new FormControl('Montevideo', Validators.required)
});
FormArray
: is a variation of FormGroup
. The main difference is that its data gets serialized as an array, as opposed to being serialized as an object in case of FormGroup. This might be especially useful when you don’t know how many controls will be present within the group, like in dynamic forms.
this.user_data = new FormArray({
new FormControl('agustin', Validators.required),
new FormControl('Montevideo', Validators.required)
});
FormBuilder
: is a helper class that creates FormGroup
, FormControl
and FormArray
instances for us. It basically reduces the repetition and clutter by handling details of form control creation for you.
this.validations_form = this.formBuilder.group({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
]))
});
All of them should be imported from the @angular/forms
module.
import { Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';
Answer by Bellamy Hale
«cannot read property of ‘valid’ of undefined «,Angular8 cannot read property of ‘valid’ of undefined for the form ,I am using register form for adding employee.. and using validation for this. but for some reason, it’s giving me an error
ts file
export class NewEmployeeComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder,private service:NewEmployeeService) {
this.getJobs()
}
ngOnInit() {
this.registerForm = this.formBuilder.group({
jobid: ['', Validators.required],
firstName: ['', Validators.required],
date: ['', Validators.required],
lastName: ['', Validators.required],
}, {
// validator: MustMatch('password', 'confirmPassword')
});
}
get f() { return this.registerForm.controls; }
onSubmit(event:any) {
console.log(event)
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
Swal.fire("Successfull","New employee registration is successfull","success")
}
public jobList:any=[]
public getJobs()
{
this.service.getJobList().subscribe(data=>{
this.jobList=data;
})
}
}
Answer by Kailey Donovan
Previously, you were returning undefined and that is what was causing issues.,Not sure what you mean. required doesn’t have anything to do with this issue. This is about returning a boolean value from your validator.,@BobChao87, I see. This seems to be an unexpected side effect of an unintended use. Internally, the $setValidity treats values as follows:
function (modelValue, viewValue) {
var check = true;
if (modelValue) {
...
}
return check;
}
Issue
I have two routes inside my application, if i want to access the second one i got this error:
UndefinedError: 'register_form' is undefined
The register_form is for the first route, here is the first route:
@abonent_route.route('/')
@abonent_route.route('/', methods=['GET', 'POST'])
def index():
register_form = RegistrationForm()
return render_template('index.html', register_form=register_form)
This is the second route:
@client_route.route('/client/')
@client_route.route('/client/', methods=['GET', 'POST'])
def index():
form_login = ClientLogin()
return render_template('index.html', form_login=form_login)
Also I’ve initialized the routes inside my create_app function as following:
from .abonent import abonent_route
app.register_blueprint(abonent_route)
from .client import client_route
app.register_blueprint(client_route)
Now the problem is if i replaced the client route step up so to be above the abonent route and if i open abonent route, i got the same error but a little bit different:
UndefinedError: 'form_login' is undefined
This time, the form_login is undefined, also if i again moved the abonent back again to it place and if i want to visit the client route, i got the first error which is register_form undefined .
Please any help would be appreciated .
Edit: Add some codes
Client main route
:
@client_route.route('/client/', methods=['GET', 'POST'])
def index():
form_login = ClientLogin()
if request.method == 'GET' and request.args.get('next'):
session['next'] = request.args.get('next')
if form_login.validate_on_submit():
user = Client.query.filter_by(
tele = form_login.telephone.data
).first()
if user:
if check_password_hash(user.password, form_login.password.data):
session['client_logged_in'] = user.name
session['client_family'] = user.family
session['client_image'] = user.image
session['client_phone'] = user.tele
if 'next' in session:
next = session.get('next')
session.pop('next')
return redirect(next)
else:
flash('Привет, {}'.format(user.name), 'success')
return redirect(url_for('client.profile'))
else:
flash('Неверные учетные данные.', 'danger')
return redirect(url_for('client.index'))
else:
flash('Неверные учетные данные.', 'danger')
return redirect(url_for('client.index'))
return render_template('index.html', form_login=form_login)
Abonent main route
:
@abonent_route.route('/', methods=['GET', 'POST'])
def index():
register_form = RegistrationForm()
if request.method == 'POST':
if register_form.is_submitted():
if not register_form.terms_agree.data:
flash('Вы должны согласиться с нашим договором и со всеми его пунктами.', 'danger')
return redirect(url_for("abonent.index"))
if register_form.master_salon.data or register_form.master_cto.data or register_form.master_company.data == True:
user = User()
user.name = register_form.name.data
user.family = register_form.family.data
user.bio = register_form.biography.data
if User.query.filter_by(tele=register_form.telephone.data).first():
flash('Этот номер: {} уже использован.'.format(register_form.telephone.data), "warning")
return redirect(url_for('abonent.index'))
else:
user.tele = register_form.telephone.data
user.set_password(register_form.password.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('abonent.confirm', phone=phone))
return render_template('index.html', register_form=register_form)
Here is a link to where full error shows, this one is raises if the client route is under abonent route in __init__.py
file:
Click to open
Another thing that i forgot to mention is, if tried to open for example /client/registration
, it opens without any error, the error raises if i wanted to access /client
which is the index page for client
Solution
Seems like there is a couple of redundant block info in your code.
@abonent_route.route('/')
@abonent_route.route('/', methods=['GET', 'POST'])
You don’t need twice to declare this route. The bottom line will be enough.
Also I’ve initialized the routes inside my create_app function as
following:
It is not declaring route. It’s a blueprint. It’s like big part of your project.
I can have many routes in your blueprint.
You don’t need declare one blueprint for one route.
For a more detailed answer, please provide a more detailed source code of your application.
Take a look:
http://exploreflask.com/en/latest/blueprints.html and
DO docs
Answered By – Vladimir Yakovenko
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
11 Years Ago
Hi,
I’m getting this.form undefined
error message when I submit it. Do I miss anything?
Thanks
function signup_scramble(uid)
{
alert(uid.value);
return false;
}
<form action="do_signup" method="post" onsubmit="return signup_scramble(this.form.text_username)">
Username : <input type="text" name="text_username" value="" /><br />
Password : <input type="password" name="text_password" value="" /><br />
<input type="submit" name="submit_button" value="Signup" />
</form>
Edited
11 Years Ago
by veledrom because:
.
Recommended Answers
Change it to the following (the code is not tested)
function signup_scramble(element) { alert(element.value); return false; } <form action="do_signup" method="post" onsubmit="return signup_scramble(document.getElementById('text_username'))"> Username : <input type="text" id="text_username" value="" /><br /> Password : <input type="password" id="text_password" value="" /><br /> <input type="submit" id="submit_button" value="Signup" /> </form>
You can …
Jump to Post
All 3 Replies
stbuchok
11 Years Ago
Change it to the following (the code is not tested)
function signup_scramble(element)
{
alert(element.value);
return false;
}
<form action="do_signup" method="post" onsubmit="return signup_scramble(document.getElementById('text_username'))">
Username : <input type="text" id="text_username" value="" /><br />
Password : <input type="password" id="text_password" value="" /><br />
<input type="submit" id="submit_button" value="Signup" />
</form>
You can use getElementByName, howerver this will return an array as the name attribute does not need to be unique. I would suggest using the id attribute unless you really need to use name.
Edited
11 Years Ago
by stbuchok because:
Original post was for a diferent post.
fobos
19
Posting Whiz in Training
11 Years Ago
You could also try this
<script type="text/javscript">
function signup(){
var username = document.getElementById("text_username").value;
var password = document.getElementById("text_password").value;
alert(username + " " + password);
return false;
}
</script>
<form action="do_signup" method="post" onsubmit="signup()">
Username : <input type="text" id="text_username" /><br />
Password : <input type="password" id="text_password" /><br />
<input type="submit" name="submit_button" value="Signup" />
</form>
Or if your form and inputs had a name:
<script type="text/javascript">
function greeting(){
alert("Welcome " + document.forms["frm1"]["fname"].value + "!")
}
</script>
</head>
<body>
What is your name?<br />
<form name="frm1" action="submit.htm" onsubmit="greeting()">
<input type="text" name="fname" />
<input type="submit" value="Submit" />
</form>
Hope this helps
11 Years Ago
Thanks guys. You gave me hint.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.