I'm working on a project where I have to select multiple input tags by NAME from multiple forms.
I selected the forms using getElementsByTagName('forms') (which returns a HTML Collection as far as I understand). When I try to apply the getElementsByName('example') i get the undefined TypeError. After doing some reading I've found out that HTML Collection does not have that method. My question is what method should I use to select the input fields by name in this case?
(Note: I can't use jQuery on this project.)
Please let me know if I need to clarify anything.
Cheers!
Edit: Here's a code i'm working on. One of the constraints in this project is that I don't know how many forms there will be on the website, or how many input boxes those forms will have. (FieldObj is an object that contains the names of input fields)
var formsList = document.getElementsByTagName('form');
var form;
for (form in formsList) {
var currentForm = formsList[form];
for (field in fieldObj) {
if (formsList.getElementsByName(field)) {...}
}
}
It seems fieldObj variable in your code is undefined. I would loop forms in this way:
var formsList = document.getElementsByTagName('form');
for (var i=0; i < formsList.length; i++) {
var form = formsList[i];
for (field in form) {
var value = form[field].value;
}
}
Related
I have an array of 27 checkboxes generated using php. Checking the checkboxes manually works perfectly. The checkboxes are placed in an html table (other tabular dated is included), (all inside the form tags) with name="chk[]' and value='Index Number' of the array (0-27) in the usual form of
When I execute a typical Java-script "Check All" function (from a link_click or button_click) the check boxes all display the check-boxes as 'checked'. But, nothing gets submitted. Print_r shows the 'chk' array is indeed empty when I submit!
If I set the check-boxes manually, $_POST('chk') array IS posted, and everything works as expected.
It appears that when checking the check-boxes with Javascript, ¡checked' values don't get posted.
Print_r confirms the 'chk' array is empty whenever the 'displayed' value was set using Javascript!
Can anybody attempt to explain to me why the 'displayed value' of the checkbox is not reflected by, or included in the post?
The page validates on W3C Ok and I have crawled over my code and cannot find any likely errors. Platform is Win7/Wamp Sever/Firefox. Google/StackOverflow search does not reveal any similar symptoms/solutions.
Many thanks in advance for anyone with an idea on the problem.
The javascript CheckAll function I am using is -
function checkall(frm) {
for (var i=0; i<frm.elements.length; i++) {
if (frm.elements[i].name = "chk")
{frm.elements[i].checked = true;}
}
}
The array of 27 check-boxes is in the normal array format, with 'value' being the array Index.
<tr><td><input type='checkbox' title='' name='chk[]' value='6' ></td> text label </tr>
You have two errors in your if condition.
It's not even a condition, it's an assignment statement (conditions are written with
double equal signs)
Element name should be compared to chk[] instead of chk
Your checkall function should be:
function checkall(frm) {
for (var i=0; i<frm.elements.length; i++) {
if (frm.elements[i].name == "chk[]")
frm.elements[i].checked = true;
}
}
Now you might be wondering what the hell does this have to do with the values not being submitted, and why are they checked, I can explain.
Your current code is assigning a new name "chk" to the checkbox elements (see reason 1 why your condition is not even a condition), and since it's not a condition, the if statement is always true, and the code segment that sets the checked value to true is being executed and that's why you can see the elements checked. Now when you request $_POST['chk[]'] in your PHP you get nothing because the elements' names were all changed to 'chk' by your supposedly (if "condition").
iSWORD has a complete answer, this is just some additional hints. You can simplify the function by taking advantage of built–in browser features:
function checkall(frm) {
var cbs = frm['chk[]'];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cbs[i].checked = true;
}
}
Form controls are available as named properties of the form. Where more than one control shares the same name, an HTML collection is returned. So in the above, cbs is a collection of all the controls with a name of 'chk[]'.
To account for cases where there might be zero, one or more same–named controls, use:
function checkall(frm) {
var cbs = frm['chk[]'];
if (cbs) {
if (typeof cbs.length == 'number') {
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cbs[i].checked = true;
}
} else {
cbs.checked = true;
}
}
}
You could also use querySelectorAll, which always returns a collection (but might not be available everywhere) and use the following with the first function:
var cbs = document.querySelectorAll('input[name="chk[]"]');
You can try using this function
Javascript
function checkall(formname,checkname,thestate){
var el_collection=eval("document.forms."+formname+"."+checkname)
for (c=0;c<el_collection.length;c++)
el_collection[c].checked=thestate
}
HTML
Check All
Uncheck All
I have a script wherein I would like to get the form's placeholder attribute and then use as a conditional in a function like so (this doesn't seem right to me, so I'm not surprised it doesn't work):
if (document.getElementsByName("Name").input.placeholder == "Enter Name") {
//do something
}
The wrapper function actually takes the form as argument:
function form_function(form) {
var input = document.getElementsByName("Name");
var placeholder = input.placeholder;
if (placeholder == "Empty") {
// do something
}
}
I've tried a few different things to no avail. The error console is telling me that the input is undefined. For example, I started with:
var placeholder = form.input.placeholder;
and that didn't work either.
I then ran some alert tests and when I just alert the input I get NodeList object, which I'm not sure how to deal with.
So I tried looping through the NodeList and got some objects I'm unsure how to use.
var inputList = document.getElementsByName("Name");
var inputArray = [];
for (var i = 0; i < inputList.length; i++) {
inputArray[i] = inputList[i];
alert(inputArray[i]);
}
Alert gives [object HTMLInputElement]
Basically, I just want to test against the placeholder value in the form with the specific name attribute. Seems I've gone awry...
Thanks.
As #apsillers correctly stated, the elements re turned are in an array so I needed to capture the one I needed. I went with this:
placeholder = document.getElementsByName("Name")[0].placeholder;
and then was able to use this in the function as required.
I am new to radcontrols.
I want to know how to get type of control of a radcontrol using javascript.
For normal asp.net controls we write:
var controlType=document.getElementById("hdnCode").type;
The above code will give type of control as "hidden", and for textbox it will give "text".
When i try to get type of a rad control it gives undefined as shown here:
var controlType=document.getElementById("RadComboBox1").type;
The above code gives undefined.
Please suggest me how to get type in case of Rad Controls.
Thanks
You can't really check for the type of the control like this, these are complex objects (IScriptControls) and not simple HTML elements.
You can try the following approach to see the instances of given type (the if block shows how you can make a check only):
function get_allRadCombos()
{
var allRadCombos = [];
var allRadControls = $telerik.radControls;
// all RadControls are referenced
for (var i = 0; i < allRadControls.length; i++)
{
var element = allRadControls[i];
if (Telerik.Web.UI.RadComboBox && Telerik.Web.UI.RadComboBox.isInstanceOfType(element))
{
allRadCombos.push(element);
}
}
// only the RadCombos are gathered into an array
return allRadCombos;
}
The $telerik.radControls is an array the RadControls create and populate, you can check a given instance by referencing it through the $find(controlClientID) method
I'm working on a basic order form and I would like to see if I can build it from stratch.
I have a form which is made up of a table with 12 items listed and text input fields for item quantity. What I would like to do is have the code run through the form to check for any quantities that have been entered, then relate these values to the prices in an array.
So far I have the array:
var juicePrice = new Array();
juicePrice["citrusZing"]=20.00;
juicePrice["strawberrySmooth"]=22.00;
juicePrice["carrotSpin"]=21.50;
juicePrice["Tropical"]=20.75;
...
and a way to run through the form:
calculateTotal()
{
var juiceForm = document.forms["juiceform"];
//Get a reference to the juice the user Chooses name=selectedJuiceQty":
var selectedJuiceQty = juiceForm.elements["selectedJuiceQty"];
for(var i = 0; i < selectedJuiceQty.length; i++);
but I'm not quite sure how to connect the information from the form to calculate the totals. Can anyone point me in the right direction? Is it something like this?
for(var i = 0; i < selectedJuiceQty.length; i++){
var juiceTotal = 0;
if(selectedJuiceQty[i]>0) {
juiceTotal += juicePrice[selectedJuiceQty[i].value]*selectedJuiceQty;
//If we get a match then we break out of this loop
break;
}
return total;
}
Is it possible to use the same name tag for each field or should I just use citrusZingQty = parseInt(document.getElementById("citrusZing").value); for each item? Then I would have to list all of the items, which doesn't seem a very elegant way. What would happen if multiple items are selected?
Any help anyone can give to point me in the right direction would be great.
So you can do what you want. Michael pointed this out in the comments but it may have been overlooked.
var myPrices = new Object();
myPrices['eggs'] = 1.50;
myPrices['bread'] = 1.00;
// ...
Then you can loop through your form fields and check against your 'myPrices' object.
EDIT
To answer your question in the comments - I would not use the same name for all of my input fields. It does make looping through the form easier perhaps. However, using the id/class of the input tag is not a nice solution in my opinion. HTML id/class are there for CSS/Javascript manipulation and using it to identify which fruit the input represents will not be apparent to other developers working on the project (I realize this may be a small project for you but it's best not to start any bad habits). I would name each input after the juice/drink it represents.
This is driving me nuts, and I'm sure it's both possible and surely simple to do.
I have a page with a whole bunch of dynamically created forms on it. In one of my functions, I need to access one of those forms, so I pass the name of the form in a variable.
Then I need to access the name of that form using the document tree.
However, when I put in the variable, it assumes the name of the variable is the name of the form.
So this does not work:
function myAwesomeFunction(nameOfForm)
{
var selection = document.nameOfForm.nameOfInput.selectedIndex;
}
So I looked around the net and saw that I need to use bracket notation, but this doesn't work either:
function myAwesomeFunction(nameOfForm)
{
var selection = document[nameOfForm].nameOfInput.selectedIndex;
}
I also tried with some quotation action:
function myAwesomeFunction(nameOfForm)
{
var selection = document['nameOfForm'].nameOfInput.selectedIndex;
}
... but no joy.
So, where am I going wrong?
For bonus points... what if both the name of the form and the name of the particular input were both dynamic? Then what?
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document[nameOfForm][nameOfInput].selectedIndex;
}
Look them up in the forms object - this won't work since it is an array and not an object.
use document.getElementsByName
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document.getElementsByName(nameOfForm)[nameOfInput].selectedIndex;
}
or even better, set an id attribuite on the form and use document.getElementById to find the form
Try using document.getElementById(nameOfForm) (if you have the ID on the form as well)...
If you can include a jQuery reference to your page, you can easily do the following (again assuming you have the ID on the form):
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var form = $("form#" + nameOfForm);
var input = $("#" + nameOfInput + ":input");
var selection = $(input).val();
}
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
}
try this
formname is name of the form and elemname is input label name