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
Related
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;
}
}
i want to check the first element of multiple radiobutton groups.
I'm using Firebug, which is why i do not want, yes i know there is firequery, but there must be a way like they did it in the old days :)
Any help yould be great, thx in advance.
Loop backwards over document.getElementsByTagName('input') and set checked to true if type is equal to "radio".
If you try to check multiple buttons in the same group, the last one will hold.
Thus, looping backwards will end up checking the first option in each group.
Update
Feeling a bit silly here, you said you were using Firebug, and thus Firefox, and so we have querySelector available. Thus checking the first radio button in any given group is a one-liner:
document.querySelector('input[type="radio"][name="theGroupName"]').checked = true;
Live example
querySelector returns the first matching element, and so the above will return the first input element with type="radio" and name="theGroupName". Then we just set its checked to true.
Granted that doesn't do the first of all groups, but it gives you more control and is (again) a one-liner — handy for Firebug.
Original answer
You can use getElementsByTagName to get all input elements in document order. Then loop through them, only processing the ones with type="radio" and remembering the last name you encoutered; mark checked = true for the first of each name.
E.g.:
var inputs = document.getElementsByTagName('input');
var lastName, index, input;
for (index = 0; index < inputs.length; ++index) {
input = inputs.item(index);
if (input.type.toLowerCase() === "radio") {
if (input.name !== lastName) {
lastName = input.name;
input.checked = true;
}
}
}
Live example
If you want to limit that to some container, you can use the element version of getElementsByTagName.
I am a javascript novice. I'm trying to build a complex form whilst simultaneously learning JS and JQ... not an easy task. This code works, but I don't know what two lines do, so I thought I'd ask here.
What this code does is loop through an array to see if a radio button checkbox has been checked as yes or no. It runs at initialization when a user revisits the form he/she is filling out. The code is attached to a textfield element which unhides if myRadioButton is yes, stays hidden if no.
I do not know what lines 5 and 6 do (beginning with the second if statement). Would some knowledgable person please be so kind as to transcribe those lines into a couple of sentences, kind of like they do in tutorials? I would really appreciate it!
var rbVal = "";
var rbBtn = JQuery("[name=\"myRadioButton[]\"]");
for (var i = 0; i < rbBtn.length; i++)
if (rbBtn[i].checked) {
if (rbVal != "") rbVal += ",";
rbVal += rbBtn[i].value;
}
if( rbVal != "yes" ){
doSomething;
}
else {
doSomethingElse;
}
That code is checking all radio buttons with a shared name myRadioButton[], to make sure that if one is checked its value is added to rbVal string seperated by a comma.
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); <- gets an array of radio buttons
for (var i = 0; i < rbBtn.length; i++) <- loops through every button in that array.
if (rbBtn[i].checked) { <- if the button is selected it then checks to see if rbVAl is already set. <-- Either you are missing something here or it is faulty program
Line 5 compares the value of rbVal to an empty string (""). If rbVal is not equal (!=) to an empty string, a string containing a comma character is appended to rbVal. So for example, if rbVal contains the string "hello", after the execution of that line, it will contain "hello,".
Line 6 then appends the value of rbBtn[i].value to rbVal. rbBtn is an array-like object (in fact, it appears to be an instance of jQuery containing whatever was matched by the selector), and when you access a jQuery object with array syntax like that, you get the actual DOM element rather than another jQuery object, so the value property is the actual value property of the DOM element (by the look of it, that will be a radio button).
So, if you have a radio button like this:
<input type="radio" value="someVal">
then your loop would result in rbVal == "someVal".
If you have two radio buttons:
<input type="radio" value="someVal">
<input type="radio" value="anotherVal">
then you would end up with rbVal == "someVal,anotherVal". You can see from that what the overall purpose of that loop is - to build up a comma-separated string of the values of all the radio buttons matched by the jQuery selector.
Curiously, this is using jQuery to grab radio buttons and some vanilla JavaScript to see if the returned radio buttons are checked or not.
var rbVal = ""; initalises a new variable with an empty string "".
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); fetches all elements from the document that are called myRadioButton[].
for (var i = 0; i < rbBtn.length; i++) loops through each of the returned elements (there might be more than one as myRadioButton[] is an array of radio buttons hence the [] at the end). i is the current index in the array of returned elements.
if (rbBtn[i].checked) sees whether the radio button is "checked" ("on", if you like).
rbVal += rbBtn[i].value;: If the current radio button is checked (remember, for() loops through them all), fetch it's value attribute and append it (add it onto) whatever is currently in rbVal.
For example, if rbVal contains Hello and the radio button's value is world then rbVal would end up containing Hello world.
if( rbVal != "yes" ) If the value in rbVal doesn't equal (!=) yes, then we call the doSomething function.
If rbVal does contain yes, then we want to call the doSomethingElse function:
else {
doSomethingElse;
}
I have a form which has 4 columns and the user can dynamically add or delete rows.
Now I tried to validate this through javascript following code:-
<script type="text/javascript">
function chkempty()
{
var x=document.forms["main"]["qty[]"].value
var y=document.forms["main"]["price[]"].value
var z=document.forms["main"]["item[]"].value
if (x==null || x=="") {
alert("Quantity must be filled out");
return false;
}
if (y==null || y=="") {
alert("Price must be filled out");
return false;
}
if (z==null || z=="") {
alert("Itemcode cannot be empty");
return false;
}
}
It works for the first row but when the user selects more than one row, even after filling up values, he is getting the validation error message. can someone help me with this please?
Thanks and keep smiling.
VERY simple solution here:
Use Jquery Inline Validator
When you add new lines of content to the table, simply ensure that you have the proper class defined (such as class="validate[required,custom[email]]" ) to ensure that it will validate the field correctly as you wish. I often just do the required element, but the example I gave above also does email format checking. There are additional built in checkers for phone numbers, currency, etc.
If the user messes up an input, it will display a visually appealing tooltip like dialog next to the field with the error.
Done. Simple. Clean. Fast.
None of these solutions make up for the fact that you really need to sanitize on the server-side as well. Any Javascript can be bypassed, so it's not 100% guaranteed to be safe or accurate. But it is a good start and provides quality, instant feedback to the user.
var x=document.forms["main"]["qty[]"].value
You should loop over the elements and validate each value, instead of trying to get a value from an array, I guess.
var x=document.forms["main"]["qty"];
for ( var i=0, len=x.length; i<len; ++i ){
// validate the value of the current element.
}
EDIT: added a small example.
document.forms.form_id.control_name will return either an HTMLElementNode or a NodeList depending if there are one or many matching elements.
You can do something like:
var x=document.forms["main"]["qty[]"]
if (x.nodeName) {
// Is a Node. Work with its value
} else {
// Is a NodeList, loop over it with for
for (var i = 0; i < x.length; i++) {
var node = x[i];
// Work with its value
}
}
I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}