Dinammically button in jquery with window.open - javascript

I am trying to create a button dinnamically for adding a view before upload something to a database.
I am using jquery for my web, so if solution is in jquery, better.
Now I am trying a piece of code I found here: Creating Dynamic button with click event in javascript
This is how I adapted for my case:
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = 'button';
element.value = 'hello'; // Really? You want the default value to be the type string?
element.name = 'HELLO'; // And the name too?
element.onclick = window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');;
var foo = document.getElementById("registerButtonDiv");
//Append the element in page (in span).
foo.appendChild(element);
It adds the button (well, it is a simple button and not like the others in my webpage, I guess, something related to css)
But if I try to use something like I did about onclick event, it creates the button but don't add the onclick part. I tried changing quotes, not using them... many things so maybe now it is wrong. Don't take it so seriosuly, I just copy the latest version. With the alert on the example, it works fine.
What do I have to do to fix this?
I need to do this way because I have to pass some variables dinnamically filled to the other page and this is the simplest solution I found.

As onclick is an event, it needs a handler. And here you can handle the event using any handler which can serve you as your requirements.
element.onclick = function(){
window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
};
Demo

You need to pass a function reference to onclick:
element.onclick = function(){
window.open(...);
};
or using jquery:
var element = $('<input type="button" value="hello" name="HELLO">');
element.on('click', function() {
window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
});
$("#registerButtonDiv").append(element);
jsfiddle

Related

Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?
<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>
So it would look like this
<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>
The following Javascript code doesn't work though. Why?
<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>
onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.
Both are like "onclick", but it's not the same.
So, if you want to make thing work, do this:
document.getElementById("my_button").onclick = () => window.location.replace('/destination2');
onclick div property need function(callback) not a string
A simple way to do it would be by adding a listener and preventing the default behavior of the event
document
.getElementById('my_button')
.addEventListener('click', function (event) {
event.preventDefault();
window.location.replace('/destination2');
});
working example
element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.
If you want to change the attribute, make use of element.setAttribute("onclick", "...");
element.setAttribute("onclick", "window.location.replace('/destination2');");
Behaves similar to:
element.onclick = function() { window.location.replace('/destination2'); };
Another solution would be using the data-attributes which can be accessed by element.dataset.name.
Example:
<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>
And to change it:
my_button.dataset.path = "/otherPath";

Issue regarding javascript onclick

I am creating a link tag (anchor tag) dynamically using javascript.
There is a javascript function which will be fired by an event and it will create a javascript link.
I have already mentioned the required attributes for the newly created anchor tag using javascript. Now I have also mentioned an onclick event on that anchor tag.
The problem is
that the onclick event is fired during the anchor tag creation. And it is firing for that one time. Next time when I am clicking on the link, I am unable to get my desired result.
javascript code:
function waybill()
{
var mail_link = document.createElement("a");
mail_link.href = "javascript:void(0)";
mail_link.className = 'animated bounceInDown';
mail_link.innerHTML = "Mail Waybill";
mail_link.onclick = abc_test();
var holder_div = document.getElementById("holder");
holder_div.appendChild(mail_link);
}
function abc_test()
{
alert("mail link clicked");
}
I am getting the alert only once and without even clicking.
Please help me.
mail_link.onclick = abc_test() will invoke abc_test and assign its return value to mail_link.onclick.
If you just want to reference the function, and not call it, leave out the ():
mail_link.onclick = abc_test;
Adding event listeners is one of those things that a lot of old browsers are doing in their own way, and it's a bit messy to add support for all of them. Sicnce the question is tagged jQuery, you could do all of this in jQuery and have browser support handled for you:
$('<a/>', {
href: 'javascript:void(0);',
'class': 'animated bounceInDown',
text: 'Mail Waybill',
}).appendTo('#holder').click(abc_test);
The problem is that calling abc_test() will execute the function while using only abc_test will pass a reference to the function. in this case you need to change the line:
mail_link.onclick = abc_test();
with the line:
mail_link.onclick = abc_test;
It's because that you've invoked the function instead of referencing it.
mail_link.onclick=abc_test(); - This will invoke the function while initializing
mail_link.onclick=abc_test; - This will add a reference of the function to onClick, so that it will invoke the function while you click the anchor link.

JavaScript-How can I add an onClick function to a dynamically created button element?

Beginner programmer here-I am making an app that generates list items with a dynamically created button as a child of the 'li' element. I want to assign an onClick function to this dynamically created button but nothing seems to work. I have tried many ways, here is my most recent code.
var done = document.createElement("button");
done.onClick=function() {
alert("working");
};
done.innerText = "Finished!";
done.id = "deleteButton_";
The button generates fine but nothing happens when clicked. Any ideas? Thanks!
case matters
done.onClick=function() {
needs to be
done.onclick=function() {
better if you use addEventListener and not all browsers support innerText look into textContent
For use addEventListener, you could do something like
done.addEventListener('click', function (){
alert('working');
});
var iDiv = document.createElement('div');
iDiv.id = 'buttonDiv';
var button= document.getElementById('buttonDiv').innerHtml('<input type="button" onclick="myFunction(this)"');
function myFunction(button){
console.log(buton.id);
alert('pressed button with id :'+button.id);
}

Creating an element that can remove it self?

I'm building a lightbox as a school project, and I can't use jQuery. I've got an image. When you click it, Javascript makes a transparent div with the ID "overlay". I want the div to remove itself, or the parent to remove it but it doesn't work. I think it has to do with the fact that you can't link 'onclick' to an element that doesn't exists yet.
You have to remove the element from the parent. Something like this:
d = document.getElementById('overlay');
d.parentNode.removeChild(d);
Or you could just hide it:
d.style.display = 'none';
And, oh: you can add Javascript code to a (newly created) element by assigning a function to the onclick attribute.
d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };
You can remove the element like the following
var el = document.getElementById('div-02');
el.remove(); // Removes the div with the 'div-02' id
Click here for more details
Don't use the onclick handler in the tag, use Javascripts event functions such as addEventListener to dynamically add the event to the elements. You should also make sure that when you remove the elements you properly clean up all your references (in other words, unregister the event handlers).
I've got it :)
I was doing it like bart sad, but it didn't work. my code looked something like this:
image.onclick = function(){ *create overlay*};
overlay.oncklick = function() {*overlay.parentNode.removeChild(overlay)*};
the browser goes like wtf? cause it reads the code and thinks "i cant check if the user clicked a non-existing element."
So I did this:
image.onclick = function(){
*create overlay*
overlay.onclick = function() {*remove overlay*};
};

Google FastButton Multiple Use

I've implemented the Google FastButton script into a web page. Following:
Trying to implement Google's Fast Button
The code works great. My question is how do I implement this for multiple buttons. I have several buttons that are dynamically created. I don't want to define each button with its own function. Can I use this script with another function that passes some variable.
For example, <button id="quick" onclick="someFunction(24);">button</button>
Current implementation
new FastButton(document.getElementById('quick'), function() {
alert("hello");
});
<button onclick="onLayerClick(8)">8</button>
Here's one way to do it: According to the link you pasted, the FastButton prototype accepts a function as its second argument (this.FastButton = function(element, handler)) and passes the click event to that function. So if you do something like this:
HTML:
<button id="quick">24</button>
JS:
var myHandler = function(event) {
var el = event.target;
console.log(el.innerHTML);
}
new FastButton(document.getElementById('quick'), myHandler);
Then the myHandler() function will have access to the DOM element where the click event originated (event.target), which will be whatever button was clicked. So you'll have access to that button's innerHTML, or you could put a data-mynumber="24" attribute on the button and use el.getAttribute("data-mynumber") instead of el.innerHTML... However you want to identify the button is up to you.

Categories