A way to store div id as string and send it to button click event via javascript
Is there a way I can send my div id to my asp delete button?
div.ID = String.Format("{0}", reader.GetString(0));
div.Attributes.Add("onclick", "return clickTheButton();");
protected void btnDelete_Click(object sender, EventArgs e)
{
//serverside code if confirm was pressed.
开发者_如何学编程 using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
// //PopulateWallPosts();
}
}
ASP:
<script type="text/javascript">
function confirm_delete()
{
return confirm("Are you sure you want to delete this comment?");
}
function clickTheButton() {
document.getElementById('<%= btn.ClientID %>').click();
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" OnClick="btnDelete_Click" runat="server" Text="delete"/>
I need to find a way I can send the div id to the button delete so I can use my sql syntax, atm I cant see a way of how to send it.
You want to use window.event.srcElement.id like this:
function clickTheButton() {
var Sender = window.event.srcElement;
alert("the item clicked was " + Sender.id)
}
for a button that looks like:
<input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>
you will get an alert that reads: "the item clicked was myButton.
Are you talking about a situation where you have a number of "delete" buttons, e.g. one for each comment, all hooked up to the same btnDelete_Click()
event handler?
You can put a CommandArgument
on the Button, e.g.:
<asp:Button ID="btn" OnClientClick="return confirm_delete();" OnClick="btnDelete_Click" runat="server" Text="delete" CommandArgument="123" />
And then pick this up in the event handler like so:
protected void btnDelete_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument;
}
Another approach would be to change your ASP button to a HTML button. Wire up an onclick event to the HTML button, and then call javascript function that then hits the server side Web Method.
You may want to re-approach your design, why is the div being selected causing a delete action.
If you want the reference to the actual element, not just its id, you can define your div as:
<div id="myDiv" onClick="btnClickHandler(this)">
...
</div>
This will pass the actual div element into your javascript function btnClickHandler
:
<script type="text/javascript">
function btnClickHandler(myDiv)
{
// do stuff with the div here
}
</script>
精彩评论