I have a asp button that I want to be clicked by a javascript function when I click a regular html button. However when it gets to the button.click() there is no effect whatsoever. If I look in the debugger, everything else in the function acts as normal, and if I click on the asp button myself it runs the code I expect it to or if I call the joingameBtn_Click in the console it also properly clicks the button. I created the buttons dynamically on page load in a loop so that each has an onclick function that passes an id unique to it.
function joinGameBtn_Click(campaignid) {
var temp = document.getElementById('CampaignID');
temp.value = campaignid;
var button = document.getElementById("CampaignBtn");
button.click();
}
function createFunction(id) {
return function() { joinGameBtn_Click(id); };
}
//Where the button is created
var hoverbutton = document.createElement('button');
hoverbutton.id = 'hoverbutton';
var func = createFunction(campId);
hoverbutton.onclick = func;
After reading some other posts I saw that sometimes the dynamically created buttons could be the problem in that the event listener isn't tied to them. Some suggestions mentioned making sure the document was ready so I tried this as well to no avail.
$(document).ready(function() {
$(document).on('click', '#hoverbutton', function () {
$("#CampaignBtn").click();
});
});
EDIT: Here is the asp.net button in question.
<asp:Button ID="CampaignBtn" runat="server" Text="Button" style="display:none;" OnClick="joinGame_Click" ClientIDMode="Static"/>
Here is the server side button click function:
public void joinGame_Click(object sender, EventArgs e)
{
Session["campaignid"] = int.Parse(CampaignID.Value);
Response.Redirect("CampaignSession.aspx");
}
I changed my asp button to a regular html button which seemed to resolve the issue
<button onserverclick="joinGame_Click" runat="server" id="CampaignBtn" ClientIDMode="Static">Button</button>
Not sure if fixing the issues with duplicate id's played a role in it as well.
Related
I am using ajaxToolkit to show a modal popup. Inside the popup panel I have a repeater that has some controls from which one is a button that has an onClick event.
In the code behind I have declared the onClick function, and inside it i register a script.
string str = "Are you sure?";
this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);
and a javascript function in front page:
function ConfirmApproval(objMsg) {
if (confirm(objMsg)) {
return true;
} else {
return false;
}
}
If i use this exact code in a new web project everything works perfectly, but if I add it in the onClick event i spoke before nothing happens. Also, all the other things in the onClick method work perfectly no matter if i add or remove the registerScript part.
Anyone has any idea why this happens?
Why don't you add an OnClientClick event on your Button?
Something like:
OnClientClick="return ConfirmApproval('Are you sure?');"
should get the job done
I have an input as count named in a repeater with hdncount hidden input. And I have a server side button out of repeater. This script runs onblur event of count. I want to trigger server side button's click event if client click OK button on confirmation. What should I do to do that?
<script type="text/javascript">
function changeItemCount(input) {
var hdnCount = $(input).closest("div").find("input[id=hdnCount]").val();
var crrCount = $(input).closest("div").find("input[id=count]").val();
if (hdnCount != crrCount) {
var answer = confirm("Ürün adedi değiştirilecektir. Onaylıyor musunuz?");
return answer;
} else {
return true;
}
}
</script>
How to fire a button click event from JavaScript in ASP.NET
var answer = confirm("Ürün adedi değiştirilecektir. Onaylıyor musunuz?");
if(answer)
__doPostBack('btnSubmit','OnClick'); //use the server-side ID of the control here
Use OnClientClick together with OnClick
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" OnClientClick="return CheckGoJSEvents();" />
EDIT:
Didn't see that you had the function execute on the blur event. In that case you would not use the OnClientClick of the button. The answer posted by mattmanser would be correct.
If you wanted it to function from the button click, then you could use this method. Sorry for the confusion.
I have a DropDownList called "ddlCaseFiles".
I then have a script which I import that contains the jQuery .change() function to capture the event. Then I have 3 radio buttons which sorts the dropDownList. When the default radio button is loaded, then the event fires. But as soon as I select another radio button, then the event doesn't fire anymore.
Here is my DropDownList:
<asp:DropDownList runat="server" ID="ddlCaseFiles" DataSourceID="dsMyCaseFiles"
DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" />
and here is my jQuery .change():
$('#ddlCaseFiles').change(function () {
debugger;
$('#lblNextExhibitNumber').text('');
var temp = $(this).val();
});
Here is a snipper of what the radio buttons do:
protected void rbByFileName_CheckedChanged(object sender, EventArgs e)
{
ddlCaseFiles.DataSourceID = "dsCaseFilesReverse";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
}
protected void rbByFileID_CheckedChanged(object sender, EventArgs e)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
}
I have never used the .change() before. So maybe I am missing something
Looks like your CheckedChanged events of the radio buttons don't trigger the dropdown change event. The JS change event fires when the selected value of a drop down changes. This doesn't necessarily happen when you change the DataSourceID, does it?
I'm not sure how to trigger this in ASP. Perhaps ddlCaseFiles.SelectedIndexChanged()?
Otherwise, you could add a click event handler to the radios:
$('input[type="radio"].someCssClass').click(function(){
$('#ddlCaseFiles').trigger('change');
});
EDIT:
This is just a guess, but it looks like the CheckedChanged might be modifying the <select> element on the page. For example, is it reinserted every time DataSourceID changes?
Try changing your dropdown change event handler like this using the .on() function:
$('body').on('change', '#ddlCaseFiles', function () {
debugger;
$('#lblNextExhibitNumber').text('');
var temp = $(this).val();
});
Note: for better performance change $('body') to some container closer to the dropdown.
The .change() function attaches the change handler to an element on a page. If ASP removes an element and re-adds it later then the handler is gone.
A handler attached using the .on() function persists even if the element is removed. Read more here.
A more modern answer using jquery 3.6
$(document).on('change', "#ddlCaseFiles", function (e) {
debugger;
$('#lblNextExhibitNumber').text('');
var temp = $(this).val();
});
I have button
<UpdatePanel>
<asp:Button CssClass="btn-send" runat="server"
OnClick="SendMessage" Text="Send" />
</UpdatePanel>
Server side method
protected void SendMessage(object sender, EventArgs e){...}
I need to make little delay and show progress bar animation before POST. I would like to use javascript (jquery) for this.
How to make this delayed submit
1) without server delay
2) without second button with client script, which click server button?
You could try something like this...
<asp:Button runat="server" OnClick="SendMessage" Text="Send"
OnClientClick="return sendMessage(this);" />
<script type="text/javascript">
var sendBtn = null;
function sendMessage(btn){
if(sendBtn==null){
sendBtn = btn;
window.setTimeout(function(){ sendBtn.click(); }, 1000);
// DO YOUR VISUAL STUFF HERE
return false;
}else{
return true;
}
}
</script>
The idea is that the clicking of the button first stores the button object, sets a timeout to click the button, and then does the visual things you want to do.
Then after one second, the button is clicked again (this time not doing the timeout section)
(I have not had time to learn jquery yet, but I'm sure there is a simpler way to do this with it)
You can do this without jQuery, just using a regular Javascript setTimeout.
You can capture the onsubmit of your form, and then when you have submit (your button is pressed) you open your wait message of the page. So you add this line on Page_Load()
Page.Form.Attributes["onsubmit"] = "return AllowFormToRun();";
and the javascript:
<script>
function AllowFormToRun()
{
setTimeout(OpenWaitMsg, 10);
return true;
}
function OpenWaitMsg()
{
// open here the wait div
}
</script>
You should use Event.preventDefault() on the submit button click to prevent the page from submiting on click. Then start your progress animation, when its complete, call your form submit from the js.
$("form").submit(function(e){
var form = this;
e.preventDefault();
function animation(total,callback){
//perform your animation
callback();
};
animation(100,function(){
form.submit();
});
});
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;
});
Objects that fire .click and other functions are "collected" at load, if you add any elements after that, you need to either use .delegate or .bind to make the new elements also fire an event.
Events bubble up the DOM, ie. they'll get triggered for the element it happened on, as well as all of it's parents (up to the document node itself). This make it easy to solve your problem: just attach a click handler to the container of the buttons. jQuery makes it even easier to do it through it's delegate function, here's some example code:
$('#buttons').delegate('.delete_control', 'click', function(e) {
e.preventDefault();
e.stopPropagation(); // maybe you don't need these 2, you can remove them if so
if (confirm('Are you sure you want to delete that element?')) {
// make an ajax request to delete the image. alternatively you can submit
// a hidden form, with the controlid in an input, but this is way simpler.
$.post('/url/to/delete/control/by/id/' + e.target.id, function() {
$(e.target).remove(); // to delete the button when the request is done.
});
}
});
And here's a JSFiddle page showing the whole thing working: http://jsfiddle.net/8d7D4/