I don't seem to be familiar with calling objects/elements from the DOM. In my code below i have a variable that collects all the added checkboxes. And now i want to collect only the checked ones once submit is pressed.
<form id="name_form">
<label for="name">First name: </label>
<input id="name" type="text" name="name">
<input type="button" id="btnAdd" value="add" onclick="newTextBox(this)"><br>
<input type="button" id="btnAdd" value="submit" onclick="printme()">
</form>
<script>
var instance = 1;
var allchecked = [];
var form = document.forms.name_form;
function newTextBox(element) {
form = document.forms.name_form; // call the form from DOM.
if (form.name.value === null) { // if name value in the form is empty.
console.log("if has: " +form.name.value); // prove it. :D
alert("Insert something in the name department. :)"); // alert me as well.
} else {
console.log("else has: " + form.name.value); // prove whatever else it might have.
var newInput = document.createElement("input"); // create a new input element.
newInput.id = "text" + instance; // add an id to it.
newInput.name = "text" + instance; // add a name to it.
newInput.type = "checkbox"; // add a type of checkbox.
newInput.checked = true; // turn it's checkbox to true.
var label = document.createElement("label"); // create a label for it.
label.id = "added"; // give an id to the label.
label.htmlFor = "text" + instance; // what is the label for.
label.innerHTML= "Hello " + form.name.value // insert values from the given name inside the form.
instance++; // increment the instance counter.
form.insertBefore(document.createElement("br"), element); // insert a brake tag after the add button element.
form.insertBefore(newInput,element); // insert the new input tag before the add button element.
form.insertBefore(label, newInput); // insert the label before the input tag element.
allchecked.push(label.innerHTML); // push value to the label created.
form.name.value = null; // clear the value in the name entry.
}
}
var chek = [];
function printme(){
for (i=0; i<form.elements; i++) {
if (form.elements[i].checked) {
chek.push(form.elements[i])
}
}
console.log(chek);
}
</script>
Once the Submit button is pressed I need the "chek" list to print with only checked values the way the "allchecked" list does. My "printme()" function is return an empty list. am I using elements wrong.
Aucun commentaire:
Enregistrer un commentaire