Javascript Toggle Check All Nested Array Names - javascript

I'm having a problem trying to create a Javascript function that checks all the checkboxes in a form.
An example of the checkboxes on my form look like
<b>A:</b> <input type="checkbox" name="multipleForms[201][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[201][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[201][C]"><br>
<b>D:</b> <input type="checkbox" name="multipleForms[201][D]"><br>
<b>A:</b> <input type="checkbox" name="multipleForms[500][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[500][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[500][C]"><br>
And what I want to do is be able to pass a number such as 201 and 500 into a Javascript function and have all checkboxes with the first array index as that integer be checked.
So, checkAll(201) would have the first 4 checkboxes checked and checkAll(500) would have the other 3 checkboxes checked.
I would rather not change the names of my checkboxes if that is possible as the stringed indexes are really important for my PHP code.
Thanks in advance.
Also, I would rather have non-jQuery code.

Something like that ? : http://jsfiddle.net/RZPNG/6/
var checkboxes = document.getElementsByTagName('input');
function check(num) {
for (var i = 0; i < checkboxes.length; i++) {
if (parseInt(checkboxes[i].name.split('[')[1]) === num) {
checkboxes[i].checked = 'checked';
}
}
}
check(201);​

Something like the following should do:
function checkBoxes(form, s) {
var input, inputs = form.getElementsByTagName('input');
var re = new RegExp(s);
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'checkbox' && re.test(input.name)) {
input.checked = true;
} else {
input.checked = false;
}
}
}
You could also use querySelectorAll, but support isn't that common yet:
function checkBoxes(s) {
var els = document.querySelectorAll('input[name*="' + s + '"]');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].checked = true;
}
}

Related

Add class to radio button if checked

I want to add the class 'selected' to both checkboxes and radio buttons if they are checked. I found below code online to make it work with the checkboxes.
What do I need to change to include the radio buttons also in the code?
<script>
var inputs = document.getElementsByTagName("input");
var checkboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
checkboxes.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
for (var j = 0; j < checkboxes.length; j++) {
checkboxes[j].onclick = function() {
if (this.checked == true) {
this.className += " selected";
} else {
removeClassName(this, 'selected');
}
}
}
function removeClassName(e,t) {
if (typeof e == "string") {
e = xGetElementById(e);
}
var ec = ' ' + e.className.replace(/^\s+|\s+$/g,'') + ' ';
var nc = ec;
if (ec.indexOf(' '+t+' ') != -1) {
nc = ec.replace(' ' + t + ' ',' ');
}
e.className = nc.replace(/^\s+|\s+$/g,'');
return true;
}
</script>
You don't need javascript.
There is a css selector for this, it's :checked
input[type="radio"]:checked {
/* Use the css of selected class */
}
For some reason some plugins in Wordpress removed that data. That's why I want to add an extra class to all the radio buttons and checkboxes. Below an example(this box is now checked):
<input id="payment_method_mollie_wc_gateway_ideal" type="radio" class="input-radio" name="payment_method" value="mollie_wc_gateway_ideal" data-order_button_text="">
If I understand your code correctly, I would assume you have to change if (inputs[i].type == "checkbox") { (around line 5) with if (inputs[i].type == "checkbox" || inputs[i].type == "radio" ) {, then it should also include the radio-buttons.
Here is the JSFiddle source https://jsfiddle.net/rj1405/Lnv70bsu/14/
Instead of adding the class name like
this.className += " selected";
I am trying tho add through javascript method
inputs[i].classList.add('selected');
please find the below code for your reference.
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" || inputs[i].type == "radio") {
if (inputs[i].checked) {
inputs[i].classList.add('selected');
// console.log(inputs[i].classList);
// console.log(inputs[i]);
}
}
}
<input type="radio" name="imgsel" value="" checked="checked" />
<input type="radio" name="imgse2" value="" checked/>
<input type="checkbox" name="vehicle" value="Car" checked>

How to disable multiple radio buttons with sequential ids?

I need to disable all the radio buttons; the best approach is by using javascript but i am not too good at it; I try looping the ids but it was a disaster!
i end up using 6 lines to disable each radio button at a time; can I do this a little more efficiently
document.getElementById("radio1").disabled = true;
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
document.getElementById("radio4").disabled = true;
document.getElementById("radio5").disabled = true;
document.getElementById("radio6").disabled = true;
Radio Buttons:<br>
<input type="radio" id="radio1">1<br>
<input type="radio" id="radio2">2<br>
<input type="radio" id="radio3">3<br>
<input type="radio" id="radio4" checked>4<br>
<input type="radio" id="radio5">5<br>
<input type="radio" id="radio6">6
You can use querySelectorAll() to select all inputs with type="radio" and then use loop to set disabled = true on each one
var inputs = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = 'true';
}
Radio Buttons:
<br>
<input type="radio" id="radio1">1<br>
<input type="radio" id="radio2">2<br>
<input type="radio" id="radio3">3<br>
<input type="radio" id="radio4" checked>4<br>
<input type="radio" id="radio5">5<br>
<input type="radio" id="radio6">6
Not sure why looping was a disaster. Here's how I would do it:
for (var i = 1; i <= 6; i++) {
document.getElementById("radio" + i).disabled = true;
}
Alternatively:
var ids = ['radio1', 'radio2', 'radio3', 'radio4', 'radio5', 'radio6'];
ids.forEach(function (id) {
document.getElementById(id).disabled = true;
});
You can use css selector (document.querySelectorAll):
var radios = document.querySelectorAll("[id^='radio']"); //get all elements that have an id starting with 'radio'
for (var i = 0; i < radios.length; i++) {
radios[i].disabled = true;
}
You could do something along these lines
// load all the inputs in the document into memory
var inputs = document.getElementsByTagName("input");
// loop over them, and set the disabled attribute on each of them
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
Note that by doing document.getElementsByTagName("input"), you collect all the inputs in your page, so a better approach would be to wrap them in a container, and do the expression on it, like this:
<div id="input-container">
<input type="radio" id="radio1">
...
</div>
and then
var container = document.getElementById("input-container");
var inputs = container.getElementsByTagName("input");
the loop remains the same

Trouble setting and adding array values javascript

I want to give each check box an integer value and then if the box is checked add the values and display the total in a text box with the ID="options". So far the code is not sending a value to the desired location. Any instruction on how to improve the code would be helpful. Thank you.
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input"),
result = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += inputs[i].value;
document.getElementById("options").value = result;
}
}
}
getOptions();
</script>
You may need to attach onchange event handlers to the checkboxes as shown below. And you should parse inputs[i].value to a number using parseFloat() before adding it to result.
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input");
function getOptions() {
var result = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += parseFloat(inputs[i].value);
}
}
document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox") {
inputs[i].onchange = function () {
getOptions();
}
}
}
getOptions();
JSFiddle

Radio Button list selected items value in javascript

I am using following code to get the selected elements value in radio button list.
function SelectRadioButton()
{
var radiobutton = document.getElementsByName('<%=RadioButtonList1.ClientID %>');
alert(radiobutton.length);
for(var x = 0; x < radiobutton.length; x++)
{
if(radiobutton[x].checked)
{
alert('selected is ' + radiobutton[x].id);
}
}
}
Following is the HTML markup
<table id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1" class="chk" onclick="javascript:SelectRadioButton(this, ctl00_ContentPlaceHolder1_idControl_RadioButtonList1)" border="0">
<tr>
<td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="1" checked="checked" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0">List</label></td><td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="2" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1">Assignment</label>
But I am getting length 0 in alert(radiobutton.length); statement.
Why is this happening. any thing that I am missing?
You can use jquery to do this.
alert($(".chk").find("input:checked").length); // chk is your css class name applied to Checkbox List element.
You can get specific element by using this
alert($(".chk").find("input:checked")[0]);
RadioButtonList1 will be converted to radio buttons with ids having RadioButtonList1, You can iterate through DOM and look for matched ids and put them in some array or directly perform what you want to them.
radiobutton = [];
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf("RadioButtonList1") != -1 )
{
radiobutton.push(e);
}
}
Here's how you do it with javascript only, if you don't want to use getElementById
Code | JSFiddle
function SelectRadioButton(){
var radiolist = getElementsByClass("table", "chk")[0],
radios = radiolist.getElementsByTagName("input");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
alert('Selected radiobutton is ' + radios[i].id);
}
}
}
function getElementsByClass(tag, name){
var elements = document.getElementsByTagName(tag);
var ret = [];
for(var i = 0; i < elements.length; i++){
if(elements[i].className.indexOf(name) !== -1){
ret.push(elements[i]);
}
}
return ret;
}

Fast way to validate if all checkboxes are un-selected?

Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)
All my check boxes have the same name...
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us" value="Joe" ID="Checkbox1">
<input type=checkbox name="us" value="Dan" ID="Checkbox2">
<input type=checkbox name="us" value="Sal" ID="Checkbox3">
</form>
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:
function AreAnyCheckboxesChecked () {
var checkboxes = document.forms.Form2.elements.us;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.
var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
is_checked = inputs[x].checked;
if(is_checked) break;
}
}
// is_checked will be boolean 'true' if any are checked at this point.
JavaScript:
var allischecked = (function(){
var o = document.getElementById("Form2").getElementsByTagName("input");
for(var i=0,l=o.length;i<l;i++){
o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
}
return true;
})();
With jQuery:
var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);
In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.
var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
if(a[i].checked)
return false;
return true;
(did not test, but conceptually it is valid)
What do you mean by
Without going through array
?
You could just do
function check() {
var anyChecked = false;
var form = document.getElementById('Form2');
var checkboxes = form.getElementsByTagName('input');
for(var i=0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
alert("Checkboxes checked? " + anyChecked);
}
Working Demo
If you have a large amount of checkboxes that you don't want to loop through to test it might be more efficient to use this approach.
var checked = 0;
$("input[type=checkbox]").live("click", function() {
if($(this).attr("checked")) checked++;
else checked--;
}
Then you would be able to test like this.
if(checked === 0) {
doSomething();
}
The proper solution with jQuery attribute checked:
$checkboxes = $('#Form2 input:checkbox');
$checkboxes.on('click', checkboxes);
function checkboxes() {
var allChecked = $checkboxes.not(':checked').length == 0;
console.log(allChecked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us1" value="Joe" ID="Checkbox1"><label>Joe</>
<input type=checkbox name="us2" value="Dan" ID="Checkbox2"><label>Dan</>
<input type=checkbox name="us3" value="Sal" ID="Checkbox3"><label>Sal</>
</form>
Even easier without loop
const toggleCheckboxes = checkbox => {
if(checkbox.checked){
return true
}else{
if(document.querySelectorAll(':checked').length === 0){
// All are unchecked
return false
}
}
}

Categories

Resources