Create button by asp code and assign a javascript method

0

I am generating a button by code (I generate a button to delete, there is a button for each row of a dynamic table) and I need to generate an alert to prevent them from deleting information by mistake.

 Button boton = new Button();
 boton.Text = "Eliminar";
 boton.Click += new EventHandler(encontrarEliminar);

 private void encontrarEliminar(object sender, EventArgs e){
   . . .  CODIGO   . . . 
 }

I found that the best way to use a confirm is through javascript. Here is the javascript code:

 function Confirm() {
 var confirm_value = document.createElement("INPUT");
 confirm_value.type = "hidden";
 confirm_value.name = "confirm_value";
 if (confirm("Seguro que quieres eliminar?")) {
     confirm_value.value = "Yes";
 } else {
     confirm_value.value = "No";
 }
 document.forms[0].appendChild(confirm_value);
}

And it is assumed that the button would have to work correctly in this way:

<asp:Button ID="btnConfirm" runat="server" OnClick = "encontrarEliminar()" Text = "Raise Confirm" OnClientClick = "Confirm()"/>

The problem here is that you can only assign the button an event EventHandler type would like to know if there is any way to assign the javascript method or if there is another way to confirm.

    
asked by Ezequiel 01.07.2017 в 02:47
source

2 answers

0

In principle it is very easy to add javascript events, you just have to add an attribute to the button

Button btn = new Button();
btn.Attributes.Add("onclick", "confirm('Atención:xxx'))");

If you need to execute an action with the boolean that returns confirm, put it in a javascript function and call it in the onclik

var confirmar = confirm("Atención:xxx");
if (confirmar == true) {
} else {
}
    
answered by 06.07.2017 / 11:45
source
0

Try to put a class x to the button and assign the event click in javascript something like this:

<button class='btn'>
   test
</button> 

And in javascript you assign the click event:

var btn = document.getElementsByClassName('btn');

btn[0].addEventListener("click", function(){
   var confirm_value = document.createElement("INPUT");
   confirm_value.type = "hidden";
   confirm_value.name = "confirm_value";
 if (confirm("Seguro que quieres eliminar?")) {
     confirm_value.value = "Yes";
 } else {
     confirm_value.value = "No";
 }
});
    
answered by 01.07.2017 в 17:00