Removing a newly created element in JavaScript with creating a button - javascript

I have added a <p> to a <div> by this code and made a button, too.
var selectedId = this.value;
var divElem = $("#selectedItem");
var bElem = document.createElement("Button");
var bElemInnerHTML = document.createTextNode("Erase");
bElem.addEventListener('click', function () {
remove(this.value);
}, true);
bElem.appendChild(bElemInnerHTML);
var pElem = document.createElement("p");
var pElemInnerHTML = document.createTextNode(this.value);
pElem.setAttribute('id', selectedId);
alert(pElem.getAttribute('id'));
pElem.style.fontSize = '25px';
pElem.style.textAlign = 'center';
pElem.style.margin = '5px';
pElem.appendChild(pElemInnerHTML);
pElem.appendChild(bElem);
divElem.append(pElem);
I add to the button to run the remove function when clicked on
function remove(id){
var emad = document.getElementById(id);
emad.parentNode.removeChild(emad);}'
but it doesn't work.

bElem.addEventListener('click', function () {
remove(this.value);
}, true);
this.value in the above context refers to the Button element's value property(which is a string), not the ID of the Button. Also, you haven't defined the ID, so this.id would return ""(an empty string)
bElem.addEventListener('click', function () {
remove(this.id);
}, true);
You can modify remove() to accept an Object instead:
function remove(btn){
emad.parentNode.removeChild(btn);
}
bElem.addEventListener('click', function () {
remove(this);
}, true);

Related

Get click array item

trying to call an array from model.data in catListView.render(), it's showing perfectly but how to make the array item clickable, (i.e cat0 is clicked or cat2 is click).
$(function () {
var model = {
data: ["cat0", "cat1", "cat2", "cat3"],
}
var oct = {
init: function () {
catList.init();
},
getCat: function () {
return model.data;
},
};
var catListView = {
init: function () {
this.$catList = $("#cat-list");
catList.render();
},
render: function () {
var catList = this.$catList.html('');
var cats = oct.getCat();
for (var i = 0; i < cats.length; i++) {
var cat = cats[i];
var li = "<li>" + cat + "</li>";
addEventListener(li, "click", function(){
console.log(this.li.text());
});
catList.append(li);
}
}
};
oct.init();
}());
You should bind an eventListener to the EventTarget using EventTarget.addEventListener() when using pure DOM (see https://developer.mozilla.org/de/docs/Web/API/EventTarget/addEventListener for reference).
So in your code it would be:
var li = document.createElement('li'); // create an element instead if string
li.innerText = cat;
li.addEventListener("click", function(){
console.log(li.innerText);
});
Note that you also need to create a DOM element to bind events to.
The codes you typed cannot run... I try to guess what you want-
$li.bind("click", function() {
console.log("way 2", $(this).index());
});
https://codepen.io/linjiyeah/pen/QvzVQN

Incrementing this.clicks from a function inside a prototype function

This code displays two cats and the number of times each cat is clicked, how can I increment the .clicks property of each cat from inside the Cat.prototype.clickInc() method?
$(document).ready(function() {
var cats = [];
var Cat = function(id, image_path) {
this.id = id;
this.image_path = image_path;
this.clicks = 0;
};
Cat.prototype.clickInc = function() {
$('#'+this.id).click(function(){
this.clicks++;
return this.clicks;
});
};//use a closure here
var poly = new Cat("poly", "poly.jpg");
var chewie = new Cat("chewie", "chewie.jpg");
cats.push(poly);
cats.push(chewie);
for(i=0; i<cats.length; i++)
{
var catInfo = '<div class="cats"><div id="'+cats[i].id+'"><img src='+cats[i].image_path+'><h3>'+cats[i].id+'</h3></div><div class="clickNos"><span ="label">Number of clicks</span><span class="clicks">'+cats[i].clicks+'</span></div></div>';
$("#container").append(catInfo);
cats[i].clickInc();
}
});
this is not Cat within .click() handler. Also, you cannot return from an event handler. Use .next(".clickNos") with .find(".clicks") to select next .clicks element relative to clicked <img> element; set .html() of matched element to .clicks property of Cat instance.
Cat.prototype.clickInc = function() {
var _cat = this;
$('#' + this.id).click(function() {
_cat.clicks++;
$(this).next(".clickNos").find(".clicks").html(" " +_cat.clicks);
});
};
jsfiddle https://jsfiddle.net/9cykvbyv/1/

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

onclick passing on value of button

I want to send to my onClick function, the value of the button that pressed on it.
I have this function
numfunc = function (val) {
var t = document.createTextNode(val);
document.body.appendChild(t);
};
I have 5 buttons. I want them all to use this function onClick, but each send a different value,
their value.
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
one.onclick = numfunc;
two.value = "2";
and so on....
I'm trying to do this, on javascript not on the html file.
Thanks!
You can use this.value to get value inside you function numfunc, you don't need to send parameter, check example bellow.
Hope this helps.
numfunc = function (val) {
var t = document.createTextNode(this.value);
document.body.appendChild(t);
};
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
two.onclick = numfunc;
two.value = "2";
document.body.appendChild( one );
document.body.appendChild( two );
Can you use this code instead?
one.addEventListener("click", function () {
numfunc(this.value);
}, false);
two.addEventListener("click", function () {
numfunc(this.value);
}, false);

How to create dynamic instances of JQueryTE text editor

I am attempting to create a small program that incorporates dynamically created instances of this editor.
I have it working except for the ability to create a button that opens/closes the editor.
jsFiddle of what I've got so far.
"use strict";
$(document).ready(function() {
var createPad = $("#createPad").click(function () {
var body = document.getElementById("body");
var editorNumberCounter = 1;
var toggleOnOffCounter= 1;
var editorName = '.'+ (editorNumberCounter++);
var status = document.createElement('div');
status.className = "status";
status.id = "status";
var editorName= document.createElement('span');
editorName.className = "status";
editorName.id = "status";
$(body.appendChild(status));
$(body.appendChild(editorName));
var toggle = status.id + toggleOnOffCounter++;
$(editorName).jqte();
// settings of status
var jqteStatus = true;
$(toggle).click(function()
{
jqteStatus = jqteStatus ? false : true;
$(editorName).jqte({toggle : jqteStatus})
});
});
});
I made up some changes to your code an now seems to work.
I try to explain them point by point:
variabiles editorNumberCounter and toggleOnOffCounter must be globally scoped or you lose the incremented value
ID of elements (dynamically created or not) MUST be unique, so I create the div and span element considering the counter
for dynamically created elements you must use the bind method or the event will not be bind
the toggle property not exist! You must use the status property
the element onto JQTE is binded is get as next element after the clicked element
Code:
var editorNumberCounter = 0;
var toggleOnOffCounter = 0;
$(document).ready(function () {
var createPad = $("#createPad").click(function () {
var body = document.getElementById("body");
var editorName = '.' + editorNumberCounter++;
toggleOnOffCounter++;
var status = document.createElement('div');
status.className = "status";
status.id = "div_status" + editorNumberCounter;
var editorName = document.createElement('span');
editorName.className = "status";
editorName.id = "span_status" + editorNumberCounter;
$(body.appendChild(status));
$(body.appendChild(editorName));
$(editorName).jqte();
// settings of status
var jqteStatus = true;
$("#div_status" + editorNumberCounter).bind("click",function () {
jqteStatus = jqteStatus ? false : true;
$(this).next().jqte({
status: jqteStatus
})
});
});
});
Here is a working fiddle: http://jsfiddle.net/IrvinDominin/UfhNQ/14/

Categories

Resources