Checking all radiobuttons without Jquery - javascript

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.

Related

Check values of loop to see if ANY match?

In ruby, I would do something like:
array = [1,2,3]
array.any? {|a| a == 1}
=> true
Although, instead of an array, I am going up against a hash
var shop_products = {"607":607};
I have a checkbox loop and I want to check against all currently checked boxes for when checkboxes are both checked and unchecked to then see if there is a matching value and disable/able and hide/show a button if so.
code: https://jsfiddle.net/mk879vu2/7/
As #Mark Meyer mentioned, some can help but is there a way to use this against a hash or an alt for hashes?
I tried this: https://jsfiddle.net/jq9sgp58/
Maybe I am using this wrong?
My issue right now is when a checkbox is unchecked, it sees that the value is the "correct" one, but it isn't displaying the button when I uncheck. I'm doing something wrong in the conditional somehow.
In the jsfiddle I have all of the inputs but I only want one of the buttons (of the 2) to appear when a record with specific parameters is checked (in the example this is value=607, this can be any amount but in the example I have it as 1 record/input). But when I uncheck and the 607 is left alone as the only checked input, it runs the hide/disable and not the show.
What is wrong with my code?
It sounds like you are looking for #array.some()
let a = [1,2,3]
console.log(a.some(n => n === 1)) // true
console.log(a.some(n => n === 4)) //false
https://jsfiddle.net/2kaegb59/
The .some seemed like the way to get it done but i couldn't get it to work with the hash. I'm sure it's possible. Although, I ended up just checking for an undefined through the hash instead of trying to match up the check value with the hash value and it is likely unnoticeably faster.
for (var check of checked_checkboxes_check) {
if (shop_products[check.value] === undefined) {
print_submit.hide().prop("disabled", true);
break;
} else {
print_submit.show().prop("disabled", false);
}
}

Checkbox checked with javascript does not POST

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

Newbie: Checking to see if radio button is checked on form initialization. What does this code mean?

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;
}

Javascript get value by radio button name

first of all i am a beginner in javascript, a really big beginer
Can someone give me a hint on this?
I have a form, on the form i have a radio button.
And i would like to that if the radio is set yes , it would show the value of it on another page.
And i would like to get the value by the input name
is it possible?
I'm not asking to write my code, but just an example for a start.
i was tried with this just for a test
<input type="hidden" name="the_name" value="yes">
if(the_name.element == 'yes') {
alert('cool');
}
the_name.value, not the_name.element
You can use getElementsByName() for accessing the elements value via the input name. But as a standard and since it helps load off the DOM we use getElementById() instead of the name. Also you can start from here -> http://eloquentjavascript.net/
You can reference the form using:
document.forms[formName or formId].elements[element-name];
However, name is not necessarily unique in the document. If there is only one element with the name, then only one is returned. If more than one have the same name, then you will get a collection (a bit like an array) and you will have to iterate over them to find the one you want.
You can also use document.getElementsByName, which always returns a collection. So you can do:
var elements = document.getElementsByName('the_name');
// get the one with value 'yes'
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (elements[i].value == 'yes') {
return elements[i];
}
}
You will also need to be careful of case sensitivity, you might want to use toLowerCase() on the value first, or use a case insensitive regular expression:
e.g.
var re = /yes/i;
...
if (re.test(elements[i].value)) {
// value is Yes or YES or yeS or ...
<input type="hidden" name="the_name" id="the_name" value="yes"> <!-- id added -->
if(formName.the_name.value == 'yes')
{
alert('cool');
}
OR better (since you are not accessing the elements by global names)
var element = document.getElementById("the_name");
if(element.value === 'yes')
{
alert("yes, it is");
}

determining if a field exists on a form

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
}
}

Categories