Splice function in javascript not working properly - javascript

The button on click should generate radio buttons, one at a time, but I have an issue with the text node that should stick with the radio buttons. Here's part of the code:
var array = [];
items = document.getElementById("items").value.split(",");
for (var i = 0; i < items.length; i++) {
array.push(items[i]);
}
type = document.getElementById("type");
container = document.getElementById("container");
if (type.value == "radio") {
radio = document.createElement("input");
radio.setAttribute("type", "radio");
for (var i = 0; i < array.length; i++) {
text = document.createTextNode(array[0]);
container.appendChild(text);
container.appendChild(radio);
array.splice(0,1);
}
}
So this is the result, but I want the first radio button to have a value of '1', the second '2' etc.

First you don't need array the items array already contains the elements you want from text input
Also no need to slice/splice any array
Your problem was that you have to create another unique radio element for every element so what you did is appending same radio element many times which result in adding the radio button once
so you have to put
radio = document.createElement("input");
radio.setAttribute("type", "radio"); inside the for loop . . . . 😘😘
function Z() {
items = document.getElementById('items').value.split(",");
type = document.getElementById("type");
container = document.getElementById("container");
container.innerHTML = "";
if (type.value == "radio") {
for (var i = 0; i < items.length; i++) {
text = document.createTextNode(items[i]);
radio = document.createElement("input");
radio.setAttribute("type", "radio");
container.appendChild(text);
container.appendChild(radio);
}
}
}
<input onkeyup="Z()" id="items"> type:
<select id="type">
<option value="radio">Radio</option>
<option value="checkbox">Text</option>
</select>
<div id='container'></div>

Related

Generating radio buttons with label

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

Value of Radio buttons using Loop and add HTML text to it

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/

Trying to create a todo list with delete function

Im new to javascript and coding in general, I'm trying to make a simple to do list but cant get the delete button to delete all the checkboxes, it will only delete the first checkbox made. Thanks guys.
http://jsfiddle.net/fbct3oL7/1/
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
listItem.id = task;
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
checkbox.name = task;
checkbox.id = "checkbox";
document.getElementById('place').appendChild(listItem);
document.getElementById(task).insertBefore(checkbox, listItem.firstChild);
}
function deleteCheckBox() {
while (document.getElementById('checkbox').checked === true) {
var itemNode = document.getElementById(checkbox.name);
itemNode.parentNode.removeChild(itemNode);
}
}
I've modified your code, eliminating unnecessary id and name attributes, and updated the deleteCheckBox function to cycle through all the li in the ul.
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
}
function deleteCheckBox() {
var ul = document.getElementById('place');
var li = ul.children;
for (var i=0; i < li.length; i++) {
while(li[i] && li[i].children[0].checked) {
ul.removeChild(li[i]);
}
}
}
<div id="list">
<input type='text' id='textinput' />
<input type='button' onclick='taskadd()' value='Add to list' />
<input type='button' onclick="deleteCheckBox()" value='Delete' />
<ul id="place"></ul>
</div>
I also forked and updated your Fiddle: http://jsfiddle.net/JohnnyEstilles/gtpdLkLq/.
You give every checkbox the same id, and the getElementById method only returns the first matching element.
If you want to get all checkboxes and delete the checked ones you could start by doing like this. (Please notice that this code is written freehand and untested)
var inputs = document.getElementsByTagName("input");
for(i=o; i < inputs.length; i++){
if(inputs[i].type == "checkbox" && inputs[i].checked){
inputs[i].parentNode.removeChild(inputs[i]);
}
}
First get all element with the tag "input", then check if they are of checkbox type and checked.

Javascript -> Attempting to dynamically add radio buttons from an array

So I'm working on my very first 'real' JavaScript project -> the famed Quiz app :)
I'm passing questions and answers via an array, and I want make sure to allow for a variable number of answer options. To do this, I'm using a For loop and the createElement method to add and populate the appropriate HTML for each answer in the array. To my eyes, what I've built actually works great. And after running the function I can see the resultant HTML elements in the right place and with all the appropriate tagging in my console. However, the inner DIV text won't render on screen! Very confused. What am I missing? Please help!
My JS code:
<body>
<form id="form1">
</form>
<script>
var answers = ["answer1", "answer2", "answer3", "answer4", "answer5"];
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("form1");
for (var i = 0; i < len; i++){
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
form.appendChild(radio);
radio.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
}
}
</script>
</body>
And here's a screenshot of my console AFTER I run the function, for reference:
You're plan is nearly working but Input elements have no content! So the div's will not be rendered at all!
Create a div that contains your radio button and the input text on the same level:
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
radioText.innerHTML = array[i];
radioText.appendChild(radio);
form.appendChild(radioText);
Add label after or before radio button. Label will let you check radio button by clicking on it's text
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("label");
radioText.id = "c" + i;
radioText.setAttribute("for", "choice" + i);
radioText.class = "choiceText";
form.appendChild(radio);
form.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
<input> cannot contain any DOM elements or DOM nodes. But if you want to have checkboxes associated with some text, I suggest you to use <input> with <label for=""> where label.for is name of input element. For combining them you can put them into some container(i.e. <div>):
By default on label with set property for raises click event on element with the same name property value as for property value. This means that you do not need to add additional click event handlers for <label> elements.
var checkId = 1;
var container = document.createElement("div");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices"+checkId;
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var label = document.createElement("label");
label.innerHTML = array[i];
// Set attribute for
label.setAttribute("for","choices"+checkId);
//Increase counter for check element name.
checkId++;
container.appendChild(radio);
container.appendChild(label);
form.appendChild(container);

How can I disable a button on my page if I know only the name of that element?

I have the following HTML:
<button name="darkBlue" onclick="setThemeColor(this.name)">Blue</button>
<button name="black" onclick="setThemeColor(this.name)">Black</button>
and this script:
if (localStorage.buttonColor) {
var themeButtons = document.querySelectorAll(".theme");
for (var button in themeButtons) {
themeButtons[buttons].removeAttribute("disabled");
}
// I need here to disable the button with the name that matches localstorage name
}
I already have in place a way to remove the disabled from all the buttons. But how can I after that disable the button which has the same name as the localStorage.buttonColor without using jQuery?
Also could I do all this in the for (var button in themeButtons) loop? If I could do that it might be even more clean of a solution.
If there's only one button:
document.querySelector('button[name="' + localStorage.buttonColor + '"]').disabled = true;
Or:
var el = document.getElementsByName(localStorage.buttonColor);
if (el) {
el[0].disabled = true;
}
If there are multiple elements:
var all = document.querySelectorAll('button[name="' + localStorage.buttonColor + '"]');
for (var i = 0, len = all.length; i<len; i++){
all[i].disabled = true;
}
If there are multiple buttons, and you need to enable the ones that don't share the name of the localStorage.buttonColor:
var buttons = document.getElementsByTagName('button'),
buttonsQSA = document.querySelectorAll('button');
// iterate over whichever collection you prefer to use
for (var i = 0, len = buttonsQSA.length; i<len; i++){
buttonsQSA[i].disabled = buttonsQSA[i].name == localStorage.buttonColor;
}

Categories