I have the following function that dynamically creates a bunch of checkboxes:
var drawGroups = function(){
var groups = document.getElementById("groups"); //groups element is a div
groups.innerHTML = "";
//groupList is an array containing strings
for(var i in groupList){
var groupName = groupList[i];
var cb = document.createElement('input');
cb.type = "checkbox";
cb.checked = true; //this seems to do nothing
groups.appendChild(cb);
groups.innerHTML += groupName + "<br/>"
}
}
Everything I read indicates cb.checked = true should check the checkbox, but it doesn't seem to do anything. How can I create the checkboxes in a checked state?
You need to set the defaultChecked property:
var groupList = ['foo','bar','baz','biz','boz'];
var drawGroups = function(){
var groups = document.getElementById("groups"); //groups element is a div
groups.innerHTML = "";
//groupList is an array containing strings
for(var i in groupList){
var groupName = groupList[i];
var cb = document.createElement('input');
cb.type = "checkbox";
cb.defaultChecked = true;
groups.appendChild(cb);
groups.innerHTML += groupName + "<br/>"
}
}
drawGroups();
<div id="groups"></div>
You could use the method setAttribute:
cb.setAttribute('checked', true);
Related
I like to add an input field to my list element for the timer im working on.
The problem is that it can read the function but doesnt display the object.
//Input Element Object
function inputElement() {
this.input = document.createElement("input");
this.input.id = "Timer " + count
this.input.type = "number";
this.input.max = 10;
this.input.min = 01;
}
function LI(id) {
this.li = document.createElement("li");
this.li.id = id;
this.li.id += count;
this.input = new inputElement();
this.li.innerHTML += this.input + ` set Timer`;
this.setting = document.getElementById("Version3");
this.setting.append(this.li);
}
I'm trying to make the inputs in my code appear as a NodeList but when I look in the console it just says "undefined" for the line that contains console.log(value);
Here's what I have:
var id = "word" + i;
var input = document.querySelector("input#" + id);
var inputs = document.querySelectorAll("input");
var value = inputs.value;
console.log(value);
you should use like this, Because document.querySelectorAll() give values in array.
var id = "word" + i;
var input = document.querySelector("input#" + id);
var inputs = document.querySelectorAll("input");
inputs.forEach((val, index)=>{
console.log(val.value);
}
)
A JSON like this is with me in a variable
var options_array =
[{"optionText":"1safsafs 1","optionDbId":1},{"optionText":"1safsafs 2","optionDbId":2},{"optionText":"1safsafs 3","optionDbId":3},{"optionText":" 1safsafs 4","optionDbId":4}]
I have to build a radio buttons with the items in this JSON and i am using the below code
var choice_div = document.getElementById("choice_div");
var options_array = "[{\"optionText\":\"1safsafs 1\",\"optionDbId\":1},{\"optionText\":\"1safsafs 2\",\"optionDbId\":2},{\"optionText\":\"1safsafs 3\",\"optionDbId\":3},{\"optionText\":\" 1safsafs 4\",\"optionDbId\":4}]";
console.log(options_array);
console.log(options_array.length); //174 is coming here instead of 4
for (i = 0; i < options_array.length; i++) {
var _text = JSON.stringify(options_array[i].optionText);
//console.log(_text); //all values are coming as undefined
var _value = JSON.stringify(options_array[i].optionDbId);
//console.log(_value);
var option_entry = makeRadioButton("selectedoption", _value, _text);
choice_div.appendChild(option_entry);
}
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
but this code is adding 170 items to the DIV and i am getting radio button contents as undefined . Not able to spot the reason?
I am expecting this to build 4 radio buttons with 4 options in it
you had some funny errors XD, first this the working one
$(document).ready(function () {
var choice_div = document.getElementById('mydiv');
data = [{ "optionText": "1safsafs 1", "optionDbId": 1 }, { "optionText": "1safsafs 2", "optionDbId": 2 }, { "optionText": "1safsafs 3", "optionDbId": 3 }, { "optionText": " 1safsafs 4", "optionDbId": 4 }]
$.each(data, function (key, item) {
var text = item.optionText;
var value = item.optionDbId;
console.log(value);
var option_entry = makeRadioButton("option" + key, value, text);
choice_div.appendChild(option_entry);
});
});
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
console.log("bot "+value);
label.appendChild(document.createTextNode(text));
return label;
}
then lets check what you did first you used JSON.stringify() with no reason , secondly you typed the json keys wrong thats was a little funny XD.
Javascript Object key is case sensitive. You've made some typos on your object keys.
optiontext -> optionText
optiondbid -> optionDbId
for (i = 0; i < options_array.length; i++) {
var _text = JSON.stringify(options_array[i].optionText);
//console.log(_text);
var _value = JSON.stringify(options_array[i].optionDbId);
//console.log(_value);
var option_entry = makeRadioButton("option" + i,_value, _text);
choice_div.appendChild(option_entry);
}
Update (11/10/2019)
The reason you are getting incorrect length is because you are logging JSON string length ( number of characters in your JSON string ) instead of the array length.
var choice_div = document.getElementById("choice_div");
// Get options_array as actual array instead of JSON string
var options_array = JSON.parse("[{\"optionText\":\"1safsafs 1\",\"optionDbId\":1},{\"optionText\":\"1safsafs 2\",\"optionDbId\":2},{\"optionText\":\"1safsafs 3\",\"optionDbId\":3},{\"optionText\":\" 1safsafs 4\",\"optionDbId\":4}]");
for (i = 0; i < options_array.length; i++) {
// Dont need to stringify here
var _text = options_array[i].optionText;
var _value = options_array[i].optionDbId;
var option_entry = makeRadioButton("selectedoption", _value, _text);
choice_div.appendChild(option_entry);
}
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
Good evening,
I have a problem with the construction of form in Javascript. For avoid the repetition of code I'd like to use the same function:
function addCheckBoxItem(p, name, value) {
// add checkbox
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.setAttribute("value", p);
newCheckbox.setAttribute("id", p);
newCheckbox.setAttribute("name", name);
newCheckbox.onchange = function(){
var cbs = document.getElementsByName(name);
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
this.checked = true;
// define the peer selected as choice
value = this.value;
// TODO: MY PROBLEM IS HERE
};
form.appendChild(newCheckbox);
// add label to checkbox
var label = document.createElement('label');
label.setAttribute("name", name);
label.htmlFor = p;
label.appendChild(document.createTextNode(p));
form.appendChild(label);
// add br tag to checkbox
var br = document.createElement("br")
br.setAttribute("name", name);
form.appendChild(br);
}
I call my function inside loop
for (i = 0; i < array.length; i++) {
addCheckBoxItem(array[i].key, nameItemCheckbox, peer_choice);
}
I know that value = this.value isn't possible because onchange event is Async but i want retrieve the value of this event and associate it with my param. I have find different response to this problem. One of this is: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference I have understand the basic concept but none of the example is relevant to my problem. Someone could help me?
EDIT - SOLUTION
Thanks to #Tibrogargan i have modified my function in this way:
for (i = 0; i < array.length; i++) {
addCheckBoxItem(form, array[i].key, form_peer_available_class, peer_choice, (value) => peer_choice = value);
}
and
function addCheckBoxItem(p, name, value, callback) {
// add checkbox
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.setAttribute("value", p);
newCheckbox.setAttribute("id", p);
newCheckbox.setAttribute("name", name);
newCheckbox.onchange = function(){
var cbs = document.getElementsByName(name);
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
this.checked = true;
// define the peer selected as choice
callback(this.value);
};
form.appendChild(newCheckbox);
// add label to checkbox
var label = document.createElement('label');
label.setAttribute("name", name);
label.htmlFor = p;
label.appendChild(document.createTextNode(p));
form.appendChild(label);
// add br tag to checkbox
var br = document.createElement("br")
br.setAttribute("name", name);
form.appendChild(br);
}
Pass callback into addCheckBoxItem like that
// accumulator
var data = {}
// callback
var storeData = (name, value, p) => data[name] = value;
// callback as third argument
addCheckBoxItem('data1', 'checkbox1', storeData);
addCheckBoxItem('data2', 'checkbox2', storeData);
addCheckBoxItem('data3', 'checkbox3', storeData);
Check full example here http://jsfiddle.net/gtqnc109/9/
I already have this JavaScript code inside a function called add().
var newinput = document.createElement('div');
newinput.innerHTML = "<br><input type='file' id='" + counter +
"'name='filename[" + counter +
"]' accept='image/jpeg' onchange='add()'>";
document.getElementById('asd').appendChild(newinput);
But instead of this innerHTML I want to do this new function:
var newinput = document.createElement('input');
newinput.id=x;
newinput.type="file";
newinput.name="filename";
newinput.accept="image/jpeg";
newinput.onchange=add();
Thus far, the new function creates an input like the innerHTML one of the first function, but doesn't add the onchange property (and the full created input even disapears, so I have to comment the .onchange();
Is there a way I can add the ".onchange" to the createElement var or create a JavaScript listener for a couple inputs like input.onchange() = function (){}? Thanks.
As it currently is, you are expecting add() to return a function. Do not invoke the function and just do:
newinput.onchange = add;
(function() {
function add() {
console.log("Added.");
}
function createFileInput(x) {
var newinput = document.createElement('input');
newinput.id = x;
newinput.type = "file";
newinput.name = "filename";
newinput.accept = "image/jpeg";
newinput.onchange = add;
return newinput;
}
document.body.appendChild(createFileInput('my-input'));
})();
Here's an example of what you were doing, and how it would work:
(function() {
function add() {
return function() {
console.log("Added.");
}
}
function createFileInput(x) {
var newinput = document.createElement('input');
newinput.id = x;
newinput.type = "file";
newinput.name = "filename";
newinput.accept = "image/jpeg";
newinput.onchange = add();
return newinput;
}
document.body.appendChild(createFileInput('my-input'));
})();