How to disable multiple radio buttons with sequential ids? - javascript

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

Related

JavaScript, retreive values into checkbox

My for loops are fine and I got the value for both transportationOutput and trasportation2 and I want to check if both values are equal checked the right checkbox input, but it does not get into if condition and I do not know why, I try to replace the == to === but also it does not work
trasportation = "car-train" //value from database
var trasportation2 = document.getElementsByName("transportation");
var transportationOutput = trasportation.split("-");
for (var i = 0; i < transportationOutput.length; i++) {
for (var j = 0; j < trasportation2.length; j++) {
if (trasportation2[j].value == transportationOutput[i]) {
trasportation2[j].checked = true;
}
}
}
<label>transportation</label>
<input type="checkbox" id="localTransportID" name="transportation" value="car"> car
<input type="checkbox" id="localTransportID" name="transportation" value="bus"> bus
<input type="checkbox" id="localTransportID" name="transportation" value="train"> train
<input type="checkbox" id="localTransportID" name="transportation" value="airplane"> airplane

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

Checking radio buttons according to an Array

I have an array containing four numbers:
var players = [0,3,4,2];
I have some radio buttons to select a name:
<h3 id="question">Which player would you like?</h3>
<input type="radio" name="choice" value="0" id="answ1">
<label for="choice" id="choice_1">John</label>
<br>
<input type="radio" name="choice" value="1" id="answ2">
<label for="choice" id="choice_2">Wayne</label>
<br>
<input type="radio" name="choice" value="2" id="answ3">
<label for="choice" id="choice_3">Steven</label>
<br>
<input type="radio" name="choice" value="3" id="answ4">
<label for="choice" id="choice_4">Jack</label>
<br>
<button id="back">Back</button>
<button id="next">Next</button>
When the radio buttons display I would like the first radio button to be checked i.e. The player John. I know I could simply set autofocus or use jQuery but I want to do it with vanilla Javascript. The idea is that the player names will change dynamically and the player will be selected based on the value in the array i.e. number 3 of the second set of players will be chosen.
Thanks, any help appreciated.
EDIT:
John will be chosen because the first value of the array is 0 and John is the first choice i.e. 0 = 1st choice, 1 = second choice etc
You need to increment/decrement an index value when the Next/Back buttons are clicked, and then set the checked property to true for the radio button with that index.
var players = [0, 3, 4, 2, 1];
var i = 0;
var choices = document.querySelectorAll('input[name="choice"]');
choices[players[i]].checked = true;
document.getElementById('back').onclick = function () {
if (i > 0) {
i--;
choices[players[i]].checked = true;
}
}
document.getElementById('next').onclick = function () {
if (i < players.length - 1) {
i++;
choices[players[i]].checked = true;
}
}
DEMO
You can try my approach using array.indexOf
var players = [0, 3, 4, 2];
var ins = document.getElementsByName('choice');
for (var i = 0; i < ins.length; i++) {
if (players.indexOf(parseInt(ins[i].value, 10)) > -1) {
ins[i].checked = true;
}
}
FYI:
The radio button is grouped under the name check so multiple
select is not going to work in your case.
This code will fail in older version of IE and here is the workaround.
You can do this like this:
var players = [0,3,4,2];
var firstValue = players[0];
var firstInput = document.querySelector("input[type=radio][name=choice][value='"+firstValue+"']");
firstInput.checked = true;
var players = [0,3,1,2];
var currentPosInArray = 0;
window.onload = function() {
ChangeSelectedRadio();
}
function ChangeSelectedRadio() {
var radio = document.querySelectorAll("input[type='radio']");
var arrItem = players[currentPosInArray];
for (var i =0; i< radio.length; i++ ){
radio[i].checked = false;
}
if (radio[arrItem]) {
radio[arrItem].checked = true;
}
}
function ChangeSelection(forward) {
if (forward) {
currentPosInArray++;
}
else {
currentPosInArray--;
}
if (currentPosInArray < 0) {
currentPosInArray = players.length -1; //if is in first pos and click "Back" - go to last item in array
}
else if (currentPosInArray >= players.length) {
currentPosInArray = 0; //if is in last position and click "Next" - go to first item in array
}
ChangeSelectedRadio();
}
where ChangeSelection(forward) is event to buttons.
DEMO: http://jsfiddle.net/9RWsp/1/

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

js get radio label text

i have this code :
<input type=radio name="vote_x" value="5">
<label for="vote_x">blabla</label><br>
how can i get the label value for radio with id of vote_x [using JS] ??
thanks
If you put an id on the label like this
<input type="radio" name="vote_x" value="5">
<label id="for_vote_x" for="vote_x">blabla</label>
You can then use
var textinlabel = document.getElementById("for_vote_x").innerHTML;
Edited: With out using an id for the label element
var labelElements = document.getElementsByTagName("label");
for (var i = 0, var labelElement; labelElements[i]; i++) {
if (labelElement.getAttribute("for") == "vote_x") {
//this is the labelElement you want
//code goes here
}
}
Ideally you would want to create a Generic function for this
function getlabelforinput(inputname) {
var labelElements = document.getElementsByTagName("label");
for (var i = 0, var labelElement; labelElements[i]; i++) {
if (labelElement.getAttribute("for") == inputname) {
return labelElement
}
}
return null;
}
Modern answer
Use document.querySelector('label[for="INPUT_ID"]') to get the label element corresponding to the input with given id.
Example:
const label = document.querySelector('label[for="vote_x"]');
console.log(label.textContent.trim());
<input type=radio name="vote_x" value="5">
<label for="vote_x">blabla</label>
You can try this
var el = document.getElementById("vote_x");
while(el.nextSibling && !(/label/i.test(el.nextSibling.tagName))){
el = el.nextSibling;
}
var text = el.nextSibling.innerHTML
You can check it in this fiddle.

Categories

Resources