Reputation: 3490
In JavaScript, what is the meaning of the identifiers document.forms
and the .value
field?
I have trouble understanding the use of the below syntax example.
var x = document.forms["myForm"]["email"].value
Upvotes: 23
Views: 103030
Reputation: 14155
document.forms
returns a collection of all forms in an actual document
. To access all forms in iframes, frames and windows from actual document
you have to switch to correct document
from them.
You have 3 possible ways to access elements:
function setEmail()
{
document.forms['myForm']['email'].value = '[email protected]';
}
<form name="myForm">
<input name="email"/>
</form>
<button onclick="setEmail()">Set email Adresse</button>
function setEmail()
{
document.forms.myForm.email.value = '[email protected]';
}
<form name="myForm">
<input name="email"/>
</form>
<button onclick="setEmail()">Set email Adresse</button>
my-form
.function setEmail()
{
document.forms['my-form'].email.value = '[email protected]';
}
<form name="my-form">
<input name="email"/>
</form>
<button onclick="setEmail()">Set email Adresse</button>
Upvotes: 0
Reputation: 63512
document.forms["myForm"]["email"].value
that will get the value
of the "email" element within the "myForm" <form>
<form id="myForm" name="myForm">
<input id="email" name="email" value="[email protected]" />
</form>
so x
will equal "[email protected]"
document.forms
will return a collection of all of the forms within a particular page. writing document.forms["myForm"]
will return the form with the name "myForm" from that collection
Upvotes: 32
Reputation: 13
this code shows how you can use document.forms in an example with validation.
``
function validation(inputs){
if (inputs==""|| inputs=="null"){
alert("Enter Valid Number");
return false;
}
if (isNaN(inputs)){
alert("Enter Valid Number");
return false;
}
return true;
}
function triNum(num){
var triangle=0;
for(i=1 ;i <= num; i++){
triangle += i;
}
return triangle;
}
function squareNum(num){
var square = num * num;
return square;
}
function findNums(){
//var num = document.getElementById('number1').value;
var num= document.forms["MagicNum"]["FirstNum"].value;
if (validation(num)){
document.forms["MagicNum"]["tri"].value=triNum(num);
document.forms["MagicNum"]["square"].value=squareNum(num);
}
}
</script>
Upvotes: 0
Reputation: 2872
documents.forms
is an object containing all of the forms for that HTML document. With this code, you are referencing the elements by their name
attributes (not id
). So this would provide a string containing the value
for the form element with the name
"email" within the form
with the name
"myForm".
Example:
<form name="contact-form">
Email: <input type="text" name="email" />
</form>
Executing the following JavaScript code at anytime when a value for the email field is desired would provide the value.
var contact_email = document.forms["contact-form"]["email"].value;
The contact_email
variable would then contain the value entered into the input
field.
Upvotes: 15