Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top