javascript function is not defined on button click - javascript

i am dynamically creating a button element and on its onclick event seting a function call but its always saying removeimg is not defined (removeimg is name of function being called on click of button). hers the code :
link :
http://shri-ram.lifekloud.com/pilot/step4.php
(tab add delete photos)
function removeimg(){
//make request to remove the name
document.getElementById(name).style.display = 'none';
document.getElementById(btn12).style.display = 'none';
}
function showUploadedItem (source) {
var list = document.getElementById("image-listalbum"),
li = document.createElement("li"),
img = document.createElement("img");
var btn = document.createElement('input');
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("class", "t-button");
var btnId = "btn" + source + "";
btn.setAttribute("id", btnId);
var func = "removeimg()";
btn.setAttribute("onclick", func);
img.src = 'uploads/'+source;
li.appendChild(img);
li.appendChild(btn);
list.appendChild(li);
}

Try
btn.onclick = removeimg;
rather than the string version you're doing.

Functions in Javascript have a scope, because they are essentially the same as any other Object. Since your function is defined inside the $(document).ready(); function it only exists in that scope. You'll have to declare it outside the ready() function to use it on the click of a button.

Related

Call class function with addEventListener

I want to access the doSomething function when the button that the render function creates is clicked? I get the following error instead.
Uncaught ReferenceError: getMethod is not defined
main.js
class Div {
constructor(div){
this.div = div;
}
init(){
this.getMethod();
}
getMethod(){
var div = this.div;
var createButton = {
render: function(){
let button = `
<button
onclick="getMethod.doSomething(this)"
type="button">
Click Me!
</button>
`;
div.innerHTML = button;
},
doSomething: function(){
// do something
}
}
createButton.render();
}
}
const div = new Div(document.querySelector('div'));
div.init();
There are multiple problems with your code.
Event handlers in html attributes (e.g.onclick) get run in global scope, yet getMethod is defined in a local scope, the scope of your class.
getMethod does not have a property doSomething, I think you meant to write createButton.doSomething
To fix the first issue you have to define your button as an object, not just as text. Since text doesn't know anything about scope. Then you can addEventListener to add a handler for the click event. In the handler callback function's you will have access to all variables in your local scope (the scope of the getMethod function)
class Div {
constructor(div){
this.div = div;
}
init(){
this.getMethod();
}
getMethod(){
var div = this.div;
var createButton = {
render: function(){
const button = document.createElement('button');
button.type = "button";
button.textContent = "Click Me!";
button.addEventListener('click', () => {
createButton.doSomething(this)
})
//clear inner html / delete all children
div.innerHTML = '';
div.appendChild(button);
},
doSomething: function(){
console.log("do something");
}
}
createButton.render();
}
}
const divElem = document.getElementById("mydiv");
const div = new Div(divElem);
div.init();
<div id="mydiv"></div>

HTML DOM createElement() [duplicate]

I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?
ex:
<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>
javascript:
var newButton = document.createElement("button");
???
in the end i want the new button to be the same as the existing one.
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "im a button";
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
createButton(document.body, function() {
highlight(this.parentNode.childNodes[1]);
// Example of different context, copied function etc
// createButton(this.parentNode, this.onclick);
});
};
Is that what you want?
You can also use the built-in setAttrbute javascript function.
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
Hope it will help

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');
function AddOrDeleteDiv(AddString, SectorString) {
//code
}
Do not use content attribute event handlers! Use event listeners instead:
var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
//code
}
Well js is known for not having nice methods for string joining and please try to use function parameter names not same as global variable names, it's not a nice thing to do.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(' + JSON.stringify(AddString) + ',' + JSON.stringify(SectorString) + ')');
function AddOrDeleteDiv(addStr, secStr) {
//code
}
or as #Thomas said you could use acutual javascript event handler like , not modifying attributes to assign event handler
AddButton.onclick = function(){AddOrDeleteDiv(AddString,SectorString);}

cannot add onclick event to dynamically created button

I have a script that is meant to dynamically create row items. My problem is the creation of the last cell item, a button. I have tried using onclick, setAttribute and attachEvent. But either the button is created or the onclick event is launched in the addGarageRow() function which creates the button and not the onclick event of the created button itself
function addGarageRow(tableID)
{
var table=document.getElementById(tableID);
rownum = rownum + 1;
var rowCount=table.rows.length;
var row=table.insertRow(rowCount);
var cell1=row.insertCell(0);
var element1=document.createElement("input");
element1.type="checkbox";
element1.name="chk[]";
cell1.appendChild(element1);
var cell2=row.insertCell(1);
var element2=document.createElement("input");
element2.type="text";
element2.id=rownum;
element2.name="garage_for[]";
cell2.appendChild(element2);
var cell3=row.insertCell(2);
var element3=document.createElement("input");
element3.type="text";
element3.id="amount"+rownum;
element3.name="garage_amount[]";
cell3.appendChild(element3);
var cell4=row.insertCell(3);
var element4=document.createElement("input");
element4.setAttribute("type", "button");
element4.id=rownum;
//element4.name="voucher";
//element4.onclick = alert("test");
//element4.setAttribute("onClick", alert("test");
//element4.attachEvent('OnClick',Hi());
cell4.appendChild(element4);
}
The handler should be wrapped in a function. i.e:
element4.onclick = function(){
alert("test");
}
You have to wrap the function you would like to be executed when the onclick event fires inside a function block. Check it out here: http://jsfiddle.net/qbhfdkq3/

Creating two elements using js and then having access to them later in another function

I am building some js functionality where I will be creating 2 elements on a page
var createBtn = function(
var btn = document.createElement('button')
...
)
var createIframe = function(
var iframe = document.createElement('iframe')
...
)
Pretty basic stuff, but later on I want to add an event listener to the button that will apply a style attribute to the iframe.
Something like:
var displayIframe = function(
Iframe.style['display'] = 'block'
)
button.addEventListener('click', displayIframe)
My question is how can I access the elements after I have created them without going through the annoyance of attaching classes to them and accessing them all over again that way. Is there someway of getting access to them in the create functions from the beginning.
Your codes is almost correct, but some changes is needed
var btn, iframe;
var createBtn = function () {
btn = document.createElement('button');
...
}
var createIframe = function () {
iframe = document.createElement('iframe');
...
}
Callback function
var displayIframe = function(){
iframe.style['display'] = 'block'
}
Attach click listener
btn.addEventListener('click', displayIframe);
Your mistakes:
you should declare btn and iframe as global variables to be accessible to other functions
function starts with { and ends with } not (, )
so far your codes is correct, without any error, but you won't see anything on the page because you have not attached your newly created elements to the body, For accomplish this try this function
function attachToBody(){
document.body.appendChild(btn);
document.body.appendChild(iframe);
}
In your example, I dont know why you use functions to create element, but you must have your point. Try this and let me know does this work for you.
//this is equivalent to: var btn = document.createElement('button');
var btn = (function(){
var btn = document.createElement('button');
return btn;
})();
var iframe = (function{
var iframe = document.createElement('iframe');
return iframe;
})();
document.getElementById("parentId").appendChild(btn);
document.getElementById("parentId").appendChild(iframe);
btn.addEventListener('click', function(){
iframe.style.display = "none";
});
var createBtn = function() {
var btn = document.createElement('button')
btn.setAttribute("id", "myButton");
return btn;
}
var createIframe = function() {
var iframe = document.createElement('iframe')
iframe.setAttribute("id", "myFrame");
return iframe;
}
document.body.appendChild(createBtn()); // Append button to body.
document.body.appendChild(createIframe()); // Append iFrame to body.
// Get Elements by Id.
var myButton = document.getElementById("myButton");
var myFrame = document.getElementById("myFrame");
// Add event listener.
myButton.addEventListener("click", function() {
myFrame.style.display = "none", false);
}

Categories