Javascript: How to get element by variable name within the function? - javascript

function(){
var btn=document.createElement("BUTTON");
var t=document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
document.getElementById(btn).onclick = function() {next()};
}
I know this is wrong because btn is a variable name, not an Id. Could someone help me change my 6th line of code so that I can run the function next() after onclick of btn?
**I need to have my commands inside this function, and cannot make an id outside this function.

You already have a reference to the element, so use that
function functionName() {
var btn = document.createElement("button");
var t = document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener('click', next, false);
}
FIDDLE

You have already button reference in btn variable so attach event with btn variable see blow
function(){
var btn=document.createElement("BUTTON");
var t=document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick = function() {next()};
}

btn is not an id, it is a variable which has the reference of the button object.
You can add onclick event directly to btn variable:
btn.onclick = next;

Related

How to add a jquery on click on a button that was created dynamically? [duplicate]

This question already has answers here:
Adding click event for a button created dynamically using jQuery [duplicate]
(4 answers)
Closed 1 year ago.
I have buttons that was created dynamically. How to add a jquery onclick on this button? I am still new to jQuery.
This is how I created my buttons in jQuery:
var language_add_button = document.createElement("button");
language_add_button.setAttribute("id", "btnRemoveLanguage_" + ctr);
language_add_button.setAttribute("class", "btn btn-padding");
language_add_button.setAttribute("type", "button");
This function creates buttons with id + ctr making them unique.
I know about
$("#btnRemoveLanguage_").click(function (e) {
RemoveLanguage(true);
e.preventDefault();
});
But since there is a counter when created, the buttons becomes btnRemoveLanguage_1, btnRemoveLanguage_2, etc.
How do I make sure that it is clicking the right button?
for dynamic event handling you can use: event-listener on parent element. Document on event delegation
but as for now i have used document.
$(document).on("click", "#btnRemoveLanguage_",function (e) {
RemoveLanguage(true);
e.preventDefault();
});
You would do:
$(document).on("click", "#your_id" , function() {
// do something $(this) is your button
});
This is my solution.
var language_add_button = document.createElement("button");
language_add_button.setAttribute("id", "btnRemoveLanguage_" + ctr);
language_add_button.setAttribute("class", "btn btn-padding");
language_add_button.setAttribute("type", "button");
/*******************************
* Append the following code *
*******************************/
$(language_add_button).click((e)=>{
RemoveLanguage(true);
e.preventDefault();
})
.click() will only bind to existing elements in the document aka Direct binding. In your case (the element gets created dynamically), you will have to use Delegated binding like .on().
var buttonID = "btnRemoveLanguage_" + ctr;
var language_add_button = document.createElement("button");
language_add_button.setAttribute("id", buttonID);
language_add_button.setAttribute("class", "btn btn-padding");
language_add_button.setAttribute("type", "button");
$(document).on("click", buttonID, function(e) {
RemoveLanguage(true);
e.preventDefault();
});
$(document).delegate(buttonID, "click", function(e) {
RemoveLanguage(true);
e.preventDefault();
});
source
You can use bind.
language_add_button.appendTo('/where you need to add/').bind('click', '/your callback function here/');
Isn`t it easier to connect the listener to class, not to ID? Or create a data value and connect to it. That will add a listener to any new element automatically.
const language_add_button = document.createElement("button");
language_add_button.setAttribute("id", "btnRemoveLanguage_" + ctr);
language_add_button.setAttribute("class", "btn btn-padding arrayOfMyButtons");
language_add_button.setAttribute("type", "button");
$(".arrayOfMyButtons").click(function (e) {
// any logic inside
});
I added a value on my button and changed it to class instead. This solved my problem
var language_add_button = document.createElement("button");
language_add_button.setAttribute("class", "btn btn-padding btnRemoveLanguage");
language_add_button.setAttribute("type", "button");
language_add_button.setAttribute("value", ctr);
$("#btnRemoveLanguage_").click(function (e) {
var ctr = $(this).val();
RemoveLanguage(true, ctr);
e.preventDefault();
});
With this, I only have 1 remove function and will work on ALL buttons with ctr as its value.

How to get a button element made in the DOM, run a function

I created a button element using javascript, and now would like to know how to find that element or select it and get it to call this function:
function test() {
alert("it works!");
}
This way maybe.
$("body").append("<button>Button</button>");
$("button").click(function(){
alert("it works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Use addEventListener:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("ok");
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener('click', test);
// My Test Function
function test() {
alert("it works!");
}
you can do the following to apply a click function to your button;
$(btn).on('click', test);
Another option with jquery:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("ok");
btn.appendChild(t);
document.body.appendChild(btn);
$('body').on('click', 'BUTTON', function(event) {
alert("it works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your button is an object once you created it dynamically. This means that you and easily assign properties and functions to it using the dot syntax. So, for example, if you want to give the dynamic button onclick functionality, you could do this:
btn.onclick = function() {
// add the JS function you want on the dynamic button here
};
var btn = document.createElement("BUTTON");
btn.onclick = function() { test(); }
var t = document.createTextNode("ok");
btn.appendChild(t);
document.body.appendChild(btn);
https://jsfiddle.net/k30nf9oo/
Have a look at below snippet.
var bIsCreated = false;
$(document).ready(function() {
$("#createNewButton").on("click", createNewButton);
$(document).on("click", ".newButton", function() {
alert("I am a new button");
});
});
function createNewButton() {
if (!bIsCreated) {
var $newButton = $("<button/>").addClass("newButton")
.html("I am a new button");
$newButton.appendTo(".container");
}
alert("I am a old button");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="createNewButton"> Create a new button</button>
</div>

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

Remove button and assign on click

I'm working on coding javascript and I'm kind of a noob here. This is my code:
<button onclick="test()">Click Me!</button>
<script>
function test()
{
var btn = document.createElement("BUTTON");
var name = document.createTextNode("Button");
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex();
}
ex()
{
}
</script>
I want to do two things, and I can't seem to find a solution. I want to:
use the function "ex" to remove the button that says "Click Me!"
assign btn.onclick to the button I just created.
Can anyone help me with this?
EDIT: Although all you guys are trying to help me, I'm not sure you guys are quite understanding the question fully. So, expanding on the first request:
I want to use the function "ex" to delete the button "Click Me!" I want this button to be deleted from the page, and no longer visible.
Second:
I want the btn.click in the function "test" to only be assigned to the button created in the function "test." I've noticed that when you click "Click Me!" it runs the function "ex."
try this one
<script>
function test() {
var btn=document.getElementsByTagName('button')[0];
btn.attributes[0].value="ex()";
btn.innerText="second function";
}
function ex() {
console.log("ex executer");
}
</script>
<button onclick="test()">
click me!
</button>
<button onclick="test()">
Click Me!
</button>
<script>
function test(){
var btn = document.createElement("BUTTON")
var name = document.createTextNode("Button")
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex;//() remove. btn.onclick is a handler i.e. a function object,
// not the result your ex() returns.
}
function ex(){//add function
this.style.color = 'red'; // makes text of the button red
// **ONLY if button IS clicked**
}
</script>

Javascript event listener firing on page load, not click event

I'm playing around with Javascript and created a class. On initializing the class, I add a button to a certain div and then add an event listener to that button for when it's clicked. What is happening though is that the function gets fired when the page loads, and not when the button is clicked. Here is my code:
function Photobank(){
this.photos;
this.addPhotoButton;
}
Photobank.prototype.init = function(){
var btn = document.createElement('button');
btn.id = "photoupload";
var t=document.createTextNode("ADD PHOTOS");
btn.appendChild(t);
this.addPhotoButton = btn;
var pb = document.getElementById('photobank');
pb.appendChild(this.addPhotoButton);
this.addPhotoButton.addEventListener("click", this.launchMediaManager(), false);
}
Photobank.prototype.launchMediaManager = function(){
alert("Launching Media Manager");
}
Am I doing something noticeably wrong?
You're calling the function rather than passing the function as an argument to addEventListener. Take the parentheses off the end of the function name:
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
It is because you are invoking the function and setting its result as the handler to the click event, instead set the function reference as the handler.
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);

Categories