Radio Button list selected items value in javascript - 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;
}

Related

Getting error [object HTMLCollection]

I am having a problem in making a simple test in javascript. This is a quick example. Each question's div id is incremented in the html code.
HTML
<form action="#">
<div id="q1">
<label>Q. ABCD</label>
<label><input type="radio" name="radio1" value="1">A</label>
<label><input type="radio" name="radio1" value="2">B</label>
<label><input type="radio" name="radio1" value="3">C</label>
<label><input type="radio" name="radio1" value="4">D</label>
</div>
....
....
<input type="button" value="Click to Submit" onClick="result();">
</form>
JS (say for 10 questions)
function result() {
var answer = new Array();
for(var i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).getElementsByTagName("input");
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
I am getting an error [object HTMLCollection] every time I submit the code. How should I do this so that I can get the value of each answer given inside the array and if someone doesn't answer any question, the array must get 0 value at its place instead of undefined. I need a pure JS and HTML solution.
Try this one
function result() {
var answer = new Array();
// there is no answer 0
answer[0] = 'unused';
for(var i=1; i<11 ; i++) {
// check if the id exists first
var container = document.getElementById("q" + i);
if(container) {
// get the selected radio checkbox
var input = container.querySelector("input:checked");
// if there's one selected, save it's value
if(input) {
answer[i] = input.value;
}
else {
answer[i] = 0;
}
}
}
console.log(answer);
}
a working fiddle - http://jsfiddle.net/dtpLjru1/
In your code, you are trying to store the HTML collection by using getElementByTagName(). This method will return all the Tags with the name of "input", so total of 4 tags as per the code above.
Instead of that, you can modify your code like below.
Assuming, you want to store "1" in case radio button is checked. else 0
function result() {
var answer = new Array();
for (var i = 1; i <= 4 ; i++) {
if (document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).checked ? 1 : 0;
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
Have not tested the code, How about we do this ?
function result() {
var answer = new Array();
for(i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
document.write( document.getElementById("q" + i).getElementsByTagName("input") );
}
else {
document.write(0);
}
}
}

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
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/

Unchecking a checkbox and modifying value of sum

I am trying to design a menu. If you check a box, then sum get added up and if you uncheck it, the sum is reduced. I face trouble in reducing the sum while unchecking the box and also the value of sum is not globally changed. Please help me out.
<head>
<script>
var sum=0;
function a(sum,num) {
sum=sum+num;
document.getElementById("demo").innerHTML=sum;
}
</script>
</head>
<body>
<input type="checkbox" name="Dal" id="dal" onclick=a(sum,10)>Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick=a(sum,20)>Rice<br>
<h1> Total Price is : </h1>
<p id="demo"> 0 </p>
</body>
Change the markup, add a value and a class, and remove the inline JS
<input type="checkbox" name="Dal" id="dal" value="10" class="myClass">Dal
<input type="checkbox" name="Rice" id="rice" value="20" class="myClass">Rice
<h1> Total Price is : </h1><p id="demo">0</p>
Then do
<script type="text/javascript">
var inputs = document.getElementsByClassName('myClass'),
total = document.getElementById('demo');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
</script>
FIDDLE
You can do something like this:
function a (elem, num) {
var k = (elem.checked) ? 1 : -1;
sum = sum + k * num;
document.getElementById("demo").innerHTML = sum;
}
And in the HTML:
<input type="checkbox" name="Dal" id="dal" onclick="a(this, 10);">Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick="a(this, 20);">Rice<br>
Try something like this:
var sum = 0;
function a(id, num) {
if(id.checked == true){
sum += num;
id.onclick = function() { a(id, num)};
}
else {
sum -= num;
id.onclick = function() { a(id, num)};
}
document.getElementById("demo").innerHTML=sum;
}
Fiddle: http://jsfiddle.net/95pvc/2/
My own take would involve removing the event-handling from the HTML (unobtrusive JavaScript) for easier maintenance in future, using data-* attributes to contain the price and using a class-name to identify the relevant ingredients, to give the following HTML:
<input class="ingredients" type="checkbox" name="Dal" data-price="10" id="dal" />Dal
<input class="ingredients" type="checkbox" name="Rice" data-price="20" id="rice" />Rice
<h1> Total Price is : </h1>
<p id="demo">0</p>
Which leads to the following JavaScript:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
for (var i = 0, len = ingredients.length; i < len; i++) {
ingredients[i].addEventListener('change', price);
}
JS Fiddle demo.
To avoid having to iterate through the relevant checkboxes, it might be better to wrap those input elements in a form, and then bind the event-handling to that form:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
document.getElementById('formID').addEventListener('change', price);
JS Fiddle demo.
References:
addEventListener().
element.getAttribute().
getElementsByClassName().
parseFloat().

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

Categories

Resources