Javascript confirm without code in code behind - javascript

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/

Related

Javascript button click has no effect

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.

Making postback using __doPostBack in asp for filtering grid

I am in the process of adding a filter to asp grid. I have succeeded in showing a text box for filtering in header.
I need to fire server code for filtering whenever user presses enter key in textbox.
So I started with adding event like
txtFilter.Attributes.Add("onkeyup", keyUpScript);
Then I added client script as
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerkeyUPScript", registerkeyUPScript, true);
where
string keyUpScript = "keyUPScript(event);";
string registerkeyUPScript = "function keyUPScript(e){\n"
+ "var unicode=e.keyCode? e.keyCode : e.charCode;\n"
+ "if(unicode == '13')\n"
+"{\n"
+" //PostBack code"
+"}"
+"}";
Now how could I postback when ever user enters a string in text box and presses enter key. I also need to rebind the filtered data back to grid
Any help will be appreciated.
You can try using this line of code to attach an onkeyup to your TextBox to only fire a postback event when Enter is pressed. Also, just in case you want to attach an OnTextChanged event for that particular TextBox, you can do so and that will be called as well when the page postbacks.
Use this in your Page_Load event :
TextBoxID.Attributes.Add("onkeyup", "return (event.keyCode==13);");
And this is the OnTextChanged event just in case if you want to attach :
protected void T1_TextChanged(object sender, EventArgs e)
{
//your logic goes here
}
Hope this helps.

Dispatching Custom Event and listening for it somewhere else (Bubbling) in IE

I can't seem to get this to work in JavaScript. I've tried using plain old JavaScript and also JQuery but nothing seems to work.
Here's my situation:
I have this PopUp "Panel" and in it I have a Button. The button has an event listener for click and I want that handler to fire off a custom event that the Panel will listen for. This is because I need to handle all the logic of the button click in the Panel.
Here's what I'm doing:
Before I launch the Panel I call a constructor for my "Class":
function PopUpStageAsssignmentTaker(content) {
PopUpStage.call(this);
this.allPagesAdded = false;
this.questionsCreated = [];// will be an array of pages that will be submitted
this.listLabel = null;
addAssignmentTakerParts.call(this);
this.popUpDiv.addEventListener("assignmentTakingSubmitEvent", handleAssignmentSubmit, true);
function handleAssignmentSubmit(event) {
alert("YESSS!");
}
}
This does quite a bit but just know that in the call to PopUpStage it creates the div that represents the Panel and saves that in this.popUpDiv. So I add a event listener to this.popUpDiv listening for some custom event that I'm making up.
Later on I have code that creates the content in the Panel and we have something like this:
SubmitQuestionTakingPage.prototype.makeContent = function(question) {
var questionWrapper = getQuestionWrapper();
var submitDiv = document.createElement("section");
submitDiv.innerHTML = "Pressing Submit will cause this Assignment to be submitted and you will be unable to make any changes after that. If this " +
"Assignment is automatically graded you will receive a Grade upon clicking submit. If this Assignment is not automatically submitted you must wait" +
" for the creator of this Assignment to assign you a Grade. To continue, please press Submit.";
submitDiv.setAttribute("class", "separatedSmaller");
questionWrapper.appendChild(submitDiv);
var submitButton = document.createElement("input");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("class", "fancyButton");
submitButton.addEventListener("click", handleSubmitButtonClick);
questionWrapper.appendChild(submitButton);
return questionWrapper;
};
function handleSubmitButtonClick(event) {
var event = document.createEvent("Event");
event.initEvent("assignmentTakingSubmitEvent", true, true);
window.dispatchEvent(event);
// $(this).trigger("assignmentTakingSubmitEvent");
}
So we create some content and in it we create a button that has a listener for click. In the click handler you can see how I fire off the event.
Problem: I'm reading that this does not work in IE under version 9+. What can I do in to make it work in all browsers? Is there a way?

jQuery .change() only fires once

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();
});

Disable asp.net button on when clicked

I have the javascript code below which disables an asp.net button during page postback. I also have a dropdownlist whose Autopostback property is set to true. Unfortunately, when i change the selectedItem in the dropdownlist, the button is disabled.
I want the Button disabled only when the page postback is caused by that same button, but not any other control on the page.
Some one please help on what change i should make to the code below to achieve this.
<script type="text/javascript">
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Using that prm reference, hook _initializeRequest
// and _endRequest, to run our code at the begin and end
// of any async postbacks that occur.
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Executed anytime an async postback occurs.
function InitializeRequest(sender, args) {
// Change the Container div's CSS class to .Progress.
$get('Container').className = 'Progress';
// Get a reference to the element that raised the postback,
// and disables it.
$get(args._postBackElement.id).disabled = true;
}
// Executed when the async postback completes.
function EndRequest(sender, args) {
// Change the Container div's class back to .Normal.
$get('Container').className = 'Normal';
// Get a reference to the element that raised the postback
// which is completing, and enable it.
$get(sender._postBackSettings.sourceElement.id).disabled = false;
}
</script>
Well, you're hooking into any asynchrous postback, sounds like you just want to hook into a particular button's postback.
However, you could fix this with minimal code adjustment, just by checking the ID of the control which triggered the postback before disabling it.
if (args._postBackElement.id == idOfTheButton)
$get(args._postBackElement.id).disabled = true;
Of course, if your button is a server-side button (asp:button), then you would need to either render out the client-id to the client from the server, or access it directly:
if (args._postBackElement.id == '<%= YourButton.ClientId %>')
$get(args._postBackElement.id).disabled = true;
As i said, there are better solutions than this (like only hooking into the postback event of the button, not any postback event).
But nonetheless, this should solve your problem.
You are referencing the id of the button here:
$get(args._postBackElement.id).disabled = true;
So all you need to do is to check the value of the ID prior to setting it to disabled:
if(args._postBackElement.id == '<%=MyButton.ClientID %>')
$get(args._postBackElement.id).disabled = true;

Categories

Resources