Add class to radio button if checked - javascript

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>

Related

document.getElementsByTagName is working but same functionality is not working with document.getElementById

I was trying to change the color of placeholder of input tag using Javascript. I am able to achieve that if I use document.getElementsByTagName, but if I am using document.getElementById then it's not working.
HTML:
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
JavaScript (with document.getElementsByTagName):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
JavaScript (with document.getElementById):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
I am not able to figure why this is happening.
getElementById returns only 1 element, it is not an array
function ChangePlaceHolderColorx() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += "Red";
}
}
}
}
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += "Red";
}
}
}
.Red{
color:red;
}
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
You have to change function ChangePlaceHolderColor() to:
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
this is because getElementByTagName() will return HTMLCollection which you can treat as an Array, but getElementById() will return only one element.
getElementsByTagName will always return an array of HTML elements, whereas getElementsById will always return a single HTML element.
function ChangePlaceHolderColor() {
//no loop because the return is one element.
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
In HTML, element IDs must be unique on any given page.

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

Javascript Toggle Check All Nested Array Names

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

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