I am creating checkboxes through appendchild. I want to be able to check their state. I know the format is supposed to be document.form.checkboxname.value but no matter what combination of form name or checkbox name I use it doesn’t give me a response.
var myParagraph=document.getElementById("myLine");
myForm = document.createElement("FORM");
myForm.setAttribute("name", "myForm2");
mytable = document.createElement("TABLE");
var CB_Delete = document.createElement('input');
CB_Delete.type = "checkbox";
CB_Delete.name = "CB_Test";
CB_Delete.setAttribute("name", "CBTest2");
CB_Delete.value = 2;
CB_Delete.onclick = answer;
theCell.appendChild(CB_Delete);
To recap I want the answer function to give me an alert if the checkbox is checked or not. Thank you so much!
To clarify what do I replace the form and checkbox with in the alert(document.form.checkbox.value)?
CB_Delete.checkedshould work. See HTMLInputElement on MDN.jsFiddle Demo
To make your checkbox checked or unchecked, you would do
CB_Delete.checked = trueorCB_Delete.checked = falserespectively.checkedis an object property that is expected to have Boolean values.CB_Delete.checkedsimply queries its current value.In your event handler function, you can reference the element that currently handles the event as
this. So from the example in my previous jsFiddle:You could use
thisin youranswerfunction as well.You can read more about handling events on Quirksmode.
Note: Using
CB_Delete.onchangeis a quite old and not really recommended way to attach event handlers most of the time. The use ofCB_Delete.addEventListener('change', answer, false)is the right way to do this. Older IEs will have problem with it, but they haveattachEvent()instead. You can read about this technique and why to use it on Quirksmode (the article is 3 years old, take this into account when reading things like"Unfortunately few browsers support it at the moment."). To hide the browser differences, you can use a library like jQuery.