Dynamic checkbox onclick is not working - javascript

I am creating dynamic checkboxes and want a function to be called every time I check any checkbox. The checkbox looks good but my onclick event does not work. Also if I do not pass 'this' to my function, my function gets called on load as well.
Below is my code:
for(var i=0; i<options.length; i++) {
var op = options[i].new_name;
var label = document.createElement("label");
var description = document.createTextNode(op);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "multiselectCheckbox";
checkbox.value = op;
checkbox.onclick= "getCheckedValues(this)";
label.appendChild(checkbox);
label.appendChild(description);
document.getElementById("multiselect").appendChild(label);
document.getElementById("multiselect").appendChild(document.createElement("br"));
}
Please let me know what am I doing wrong here.

The below snippet works. I suppose this is what you want to do. You need not pass this in the function and also call the function without ""
var options = [{new_name: "1"}, {new_name: "2"}]
for(var i=0; i<options.length; i++) {
var op = options[i].new_name;
var label = document.createElement("label");
var description = document.createTextNode(op);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "multiselectCheckbox";
checkbox.value = op;
checkbox.onclick = getCheckedValues;
label.appendChild(checkbox);
label.appendChild(description);
document.getElementById("multiselect").appendChild(label);
document.getElementById("multiselect").appendChild(document.createElement("br"));
}
function getCheckedValues() {
alert(this.value);
}
<div id="multiselect"></div>

Related

Not able to replace checkboxes Javascript

I am creating a mozilla add on for a web page. Using the attached Javascript code I am able to create checkbox. The checkbox should replace with other checkbox depending on the selected value in dropdown. Onclick on dropdown I am calling fun_sub_cat function which is creating checkbox and also replacing but it replace only once. For eg: If there are 2 option in dropdown 1 and 2, Selecting option 1 checkbox values should 1,2,3 and for option 2 checkbox values should be a,b,c.
On Click function it creates checkbox and changing the value for the first time replaces the checkbox value as well however when I click 3rd time on dropdown or change the value, it does not work. It attains the 2nd time changed checkbox values.
var k = 0;
function fun_cat_sub() {
console.log("Value Changed");
var Myarry = "";
if(document.getElementById('sub_cat').value == 'Password Reset'){
Myarry = check_list1;
if(k == 0){
console.log("creating checkbox for the first time");
k = k+1;
for (var i = 0; i < Myarry.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = "checkBox"+i;
checkbox.value = Myarry[i];
checkbox.class = "_class";
checkbox.appendAfter(br_3);
var lab_chk = document.createElement('label');
lab_chk.innerHTML = Myarry[i];
lab_chk.id = "lab_chk"+i;
lab_chk.value = Myarry[i];
lab_chk.style.marginLeft = "10px";
lab_chk.appendAfter(checkbox);
document.createElement('br').appendAfter(lab_chk);
}
}
else if(k != 0){
console.log("I am in 1st Loop");
checking(Myarry);
}
}
else {
Myarry = check_list2;
console.log("I am in 2nd Loop");
checking(Myarry);
}
}
function checking(Myarry){
console.log(Myarry.length);
for (var i = 0; i < Myarry.length; i++) {
var old_chk = document.getElementById('checkBox'+i);
var new_chk = document.createElement("input");
new_chk.type = "checkbox";
new_chk.id = "checkBox"+i;
new_chk.value = Myarry[i];
old_chk.parentNode.replaceChild(new_chk, old_chk);
var old_lab_chk = document.getElementById('lab_chk'+i);
var new_lab_chk = document.createElement('label');
new_lab_chk.innerHTML = Myarry[i];
new_lab_chk.style.marginLeft = "10px";
old_lab_chk.parentNode.replaceChild(new_lab_chk, old_lab_chk);
}
}

Pass contextual variable to onclick event handler as argument

*This is happening inside a larger block of code, in a for loop. See end of post for entire loop.
I've read all of the posts that seem to be about this subject, but I'm still lost.
I'm trying to assign an onclick event to a checkbox. The function being assigned to the onclick event needs to have access to a variable that is available in the scope where the checkbox is defined (idvariable).
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.onclick = function () {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I've tried every variation of inline and named functions, but I can't figure out how to give the clicked function access to idvariable. In this example above, the value of that variable is undefined.
Or, if I try it with this way:
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function (idvariable) {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I get an alert that says [object MouseEvent]. Same with the following where I removed the () from the method name I'm assigning to the onclick event:
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function () {
return clicked;
}(idvariable);
function clicked(id) {
return alert(id);
};
*entire loop:
for (var i = 0; i < parentChildList.length; i++) {
var row = table1.insertRow(-1);
var cell = row.insertCell(0);
cell.innerHTML =
"<h4 class=\"panel-title\"><a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse" + i + "\">" + parentChildList[i]["title"] + "</a></h4>";
if (parentChildList[i].children.length > 0) {
var row2 = table1.insertRow(-1);
var cell2 = row2.insertCell(0);
var table2 = document.createElement("table");
table2.className = "collapse";
table2.id = "collapse" + i;
cell2.appendChild(table2);
for (var j = 0; j < parentChildList[i].children.length; j++) {
var row3 = table2.insertRow(-1);
var cell3 = row3.insertCell(0);
var div = document.createElement("div");
div.className = "checkbox";
var label = document.createElement("label");
label.innerText = parentChildList[i].children[j]["title"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('subj', idvariable);
var idvariable = parentChildList[i].children[j]["subjectid"];
alert(idvariable);
input.onclick = function () {
return clicked(this.getAttribute('subj'));
};
function clicked(id) {
return alert(id);
};
cell3.style.padding = "0px 0px 0px 10px";
cell3.style.fontsize = "x-small";
cell3.appendChild(div);
div.appendChild(label);
label.insertBefore(input, label.childNodes[0]);
}
}
}
onclick handler receives Event object. If a handler attached as elem.onclick=handler then the element is available inside the handler as this. So this is workaround.
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('data-subj', idvariable);
input.onclick = function () {
return clicked(this.getAttribute('data-subj'));
};
function clicked(id) {
alert(id);
};
You will have to append the checkbox to some existing element first, using the following code.
var element = document.getElementById("one").appendChild(input);
Then you can get the parent by using something like the following...
var x = document.getElementById("someId").parentElement;
where x will contain the parent element.
This link https://stackoverflow.com/a/9418326/886393 is about custom data in an event (custom event). Hope that helps.
Thanks
Paras

create and populate with DOM a checkbox list with array values in javascript

I have an array of animals ... how do I manage to create a checkbox list in javascript and fill each with a name of the animals who are in animals array and display them in html.
My my attempt code:
var lengthArrayAnimals = animals.length;
for (var i= 0; pos < tamanhoArrayDiagnosticos; pos++) {
var checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkbox");
checkBox.name = diagnosticos[i];
}
Here's one way (pure JavaScript, no jQuery):
var animals = ["lion", "tigers", "bears", "squirrels"];
var myDiv = document.getElementById("cboxes");
for (var i = 0; i < animals.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = animals[i];
myDiv.appendChild(checkBox);
myDiv.appendChild(label);
label.appendChild(document.createTextNode(animals[i]));
}
https://jsfiddle.net/lemoncurry/5brxz3mk/
I hope this is what you expected.
$(document).ready(function(){
var animals=["cat","dog","pikachu","charmaner"];
$.each(animals,function(index,value){
var checkbox="<label for="+value+">"+value+"</label><input type='checkbox' id="+value+" value="+value+" name="+value+">"
$(".checkBoxContainer").append($(checkbox));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="checkBoxContainer"></div>

Checkbox to change textdecoration input field

With javascript, i want my checkbox to change the text decoration of an input text field.
So when it's checked, the text in the input text field turns bold.
Remember i'm learning so i'm not a pro as you guys ;)
I thought something like this;
var checkbox = create("input");
checkbox.type = "checkbox";
checkbox.id = "checkboxId" + counter;
div.appendChild(checkbox);
checkbox.onClick="boldChange(this)"
var input = create("input");
input.type = "input";
input.id = "inputId" + counter;
div.appendChild(input);
function boldChange()
var boldgroup = document.getElementsByName(el.name);
for (var b=0; boldgroup[b]; ++b)
inputId.style.textDecoration = boldgroup[b].checked ? 'bold' : 'none';
}
How can i make this work?
Thank you so much in advance
Here is a working JSFiddle example based on your code above: Link to example
Code snippet: (place below </body> so that all of DOM is loaded)
<script>
var div = document.getElementById('div'),
counter = 0;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkboxId" + counter;
div.appendChild(checkbox);
checkbox.onclick = boldChange;
counter++;
var input = document.createElement("input");
input.type = "text";
input.id = "inputId" + counter;
div.appendChild(input);
function boldChange() {
input.style.fontWeight = (checkbox.checked)?'bold':'normal';
}
</script>

Creating the checkbox dynamically using JavaScript?

I am trying to create a checkbox dynamically using following HTML/JavaScript. Any ideas why it doesn't work?
<div id="cb"></div>
<script type="text/javascript">
var cbh = document.getElementById('cb');
var val = '1';
var cap = 'Jan';
var cb = document.createElement('input');
cb.type = 'checkbox';
cbh.appendChild(cb);
cb.name = val;
cb.value = cap;
cb.appendChild(document.createTextNode(cap));
</script>
You're trying to put a text node inside an input element.
Input elements are empty and can't have children.
...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));
container.appendChild(checkbox);
container.appendChild(label);
The last line should read
cbh.appendChild(document.createTextNode(cap));
Appending the text (label?) to the same container as the checkbox, not the checkbox itself
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
/* worked for me */
<div id="divid"> </div>
<script type="text/javascript">
var hold = document.getElementById("divid");
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "chkbox1";
checkbox.id = "cbid";
var label = document.createElement('label');
var tn = document.createTextNode("Not A RoBot");
label.htmlFor="cbid";
label.appendChild(tn);
hold.appendChild(label);
hold.appendChild(checkbox);
</script>

Categories

Resources