onclick of child element is causinf parent button to activate - javascript

I have 1 function that creates a new checkbox with a delete button to remove it. However when using onclick for the delete button, it causes the it to be deleted when the create checkbox is activated so that nothing is there in the first place.
<script>
var list = document.getElementById("list");
var i = 0;
function add_client(form) {
var div = document.createElement("div");
div.setAttribute("id", "div"+i.toString())
var check = document.createElement("input")
check.setAttribute("type", "checkbox");
check.setAttribute("id", "check"+i.toString());
var label = document.createElement("label");
label.setAttribute("for", "check"+i.toString());
label.setAttribute("id", "label")
txtNode = document.createTextNode(form.value);
label.appendChild(txtNode);
var br = document.createElement("br");
div.appendChild(check);
div.appendChild(label);
list.appendChild(div)
i++;
var del = document.createElement("input");
del.setAttribute("type", "button");
del.setAttribute("value", "Delete");
del.setAttribute("id", "del")
div.appendChild(del);
del.onclick = del.remove();
div.appendChild(br);
}
</script>
i know this is a DOM issue but cannot get around it.... any ideas?

Related

Is there a reason why my check mark box won't be selected when I click the span tag?

//init function
function init() {
createTaskElements();
}
//create elements and add them to the unordered list
//set attributes
function createTaskElements() {
const arrChores = ["Walk the dog", "Set dinner table", "Load dishwasher", "Empy Dishwasher", "Clean dinner plates"];
for (var i = 0; i < arrChores.length; i++) {
var task = document.createElement("LI");
task.id = "task";
var input = document.createElement("INPUT");
input.type = "checkbox";
input.id = "chore";
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
span.addEventListener("click", crossClick);
task.appendChild(input);
task.appendChild(span);
task.addEventListener("click", crossOut);
document.getElementById("itemsList").append(task);
}
}
//set the class name of the list item whenever it is clicked to completed
function crossOut() {
this.className = "completed";
}
function crossClick() {
}
W
hat I want to do when I click the span tag it checks the check box next to the element, but it isn't working.
I know the .checked method, but I'm not sure how I would get my function to work.
Replace
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
with
const label = document.createElement("label");
label.textContent = arrChores[i];
label.htmlFor = input.id;
You don't need to add any Javascript behaviour to that label as it already comes with the functionality you ask for.

How do you print out the index of a list element in an ordered list?

I have this code that on a button click, it spawns a group of elements inside a list. each of this groups is indexed in the ordered list in ascending order 1,2,3 etc.. i need these numbers to be stored for use in my database.
currently I haven't been able to find a way to identify the index number of each group in the list and thus add them as attributes.
This is my JS for spawning a group:
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
list.insertBefore(div, list.childNodes[0]);
set_index();
}
I've been using this JS code to add an index, but I cannot tell if it's working as I cant print out the index of a spawned list element.
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
This is my HTML:
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>
This is really bugging me, any help would be fantastic! Thanks :)
I change way to add li tag in ol tag and it show index.
var list = document.getElementById("spawnList");
list.appendChild(div);
var index = 1;
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
//var li = document.createElement("li");
list.appendChild(div);
console.log(index++);
//list.insertBefore(div, list.childNodes[0]);
//set_index();
}
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
if(lists != undefined){
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
}
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>

focus is not working on textarea

I am creating a page in which a user can add a question and its solution, he can delete the problem and can also edit it dynamically using DOM in javascript. I want that whenever user clicks on edit button the textbox which appears get autofocus.
This the javascript code of my page...
var questionText;
var answerText;
var questionArray=[];
var answerArray=[];
var i=0;
var j=10000;
function addProblem(){
var body = document.getElementsByTagName('body')[0];
questionText = document.getElementById('questionId').value;
answerText = document.getElementById('answerId').value;
questionArray.unshift(questionText);
answerArray.unshift(answerText);
var myContainer = document.getElementById('container');
var myDiv = document.createElement("div");
var questionLogo = document.createElement("p");
questionLogo.id = "questionLogo";
var textNode = document.createTextNode("Question:");
var question = document.createElement("p");
question.id = "question";
var questionDetail = document.createTextNode(questionArray[0]);
var deleteButton = document.createElement("button");
deleteButton.innerHTML = "Delete";
deleteButton.id = i;
var editButton = document.createElement("button");
editButton.innerHTML = "Edit";
editButton.id = j;
var answerLogo = document.createElement("p");
answerLogo.id = "answerLogo"
var ansTextNode = document.createTextNode("Answer: ");
var answer = document.createElement("p");
answer.id = "answer";
var answerDetail = document.createTextNode(answerArray[0]);
var mybr = document.createElement("br");
if(i==0){
myContainer.appendChild(myDiv);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answerLogo.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
else if (i > 0)
{
myContainer.insertBefore(myDiv,myContainer.firstChild);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answer.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
i++;
j++;
myDiv.childNodes[7].addEventListener("click", function(){
var deleteElement = document.getElementById(this.id);
deleteElement.parentNode.parentNode.removeChild(deleteElement.parentNode);
});
myDiv.childNodes[9].addEventListener("click",function(){
var editElement = document.getElementById(this.id);
var quesEdit = editElement.parentNode.childNodes[1];
var quesEditText = quesEdit.innerHTML;
var ansEdit = editElement.parentNode.childNodes[4];
var ansEditText = ansEdit.innerHTML;
var editDiv1 = document.createElement("div");
editDiv1.id = "editDiv1"
var quesTextArea = document.createElement("textarea");
quesTextArea.innerHTML += quesEditText;
quesTextArea.focus();
var saveButton1 = document.createElement("button");
saveButton1.innerHTML = "Save";
editDiv1.appendChild(quesTextArea);
editDiv1.innerHTML += ' ';
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
var editDiv2 = document.createElement("div");
editDiv2.id = "editDiv2"
var ansTextArea = document.createElement("textarea");
ansTextArea.innerHTML += ansEditText;
var saveButton2 = document.createElement("button");
saveButton2.innerHTML = "Save";
editDiv2.appendChild(ansTextArea);
editDiv2.innerHTML += ' ';
editDiv2.appendChild(saveButton2);
ansEdit.parentNode.replaceChild(editDiv2,ansEdit);
});
}
I have tried to focus the textarea using
quesTextArea.focus();
but its not working where questextArea is the name of the textarea. Please help how i can do it.
For the element could be got focused, it must be in the DOM when you invoke focus on it. You should invoke focus function after replaceChild function
editDiv1.appendChild(quesTextArea);
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
quesTextArea.focus();
I've created a simple sample as below link, you could check it
https://jsfiddle.net/pd9c6c7a/3/
Add autofocus attribute to the textarea element. So that whenever it is appended to the DOM, will get cursor activated in it.
The 'textarea' has not been added to window to be shown, an element must be part of the document object tree. In case that didn't work, add a 50ms delay.
setTimeout(function(){e.focus();}, 50);
Try the following approach:
var body=document.getElementsByTagName('body')[0];
var quesTextArea=document.createElement("textarea");
var button=document.createElement("button");
button.innerHTML = "click Me";
button.addEventListener("click",function(e){
e.preventDefault();
quesTextArea.focus();
});
body.appendChild(quesTextArea);
body.appendChild(button);
<html>
<body>
<body>
</html>
Try to add preventDefault.
var div = document.getElementById('parent');
var txt = document.createElement('textarea');
div.appendChild(txt);
txt.focus();
<html>
<head></head>
<body>
<div id="parent">
<input type="text" value="" />
</div>
</body>
</html>
The element must be in the DOM when you invoke the focus function. Move your focus() function after the appendChild() is invoked.
quesTextArea.innerHTML += quesEditText;
var saveButton1=document.createElement("button");
saveButton1.innerHTML="Save";
editDiv1.appendChild(quesTextArea);
quesTextArea.focus();

getting the value of checked checkbox to remove from div with DOM

I have a doubt in selecting and verify that the checkbox is checked in a div with id="div1" which in turn is added in another div with id = "box" and the result is checkbox -> div.id = div1 -> divbox.id = box
I have this base function to create checkbox and insert in div1 and add div1 to div box and it´s work and I don´t put the css code because don´t need
function createCheckBox() {
//count
var count = 0;
//create div1
var div1 = document.createElement('div');
div1.id = "div1";
div1.style.fontSize = "20px";
//div box
var divbox = document.createElement('div');
divbox.id = "box";
//checkbox
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "checkBox" + (count++);
checkbox.id = checkbox.name;
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode("checkBox" + (count++)));
var br = document.createElement('br');
div1.appendChild(checkbox);
div1.appendChild(label);
div1.appendChild(br);
divbox.appendChild(div1);
document.body.appendChild(divbox);
}
my doubt is select checkbox check and return if is checked or not
and in this function removeCheckBox I wanna get value of checked checkbox
in this way divbox.id = box -> div.id = div1 -> checkbox.checked and it´s not work
function removeCheckBox() {
//box
var divbox = document.getElementById("box");
//inside divbox select element with id = div1
var div1 = divbox.getElementById("div1");
for (var i = 0; div1.childNodes.length; i++) {
if (div1.childNodes[i].checked) {
alert("CheckBox is checked");
//remove from div1
div1.removeChild(div1.childNodes[i]);
} else {
alert("CheckBox is not checked");
}
}
}
any suggestion?
There is solution (description in code comment), based on all those comments :
function removeCheckBox() {
var box=document.getElementById('box');
//get all checked checkboxes inside box div
var chk=box.querySelectorAll('[type="checkbox"]:checked');
for(var i=0;i<chk.length;i++) {
box.removeChild(chk[i].parentNode); //remove complete div, who is parent of checked checkbox
}
}
function createCheckBox() {
//count
var count = 0;
var div = document.createElement('div');
div.id = "div1";
div.style.fontSize = "20px";
//div box
var box = document.getElementById('box');
//checkbox
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "checkBox" + (count++).toString();
checkbox.id = checkbox.name;
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode("checkBox" + (count++)));
var br = document.createElement('br');
div.appendChild(checkbox);
div.appendChild(label);
div.appendChild(br);
box.appendChild(div);
}
<input type="button" value="create" onclick="createCheckBox();" />
<input type="button" value="remove" onclick="removeCheckBox();" />
<br>
<div id="box">
</div>
You have many issues in the code. Your function should look something like this:
function selectCheckBox() {
//box
var box = document.getElementById("box");
//div1
var div1 = document.getElementById("div1"); //should be document not box
for (var i = 0; i < div1.childNodes.length; i++) {//should be condition i < div1.childNodes.length, also not spelling of length
if (div1.childNodes[i].type == 'checkbox') { //make sure it is a checkbox first
if (div1.childNodes[i].checked) {
alert("CheckBox is checked");
} else {
alert("CheckBox is not checked");
}
}
}
}

How to get spacing while making form in javascript?

I want adequate alignment of my form attributes. I tried using CSS, but dont know how to use it in javascript. I am new to development so any help will be appreciated.
<script type='text/javascript'>
function nextformdisplay()
{
var noee =document.getElementById('noe').value;
// document.getElementById('noe').value=noee-1;
var i;
for(i=0;i<noee;i++)
{
var btn = document.createElement("TEXT");
var t = document.createTextNode("EVENT NAME: ");
btn.appendChild(t);
document.body.appendChild(btn);
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
document.body.appendChild(x);
linebreak = document.createElement("br");
document.body.appendChild(linebreak);
var btn1 = document.createElement("TEXT");
var t1 = document.createTextNode("EVENT TIME:");
btn1.appendChild(t1);
document.body.appendChild(btn1);
var x1 = document.createElement("INPUT");
x1.setAttribute("type", "text");
x1.value="HH:MM:SS";
document.body.appendChild(x1);
linebreak = document.createElement("br");
document.body.appendChild(linebreak);
var btn2 = document.createElement("TEXT");
var t2 = document.createTextNode("PLAYER NAME:");
btn2.appendChild(t2);
document.body.appendChild(btn2);
var x2 = document.createElement("INPUT");
x2.setAttribute("type", "text");
document.body.appendChild(x2);
linebreak = document.createElement("p");
document.body.appendChild(linebreak);
}
}
</script>
Define CSS classes as you Desire and append these classes to them via JavaScript as you wish.
You can als.o use element IDs or inline css but Using CSS classes makes your life easier
e.g
css
.my-spacing-class{
padding:100px;
/* Other properties go here*/
}
javascript
var btn = document.createElement("TEXT");
btn.className += " my-spacing-class";
NOTE : The [SPACE] before my-spacing-class is intentional!!!!

Categories

Resources