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/
Related
I have few radio buttons:
<input type="radio" value="####.###/resources/videos/7.mp4">
<input type="radio" value="####.###/resources/videos/8.mp4">
<input type="radio" value="####.###/resources/videos/9.mp4">
How can I make an array containing the selected values like following:
var videos = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"];
Onclick push the value of radio in array
var arr=[];
$('input').click(function(){
arr.push("."+$(this).val().split('####.###')[1])
console.log(arr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="####.###/resources/videos/7.mp4">Video1
<input type="radio" value="####.###/resources/videos/8.mp4">Video2
<input type="radio" value="####.###/resources/videos/9.mp4">Video3
I would add a change event listener, that checks if the input got checked or unchecked and would add it or remove it from the list.
var originalVideoList = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"
];
var videos = document.querySelector("#videos");
var result = document.querySelector("#result");
var template = "<li><label for='{0}'>Video {1}</label><input id='{0}' type='checkbox' onchange='onChange()'/></li>";
var selectedArray = [];
// Set up html
videos.innerHTML = originalVideoList.map(function(video) {
return template.replace(/\{0\}/g, video).replace(/\{1\}/g, video.split("/").pop());
}).join("");
// triggered on input change
function onChange() {
selectedArray = toArray(document.querySelectorAll("li>input:checked")).map(function(item) {
return item.id.replace("####.###", ".");
});
result.innerHTML = selectedArray.map(function(video) {
return "<li>" + video + "</li>";
}).join("");
}
// Same as [...input]
function toArray(input) {
var result = [];
for (var index = 0; index < input.length; index++) result[index] = input[index];
return result;
}
<ul id="videos"></ul>
<ul id="result"></ul>
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
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;
}
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;
}
}
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.