Hi
I am creating dynamic div elements , let say 4 div are there . div1,div2,div3,div4. each div has set of radio buttons rad1,rad2,rad3,rad4 . see as follows.
div1 ->rad1,rad2,rad3,rad4 groupName=rd1 ->end div1
div2 ->rad1,rad2,rad3,rad4 groupName=rd2 ->end div2
div3 ->rad1,rad2,rad3,rad4 groupName=rd3 ->end div3
div4 ->rad1,rad2,rad3,rad4 groupName=rd4 ->end div4
This is dynamically created html. i want to get which Radio selected from div2 or div3 what script i have to write ?
DEMO: http://so.lucafilosofi.com/get-html-element-inside-another-element-in-javascript
function checkRadio() {
var radios = document.getElementById('rBox').getElementsByTagName('input');
for (var i = 0; i < radios.length; i++) {
radios[i].onclick = function(e) {
var pid = this.parentNode.id;
if ( pid == 'group-2' || pid == 'group-3' )
alert('PARENT: ' + this.parentNode.id )
}
}
}
<body onload="checkRadio()">
<div id="rBox">
<div class="rad" id="group-1">
<input type="radio" name="option" />
....
</div>
<div class="rad" id="group-2">
<input type="radio" name="option" />
....
</div>
....
</div>
</body>
use jquery
use jquery-> $.live()
If I understood you right, this may help you:
var num_of_options = 4;
var selected = new Array();
var op, i, j;
for (j=1;j<=num_of_options;j++) {
op = document.getElementsByName("rd"+j);
for (i in op) {
if (op[i].checked) {
selected[j] = op[i].value;
}
}
}
selected will contain the selected values for the radio groups in each divs.
Here is crude sample code that will show the selected value in each div:
var arrDivs = ["div1", "div2", "div3"];
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = document.getElementById(arrDivs[i]);
if (oDiv) {
var arrInputs = oDiv.getElementsByTagName("input");
var blnFound = false;
for (var j = 0; j < arrInputs.length; j++) {
var oInput = arrInputs[j];
if (oInput.type == "radio" && oInput.checked) {
alert("The value of selected radio in div '" + arrDivs[i] + "' is: " + oInput.value);
blnFound = true;
break;
}
}
if (!blnFound)
alert("div '" + arrDivs[i] + "' contains no selected radio button");
}
else {
alert("div was not found: " + arrDivs[i]);
}
}
Related
I'm trying to select items from a Select list and generate a Radio list.
Let's say I have these options in a list:
abc
dab
I want to print them in a radio list like this:
(radiobutton1) abc
(radiobutton2) dab
But right now I am just getting a result like this:
(radiobutton1)(radiobutton2) abc dab
Here is my code:
HTML
<radio id = MyRadio multiple></radio>
<label id = MyLabel multiple></label>
and Javascript:
function btn2Click() {
var SelectedItems = document.getElementById("MyList");
var i;
for (i = 0; i < SelectedItems.length; i++)
{
if(SelectedItems.options[i].selected)
{
var RadioSelect = document.createElement("INPUT");
RadioSelect.setAttribute("type", "radio");
var RadioText = document.createTextNode(SelectedItems.options[i].text+'\n');
RadioSelect.appendChild(RadioText);
document.getElementById("MyRadio").appendChild(RadioSelect);
document.getElementById("MyLabel").appendChild(RadioText);
}
}
}
something like this? http://jsfiddle.net/swm53ran/101/
<div class="radioButtons">
Place Radio Buttons Here
<br/>
</div>
$(document).ready(function() {
var list = ['dog', 'cat', 'fish'];
var html = "<input type='radio'/>";
for (var i = 0; i < list.length; i++) {
$('.radioButtons').append(html + list[i] + '<br/>');
}
});
Labels work with the for attribute. The for attribute needs to refer to the id of the radio input.
if(SelectedItems.options[i].selected)
{
var RadioSelect = document.createElement("INPUT");
RadioSelect.setAttribute("type", "radio");
var RadioText = document.createTextNode(SelectedItems.options[i].text+'\n');
document.getElementById("MyRadio").appendChild(RadioSelect);
document.getElementById("MyLabel").appendChild(RadioText);
}
Change the label html to:
<label id="MyLabel" for="MyRadio" multiple></label>
HTML
<div id="myRadioButtons" />
JS
var html='';
$.each(['apply', 'pear', 'peach', 'lime'], function (i, v){
html += "<input type='radio'/>" + v + '<br/>';
});
$('#myRadioButtons').append(html);
DEMO
Please see the fiddle link at the bottom. I have two questions:
How to add HTML text to these radio buttons. I have to give them $ and % value (for the user).
Find the values of every radio button selected. For example, the user added 10 rows (each having 2 radio buttons). I have iterated a loop to find the input type and see if the button is checked and then find its value.
NOT WORKING, guide me what wrong am I doing.
FIDDLE
var i=0;
window.myAdd = function(){
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency"+x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio"+i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i=i+1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency"+x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio"+i);
i=i+1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('tab').appendChild(row);
x=x+1;
}
window.myfunction = function(table){
//var x = String(document.getElementById('radioP').value);
//alert(x);
for(var i=0;i<table.elements.length;i++){
if(table.elements[i].type =='radio'){
if(table.elements[i].checked == true){
alert(table.elements[i].value);
}
}
}
}
I have corrected your script to work:
var i = 0;
window.myAdd = function() {
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency" + x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio" + i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i = i + 1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency" + x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio" + i);
i = i + 1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('mytable').appendChild(row);
x = x + 1;
}
window.myfunction = function(table) {
//var x = String(document.getElementById('radioP').value);
//alert(x);
//debugger;
for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i];
for (var j = 0; j < row.childNodes.length; j++) {
if (row.childNodes[j].type == 'radio') {
if (row.childNodes[j].checked == true) {
alert(row.childNodes[j].value);
}
}
}
}
}
<button onclick='myAdd()'>Add Radio Buttons</button>
<table id="mytable" name="mytable"></table>
<button onclick='myfunction(document.getElementById("mytable"))'>GET VALUE</button>
1) You have to use <label> element, e.g.:
<input id="radio_1" type="radio" value="1" />
<label for="radio_1">$</label>
<input id="radio_2" type="radio" value="2" />
<label for="radio_2">%</label>
2) You have to iterate through them. Considering all of the radios are within some div with class "container", you'll need something like this:
document.getElementById('get_values').addEventListener('click', function() {
var radios = document.querySelectorAll('.container input[type="radio"]');
values = {};
for(i=0; i<radios.length; i++) {
var radio = radios[i];
var name = radio.getAttribute('name');
if(radio.checked) {
values[name] = radio.value;
} else {
values[name] = values[name] || null;
}
}
alert(JSON.stringify(values));
});
See this fiddle: http://jsfiddle.net/andunai/gx6quyo0/
I am in the process of creating a quiz in javascript; At present I have a forward and back button which iterates through my questions! \0/
Also, I have managed to create some radio buttons and able to extract the first array of answers.
My problem is I can't iterate through the rest of answers (in the array) to match the questions...
This is the html:
<div class="container">
<div class="sixteen columns">
<div class="row"></div>
<h1>
Welcome to the <br>ultimate nerd quiz!
</h1>
<form id="f1" method="post">
<div id="question"></div>
</form>
<button class='navBackward'><</button><button class='navForward'>></button>
</div>
<!-- sixteen columns -->
</div>
<!-- container -->
This is the array:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0},
{
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3}, {}]; //etc
This is my JS: (This is what creates the initial radio buttons and the first set of answers)
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("f1");
for (var i = 0; i < len; i++) {
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
form.appendChild(radio);
form.appendChild(radioText);
}
}
createRadioButtonFromArray(item.choices);
This is what I am trying to use to display the other choices/answers in the array..
function answerFwd(){
var answerOutput = " ";
var itemAnswers = allQuestions;
if(currentAnswer <= itemAnswers.length){
currentAnswer++;
}
I suppose the problem is I am not properly outputting the array contents...
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices + "</p> <br/>";
update = document.getElementById("f1");
update.innerHTML = answerOutput;
}
I guess you should do something like that instead :
HTML : (-> add a responses' div, like the question's one)
<div class="container">
<div class="sixteen columns">
<div class="row"></div>
<h1>
Welcome to the <br>ultimate nerd quiz!
</h1>
<form id="f1" method="post">
<div id="question"></div>
<div id="responses"></div>
</form>
<button class='navBackward'>
<</button>
<button class='navForward'>></button>
</div>
<!-- sixteen columns -->
</div>
JS :
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses"); // <- reach the responses div instead of the form
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
// ...
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices); // <- Why don't you use the function you created earlier ????
/*
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices + "</p> <br/>";
update = document.getElementById("f1");
update.innerHTML = answerOutput;
*/
}
See the jsFiddle : http://fiddle.jshell.net/msieurtoph/uD29v/
(I did not implement the 'backward answers' function)
I suppose the problem is I am not properly outputting the array
contents...
Yes. Your contents is an array, so you would need to iterate it
var answerOutput = "<p>" + itemAnswers[currentQuestion].choices[0] + "</p> <br/>";
JSFiddle demo on how to iterate the array
I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
I would like for jQuery to dyanmically create a list of checkboxes based on the class/data present in divs. Essentially these checkboxes will filter through the products so that clicking a checkbox will show the products containing that tag in their div while avoiding any duplicate checkboxes.
Sample:
<div class="Shoes" data-size="Small" data-color="Black">
<h3>Nike</h3>
</div>
<div class="Belts" data-size="Medium" data-color="Black">
<h3>Belt</h3>
</div>
<div class="Shirt" data-size="Large" data-color="Blue">
<h3>Polo</h3>
</div>
<div class="Socks" data-size="Small" data-color="White">
<h3>Generic Socks</h3>
</div>
Expected output
Class Type
Shoes
Belts
Shirt
Socks
Size
Small
Medium
Large
Color
Black
White
Blue
Each checkbox needs to be able to hide/show the item.
JsFIDDLE
The code I have so far is from searching around/previous answers, however it is only creating 1 checkbox type which is for "class" and not creating multiple ones.
Try
jQuery(function ($) {
function createCheckboxes($els, attr) {
var props = {};
$els.each(function () {
props[$(this).attr(attr)] = true;
});
return $.map(props, function (val, key) {
var $chk = $('<input />', {
type: 'checkbox',
value: key
})
return $('<label />', {
text: key
}).append($chk)
})
}
$('span').append(createCheckboxes($('div'), 'class'))
$('span').append(createCheckboxes($('div'), 'data-size'))
$('span').append(createCheckboxes($('div'), 'data-color'))
});
Demo: Fiddle
Try this http://jsfiddle.net/LzmTA/1/
HTML
<div class="Shoes" data-size="Small" data-color="Black">
<h3>Nike</h3>
</div>
<div class="Belts" data-size="Medium" data-color="Black">
<h3>Belt</h3>
</div>
<div class="Shirt" data-size="Large" data-color="Blue">
<h3>Polo</h3>
</div>
<div class="Socks" data-size="Small" data-color="White">
<h3>Generic Socks</h3>
</div>
Javascript
$(document).ready(function(){
var goods = {};
var divs = $('div');
for(var i = 0; i < divs.length; i++){
var attributes = divs[i].attributes;
var item = {};
for(var j = 0; j < attributes.length; j++){
var attrName = attributes[j].name;
if(!goods[attrName]){
goods[attrName] = {};
}
goods[attrName][attributes[j].value] = 1;
}
}
printAttributes(goods);
console.log(goods);
});
function printAttributes(goods){
for(var group in goods){
var groupTitle = $('<h3>').text(group);
$('span').append(groupTitle);
for(var item in goods[group]){
console.log(item);
var sp = $('<label>').text(item);
var chk = $('<input>').attr('type', 'checkbox').attr('value', item).attr('attr', group);
chk.bind('change', function(){
filterGoods();
});
$('span').append(chk).append(sp);
}
}
}
function filterGoods(){
var separator = '|';
var chks = $('input[type=checkbox]:checked');
var filter = [];
//get filter
for(var i = 0; i < chks.length; i++){
var item = $(chks[i]).attr('attr') + separator + $(chks[i]).val();
filter.push(item);
}
//do filter
var hasAttr = false;
var divs = $('div');
for(var i = 0; i < divs.length; i++){
hasAttr = false;
for(var j = 0; j < filter.length; j++){
var filterParts = filter[j].split(separator);
if($(divs[i]).attr(filterParts[0]) == filterParts[1]){
hasAttr = true;
continue;
}
}
hasAttr ? $(divs[i]).show() : $(divs[i]).hide();
}
console.log(filter);
}