Can a button delete itself via a function? Javascript - javascript

I am creating a reset button, that when clicked should delete itself via a function.
But the deletion works only when fired by any element other than the button itself :( I mean the onclick doesn't work right.
function to create the reset button:
function createButton(context, id , value ,func)
{
var button = document.createElement("input");
button.type = "button";
button.id = id;
button.value = value; // text on button
button.onclick = func;
context.appendChild(button); // add the button to the context
}
the call to the create function:
createButton(document.body , "resetButton" , "Reset Game" , "resetGame();" );
the reset function which suppose to delete the button:
//reminder - id is "resetButton"
function resetGame()
{
var resetBottun = document.getElementById("resetButton");
var parentOfResetButton = resetBottun.parentElement;
parentOfResetButton.removeChild(resetBottun);
};
when I click the button , it should fire the resetGame() function and the button should disappear, but as I mentioned that only happens if I run the resetGame() function from any other place but not the onclick of the reset button.
hope you understand :/
please help

The value of button.onclick needs to be a function.
You are assigning "resetGame();", which is a string.
Pass resetGame instead of "resetGame()".

Related

onclick not working with dynamically-added buttons

Problem
Adding an event handler for click events with dynamically added buttons does not result in anything when clicked. I'm trying to build a build a chrome extension that dynamically adds a button.
Code
In content script (js)
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere in the document body
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function() {
alert("did something");
});
While the button does get rendered, clicking the button does nothing.
Notes
Event handlers for checkboxes work, though! Uses href = "javascript: function()"
var check = document.createElement("input");
check.id = "checkbox1";
check.type = "checkbox";
//if check is checked, then call removeSticky()
check.href="javascript:removeSticky()"
check.addEventListener('change', () => {
if (check.checked) {
removeSticky();
} else {
// nothing
}
});
document.getElementById("sticky").append(check);
//hidesthe sticky note
function removeSticky() {
window.alert("removeSticky() is working.");
// Removes an element from the document.
var element = document.getElementById("sticky");
element.style.display = "none";
}
However, doing the same with the BUTTON causes removeSticky() to be called whenever the webpage is fully loaded, when the user hasn't clicked anything yet.

Javascript - Issue on event listeners of classList

I have a "+" button that , when clicked, triggers the creation of a block with an input and 2 buttons, one for validating the input and one for removing it.
// My code looks almost like this :
addBtn.addEventListener('click', e => {
addClick++;
// All the elements of the same line (input and 2 buttons) have an int in common in their id string ==> addClick
// I'm missing all the declarations of the variables here
blockDiv.appendChild(posteInput);
blockDiv.appendChild(validateBtn);
blockDiv.appendChild(deleteBtn);
globalPostesBlock.appendChild(blockDiv)
let allDeleteBtn = document.getElementsByClassName('delete-button');
for (let i = 0; i < allDeleteBtn.length; i++) {
allDeleteBtn[i].addEventListener('click', e => {
// Retrieving the block with the same id
let deleteBtnId = parseInt((allDeleteBtn[i].getAttribute('id').match(/\d+/g)).toString());
let singlePosteBlock = document.getElementById(`poste-block-${deleteBtnId}`);
singlePosteBlock.remove();
}
})
}
The event listener represents the action of clicking the delete button so it can remove its entire containing block
I have the same logic for the validate button, but I'm using ajax in it.
Each time I create a new block, I want to create an event listener associated to this block, but all I found so far is an event listener with a loop on every buttons, so what happens is that the action triggers as many time as the block numbers because of the loop, but I don't know how to dissociate every event listeners.
If I have 3 blocks and I validate one input value which is being inserted in the DB afterwards, the value is being inserted 3 times.
Does this help ?
//id pool
let latestId = 0;
//retrive the button
var myButton = document.querySelector("button");
myButton.addEventListener("click", createKids);
//function declaration :: createKids
function createKids() {
latestId++;
//declare and initialization
let div = document.createElement("div");
let input = document.createElement("input");
let buttonSend = document.createElement("button");
let buttonDelete = document.createElement("button");
//append input & buttons to div
div.appendChild(input);
div.appendChild(buttonSend);
div.appendChild(buttonDelete);
//Some beautifying
buttonSend.innerText = "Send me";
buttonDelete.innerText = "Delete me";
//some logic
div.dataset.id = latestId;
//event handeling
buttonSend.addEventListener("click", sendItem);
buttonDelete.addEventListener("click", deleteItem);
//insert div
document.body.appendChild(div);
}
function sendItem(event) {
//do action and delete ?
let input = event.target.parentNode.querySelector("input");
//retrive data
let val = input.value;
let id = event.target.parentNode.dataset.id;
//disable input for fun ^^
input.disabled = true;
//console istead of send
console.log(id,val);
//handle some more
setTimeout(() => {
event.target.parentNode.remove();
}, 3000);
}
function deleteItem(event) {
event.currentTarget.parentNode.remove();
}
<p>Does this help?</p>
<button>Magic Button</button>

Event listeners/onclick events for buttons created in javascript function

I have a javascript button (button A), when it is clicked, it generates some new elements, including another button (button B). I would like a way to listen on button B, and then execute a separate function.
I tried editing Button B's 'onclick' attribute in javascript. This did not work.
HTML:
<input id="addTaskButton" type="submit" value="add task" onclick="addTaskFunction()"></input>
Javascript:
function buttonB()
{
// Not working
}
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = "buttonB()";
}
i am expecting the listener to perform buttonB when ran. Instead, i get no response.
Correct use is as follows
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = buttonB;
}
This works for me:
doneButton.onclick = function(){buttonB()};

Unable to attach click event to a dynamically created button

I have created a javascript function to dynamically create a button
function btn(d) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(d);
btn.appendChild(t);
btn.className = "myButton";
btn.onclick = alert('hello');
document.body.appendChild(btn);
}
when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks
you are calling the alert function not assigning a function
alert('hello'); // evals immediately.
btn.onclick = function () {
alert("Hello World"); // gives the button a click handler
// which can be called when clicked
};
Try doing it with jQuery, like so (per your jQuery tag on the question):
function btn(d) {
var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
alert('hello');
})
}
onclick should look like:
btn.onclick = function(){alert('hi');};
You are assigning the return value of alert('hello'); to the onclick, while it is expecting a function. The correct way without jQuery would be
if (btn.addEventListener)
btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
btn.attachEvent ('onclick',function(){ alert('hello');});

How to link the variable for the function to the button's variable?

Im new to javascript, is there any way to link my function's var to the button so that the function can be executed properly.I cant seem to link the function's variable to the button's id or even the button itself.
//My button
var btn1 = document.createElement('button');
btn1.textContent = questions[0].A
btn1.id = 'optionA'
document.body.appendChild(btn1);
btn1.addEventListener('click', fSubmit);
//My Function
var score=0;
function fSubmit(){
var correctanswer=btn1;
if(correctanswer.checked==true){
score++;
alert("Answer is correct! "+"Your Score is now "+score++)}
else{
alert("Answer is incorrect!")}
}
what I think you are trying to say is that you want to bind the "correctness" of a button's data to the score. What I would do is add a custom data attribute to each button containing 'true' or 'false' value for that button.
Like so:
btn1.dataset.correctOrNot = true
Then you test that value in your fSubmit function:
if (btn1.dataset.correctOrNot === true) {
// etc. etc.
}

Categories