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 ?
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);
}
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;
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"
document.form is not standard as far as I know. document.forms (note the 's') is. Documents can have multiple forms.
Related
I'm retrieving forms from my page, using:
DOMS = {
form: '[data-form]',
}
document.querySelectorAll(DOMS.fom).forEach(function (form, index) {
arr[index] = {};
arr[index]['DOMRef'] = form;
}
and adding them to an object. I add an event:
addEventListener('submit', function (event) {
send(event, form);
});
Later on form submit, I retrieve the form, and loop thru it:
form = arr[1];
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type !== 'submit') {
data = data + form.elements[i].name + '=' + form.elements[i].value;
}
}
Above, I'm creating an Ajax request data. The problem is that I always retrieve the first value(without refresh).
If I change the value of a form field, is ignored, I presume because I call it from the object, and not again from DOM. Something like refresh form.
But also I don't want if is possible to call the form DOM everytime.
You are making copies of your forms somewhere, being called from object shouldn't affect.
document.addEventListener('submit', function (e) {
collectFormData(e);
});
let formsArr = document.querySelectorAll("form");
let formsObj = {fArr: formsArr};
function collectFormData(e){
e.preventDefault();
//event.target
var currForm = e.target;
for(i=0; i<currForm.elements.length; i++){
if(currForm.elements[i].type !== 'submit')
console.log(currForm.elements[i].value);
}
//array
for(j=0; j<formsArr[0].elements.length; j++){
console.log(formsArr[0].elements[j].value);
}
//object
for(k=0; k<formsObj.fArr[0].elements.length; k++){
console.log(formsObj.fArr[0].elements[k].value);
}
}
<form name="myForm" id="myform" action="" method="POST" enctype="multipart/form-datam">
<input type="text" class="val1" name="val1" id="val1" />
<input type="text" class="val2" name="val2" id="val2" />
<input type="text" class="val3" name="val3" id="val3" />
<button type="submit">submit</button>
</form>
PS. But also I don't want if is possible to call the form DOM everytime The value of the input field is in(side) the DOM. You can't get the gift without touching the package.
This is my HJTML code. I don't know how to get values stored in filtertime[] using JavaScript and make them show on my screen.
<form action="index.php" method="post" >
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Morning"></div> <div class="f-txt-r">Morning</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Afternoon"></div> <div class="f-txt-r">Afternoon</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Evening"></div> <div class="f-txt-r">Evening</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Night"></div> <div class="f-txt-r">Night</div></div>
<div class="col-lg-12"><input type="submit" name="button" class="apply-filter" value="Apply Filter"></div>
</form>
<script>
var new = document.getElementsById("test").innerhtml
</script>
How can I get input values in JavaScript through value is stored in array as filtertime[]?
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
Add id in your form tag.
<form action="index.php" id="form_name" method="post" >
Use below code to get all form element by JS :-
document.forms["form_name"].getElementsByTagName("input");
Note:- Above Code will work only if you don't have selects or textareas in your form.
If you have assigned id in DOM element like below,
<input type="text" name="name" id="uniqueID" value="value" />
Then you can access it via below code:-
Javascript:-
var nameValue = document.getElementById("uniqueID").value;
If you have Radio button in your form, then use below code:-
<input type="radio" name="radio_name" value="1" > 1
<input type="radio" name="radio_name" value="0" > 0<br>
Javascript:-
var radios = document.getElementsByName('radio_name');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Hope it will help you :)
this is the easiest way to get array of your form items
var arrValues = [];
for (var x =0; x < document.getElementsByClassName("morning").length ; x++)
{
arrValues.push(document.getElementsByClassName("morning")[x].checked);
}
To do that, the easiest way is to select all input with the "morning" class and after, foreach look if is checked :
var item = document.getElementsByClassName("morning"); // get all checkbox
var checkboxesChecked = []; // result array with ckecked ckeckbox
for (var i=0; i<item.length; i++) {
// if is checked add the value into the array
if (item[i].checked) {
checkboxesChecked.push(item[i].value);
}
}
console.log(checkboxesChecked);
In the "checkboxesChecked" array you have all the values of the checked box.
I am just practicing some javascript and i used to use JQuery a lot! I have had no major experience with raw javascript and i want to learn it just as i did JQuery. I have a simple form and a javascript function to go with it onsubmit and i want to get the name and value of each input in the form with my function but it doesnt seem to work can someone help me out?
<!DOCTYPE html>
<html>
<head>
<title>Foreach Practice</title>
<script type="text/javascript">
function Get() {
var Form = document.getElementById('Form');
for(I = 0; I < Form.length; I++) {
var Value = this.attribute('name').value;
alert(Value);
}
}
</script>
</head>
<body>
<form id="Form" onsubmit="return false;">
<input type="text" name="User" placeholder="Username" />
<input type="password" name="User" placeholder="Password" />
<input type="submit" name="Submit" onclick="javascript:Get();" />
</form>
</body>
</html>
This question is probably better suited to code review, but whatever.
> function Get() {
Variable names starting with a capital letter are, by convention, reserved for constructors. Also, names should indicate what the function does, a generic "get" function doesn't give much of a hint. A better name might be getFormValues.
> var Form = document.getElementById('Form');
There is a document.forms collection available that can be used as an alternative to calling a method:
var form = document.forms('Form');
> for(I = 0; I < Form.length; I++) {
You should always declare variables in an appropriate scope (noting that ECMAScript only has global, function and eval scope, there is no block scope), especially counters. Also, the form's length attribute is the number of controls in the form. Since it's a live collection, getting the length every time when you don't need to is potentially a performance hit, so cache the value:
for (var i = 0, iLen = form.length; i < iLen; i++) {
> var Value = this.attribute('name').value;
The value of this is set by how you call a function. If the function is called by a handler, then depending on the browser and method attachment, this will reference the element whose listener called the function. In this case, because the function is called by an inline listener, this has not been set so will default to the global object.
You can easily pass a reference to the element from the listener if you do:
<input ... onclick="getFormValues(this);" ... >
Now your function will receive a reference to the element and can conveniently get a reference to the form and iterate over the controls. Finally, it is rare to need to access a form control's attribute values, you nearly always want to access properties. So here's the re-written function:
function getFormValues(element) {
var form = element.form;
var controls = form.controls;
for (var i=0, iLen=controls.length; i<iLen; i++) {
alert(controls[i].name + ': ' + controls[i].value);
}
// Prevent form submission
return false;
}
Lastly, you are better to call the listener from the form rather than the submit button, since forms can be submitted by means other than clicking a submit button. Oh, and don't call any form control "submit" or use any name that is the same as a form method as it will overwrite the same–named method. You get away with it here due to capitalisation, but that is not much defense.
The related HTML can be (note that the form now doesn't need either a name or id):
<form onsubmit="return getFormValues();">
<input type="text" name="userName" placeholder="Username">
<input type="password" name="userPassword" placeholder="Password">
<input type="submit" name="submitButton">
</form>
You should iterate to form's children and use getAttribute function to get attribute value.
Try this:
function Get() {
var Form = document.getElementById('Form');
var childs = Form.children;
for(I = 0; I < childs.length; I++) {
var Value = childs[I].getAttribute('name');
alert(Value);
}
}
Anyone looking for the answer to this i figured it ou just by using random attempts of rearranging my code but here it is.
<!DOCTYPE html>
<html>
<head>
<title>Foreach Tutorial</title>
<script type="text/javascript">
function Get() {
var Form = document.getElementById('Form');
for(I = 0; I < Form.length; I++) {
var Name = Form[I].getAttribute('name');
var Value = Form[I].value;
alert(Name + ' : ' + Value);
}
}
</script>
</head>
<body>
<form id="Form" onsubmit="return false;">
<input type="text" name="User" placeholder="Username" />
<input type="password" name="Pass" placeholder="Password" />
<input type="submit" name="Submit" onclick="Get();" />
</form>
</body>
</html>
I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];
Pls have a look at the following code.
<script type='text/javascript'>
function apps(){
var app= new Array(8);
for (var i=0;i<8;i++)
{
app[i]= ....;
}
}
</script>
<input type="hidden" name="NEW" value= ? >
< ....button label="Submit" OnClick='apps();return false;'/>
Here the apps() method gets executed on clicking the Submit button.
I want to access the value of app (Array) by use of a hidden element. Pls let me know what code I should write for this purpose.
<input type="hidden" name="foo" value="bar" />
document.write(document.getElementsByName('foo')[0].value);
output is "bar". getElementsByName returns an array of matching form elements with the name supplied. the [0] grabs the first match, and .value retrieves the value.
You can do this with JQuery as well.
<input id="foo-hidden" type="hidden" name="foo" value="bar" />
<script type="text/javascript">
function apps() {
var app= new Array(8);
for (var i=0; i < 8; i++) {
app[i]= $('#foo-hidden').val();
}
}
</script>