We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.
Related
I would like to use a toggle button in my toolbar but I can't find out how to retrieve the state.
Could someone explain me how to do that?
<%= Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(buttonsItem =>
{
buttonsItem.Add().Type(CommandType.Button).Text("Unconfirmed").Id("isConfirmed").Togglable(true).Toggle("isConfirmed");
})
%>
function isConfirmed(e) {
if (document.getElementById("isConfirmed").checked == true)
{
alert("yes")
}
else
{
alert("no")
}
Regards
In the toggle event itself you can look at e.checked to determine the toggle state.
In this example I am also changing the text of the button depending on the checked state:
function isConfirmed(e) {
var text = e.checked ? "Confirmed" : "Unconfirmed";
e.target.text(text);
alert(text);
}
If you want to get the state later (e.g. when a submit button is clicked), you can check the selected option of the button object ($("#isConfirmed").data("button").options.selected):
$("#btnIsConf").on("click", function(){
if ($("#isConfirmed").data("button").options.selected){
alert("Yes");
} else {
alert("No")
}
});
DEMO
You do not need to look the dom element back up to determine the state i.e. the checked property.
It is available in your e parameter as follows:
function isConfirmed(e) {
if (e.checked) {
alert("yes")
}
else {
alert("no")
}
}
Screen Grab
I have multiples buttons on my asp.net page, I need to disable certain button(s) on page load.
Which button will be disabled is determined by my database, which I successfully retrieved.
For example, I have retrieved the ID "B01", and in my page there's a button's ID named "B01"
I have to disable this button on page load, how do I do it?
Just do - if(!IsPostBack){id.Enabled = false;} on page load and make sure button must be like <asp:Button ID="btn_dn" runat="server" >Button</asp:Button> button need runat="server"
As you are using simple button so it will not take any c# command so you have to use asp button or javascript to disable button
for simple button <input type="button" disabled="disabled" value="B01" /> Or
<button id="B01" runat="server" disabled="disabled">B01</button>
You can do this in Page_Load event
string id="B01";
(FindControl(id) as Button).Enabled = false;
There are challenges with FindControl and "nested" controls. I believe you need a recursive find control function have a look at the tutorial.
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
then call it using
var x = FindControlRecursive(this.Master,"ButtonName") as Button;
x.Visible = false or x.Enabled = false
Tutorial Link is here....
in page load:
string id = "A01";
var q = from R in db.Reservations
where R.Flight_NO == id
select R.Seat;
foreach (var item in q)
{
Button b = (Button)this.Master.FindControl("main").FindControl(item);
if (b!=null)
{
b.Enabled = false;
}
}
this does automatically disable button with that specific ID on page load
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
In asp.net (c#) how can I find out which asp:button triggered the postback?
I am using it for dynamic controls and want to do a different process on pageload for different buttons. I have tried looking at __EVENTARGUMENTS etc. but they didnt work.
I am looking to do something like this:
Page_load
Case:
Button 1 clicked
//Do something
Button 2 clicked
//Do something
Use the below code.
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Calling this function:
I have included the above function in a static class UtilityClass.
String postBackControlId = UtilityClass.GetPostBackControlId(this);
The code has been referenced from Mahesh's Blog.
I am trying to hide some divs using Javascript but i think the post back keeps reloading the page.
To make things more complicated my buttons are added programmatically by my code behind.
foreach (string line in thefilters)
{
Button newButton = new Button();
newButton.ID = Convert.ToString(line);
newButton.Text = Convert.ToString(line);
newButton.CssClass = "tblbutton";
//newButton.Attributes.Add("onclick", "hide_div("+newButton.ID+")");
newButton.OnClientClick = "return hide_div('" + newButton.ID + "')";
pnl_left.Controls.Add(newButton);
}
My javascript is located in the header as follows.
<script type="text/javascript">
function hide_div(filter) {
var pnl_right = document.getElementById("pnl_right");
var listofelements = pnl_right.getElementsById("div");
for (var i = 0; i < listofelements.length; i++) {
if (listofelements[i].id.indexOf(filter) == 0) {
document.getElementById(listofelements[i].id).style.display = 'inline';
}
else {
document.getElementById(listofelements[i].id).style.display = 'none';
}
}
return false;
}
I may have issues in the javascript for what i want to achieve but i am confident that if i can stop the postback then i can solve the javascript myself..
Thanks for any suggestions in advance.
You have not showed in which event you are adding controls. But I am assuming from your problem that you are doing this in Page_Load. If yes, try and move in OnInit event.
Second, in Page_Load you need to check
if(!IsPostBack)
{
//your code for adding controls
}
Hope that helps.