Javascript confirm without code in code behind
I have a page with dynamically added imagebuttons, and i want them to send a confirm when you click them(for deletion).
Since they are dynamic i cant code anything in a .click event.
Hows the best way to do this? check if true or false and then send it to a delete function in code behind with the control as parameter? or any other way?
Thanks
If you want to be able to cancel the submission, set the OnClientClick
property to the string "Return" and the function name. The client script can then cancel the submission by returning false
.
check imagebutton clientclick property.
void Button1_Click(Object sender, EventArgs e)
Label1.Text = "Server click handler called.";
End Sub
your dynamic generated imagebutton should be somewhat like this: Create commman event hadler for all imagebuttons and set the id
of these imagebutton to the primary key value.
check Respond to Button Web Server Control Events in Client Script for details:
You can create a custom imagebutton usercontrol that will provide the delete functionality on click event. On ItemRowCreated or GridView RowCreated events assign event hadler to these dynamically added control.
If they are not in any databind control then simple assign there properties at run time.
protected void Page_Init(object sender, EventArgs e)
{
ImageButton btn = new ImageButton();
btn.ID = "1";
btn.ImageUrl = "http://icons.iconarchive.com/icons/deleket/button/256/Button-Fast-Forward-icon.png";
btn.OnClientClick = "return confirm('Ready to submit.')";
btn.Click += new ImageClickEventHandler(btn_Click);
this.form1.Controls.Add(btn);
}
check the control id in event handler.
private void btn_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
Response.Write("<script>alert('Image button with id = " + btn.ID + "clicked');</script>");
}
and then perfom delete operation
It's easy to do with jQuery (a javascript framework), even if want to do with pure JavaScript, you need to add a class to all your delete image button and add an handler to it
Using jQuery, just use this:
$(".deleteImageButton").bind("click", function() {
var res = confirm("Are you sure you want to delete?");
return res;
});
在加载时“收集”了.click
和其他函数的对象,如果在此之后添加了任何元素,则需要使用.delegate
或.bind
使新元素也触发事件。