Disable enter key in xhtml - button

I have a web page that whenever your in a text-field, if you hit enter, it will hit a very undesirable button. I know there are many posts out there like this, but the solutions haven't worked for me. I am using xhtml and am just wondering how I can stop the enter button from doing this, or even make it click a different button. Thank you for your time and help.

You can use javascript on your page to stop the enter button event.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>

Related

Mouse middle button does not work

i have a gridview which contains a linkbutton with a ID LnkCourseName
i have requirement that on a click of Middle button of a mouse a new tab should open.
to check the which button of a mouse got clicked, i used a javascript function as :
<script type="text/javascript">
function buttonalert(event) {
var button;
if (event.which == null)
button = (event.button < 2) ? leftclickclear() :
((event.button == 4) ? middleclickclear() : rightclickclear());
else
button = (event.which < 2) ? leftclickclear() :
((event.which == 2) ? middleclickclear() : rightclickclear());
dont(event);
}
function leftclickclear() {
$('#<%=HdUrl.ClientID %>').val("left");
}
function rightclickclear() {
$('#<%=HdUrl.ClientID %>').val("right");
}
function middleclickclear() {
$('#<%=HdUrl.ClientID %>').val("middle");
}
function dont(event) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
</script>
But on a press of a middle button i get an error
javascript:__doPostBack('dnn$ctr538$ViewTC_TakeAClass$GrdCourseDetail$ctl02$LnkCourseName','')
on a new tab url. Thanks for assistance.
This should be standard behaviour for any reasonable browser, and isn't really an ASP.NET or script issue - the problem is that you're using a link button, which will do a postback just like a button (i.e. <input type=submit>), and it's not a link as in an default a element.
If your links are really just that, and are not expected to post back to the server to execute some logic, and instead just specifies a URL to link to, then use a HyperLink control instead.

How to disable buttons get triggered with <Enter> on aspx-pages

I have a aspx-page with several textboxes and buttons. However, when the cursor is in a textbox, one of the buttons is still "in focus". So when I hit the Enter-key the button is pressed. What I want is to disable the ability to trigger buttons with the Enter-key, or at least when the cursor is in a textbox.
The solution for me was this:
TextBox.Attributes.Add("onkeypress", "return event.keyCode!=13");
on every textboxs and radiobuttons to prevent the enter key to submit the form.
You can try Button.UseSubmitBehavior, or disable the submit of the form using Javascript.
Set of the focus on the textbox where the curson is when the page is loaded - window.onLoad() method.
If its the only submit button in you form then it will be triggered automatically when you press enter. To disable it , you have to mark its as disabled.
To stop form submission on Enter key, add next code in Page or MasterPage:
<script type="text/javascript">
document.onkeypress = function(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
};
</script>

Facebook Like button not rendering inside a reloaded GridView

I have a fb:like button inside the GridView and GridView is inside the update panel. The first time of page load the fb:like button showing but when we click the next button, on the next page the fb:like button doesn't render. Any idea what's wrong?
Due to the fact that you are updating the page with an update panel, the like button will not be rendered when only part of the page is updated. You will have to attach to the clientside updated event (in JS) and then trigger the Facebook XFBML render command:
FB.XFBML.parse();
more about this here:
http://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/
You can do this using the following code:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
var _panels, _count;
function pageLoaded(sender, args)
{
if (_panels != undefined && _panels.length > 0)
{
for (i=0; i < _panels.length; i++)
_panels[i].dispose();
}
var panels = args.get_panelsUpdated();
if (panels.length > 0)
{
updateFbLike();
}
}
function updateFbLike()
{
FB.XFBML.parse();
}
</script>
this is taken from this article:
http://msdn.microsoft.com/en-us/magazine/cc163413.aspx
Richard's solution worked fine for me. I shortened the code to:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandlerBerliner);
function EndRequestHandlerBerliner(sender, args) {
if (args.get_error() == undefined) {
FB.XFBML.parse();
}
}

ASP.NET, jQuery, dirty forms, and window.onbeforeunload

In my ASP.NET web app, I'm trying to create a universal way of warning users before navigating away from a form when they've made changes, using jQuery. Pretty standard stuff, but after a lot of searching I have yet to find a technique that works.
Here's what I have at this point:
addToPostBack = function(func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != 'function') {
__doPostBack = func;
} else {
__doPostBack = function() {
old__doPostBack();
func();
}
}
}
var isDirty = false;
$(document).ready(function() {
addToPostBack(function() {
alert("Postback detected.")
clearDirty();
});
$(':input').bind("change select keydown", setDirty);
window.onbeforeunload = function(e) {
var msg = "You have unsaved changes. "
if (isDirty == true) {
var e = e || window.event;
if (e) { e.returnValue = msg; }
return msg;
}
};
});
setDirty = function() {isDirty = true;}
clearDirty = function() {isDirty = false;}
This works as far as warning the user from navigating away. The problem is that I get the warning on every same-page postback. There are a number of things on my forms that might trigger a postback:
There are Save, Cancel, and Delete linkbuttons on the page
There might be other linkbuttons on the page that execute server-side functionality while staying on the same page
There might be other controls with autopostback=true that also have server-side functions attached to them, but which don't result in the user leaving the page.
None of these things should provoke a warning, because the user isn't leaving the page. My code tries to hijack addToPostBack (more details on that in this question) to clear the isDirty bit before posting back, but the problem is that in IE onbeforeunload fires before __doPostBack, apparently because IE fires onbeforeunload immediately when a link is clicked (as described here).
Of course, I could wire up each of these controls to clear the isDirty bit, but I'd prefer a solution that operates on the form level and that doesn't require that I touch every single control that might trigger a postback.
Does anyone have an approach that works in ASP.NET and that doesn't involve wiring up every control that might cause a postback?
I came across this post while Googling for a solution for doing the same thing in MVC. This solution, adapted from Herb's above, seems to work well. Since there's nothing MVC-specific about this, it should work just as well for PHP, Classic ASP, or any other kind of application that uses HTML and JQuery.
var isDirty = false;
$(document).ready(function () {
$(':input').bind("change select keydown", setDirty);
$('form').submit(clearDirty);
window.onbeforeunload = function (e) {
var msg = "You have unsaved changes. "
if (isDirty == true) {
var e = e || window.event;
if (e) { e.returnValue = msg; }
return msg;
}
};
});
setDirty = function () { isDirty = true; }
clearDirty = function () { isDirty = false; }
Interesting, but... why don't you do everything with jQuery?
var defaultSubmitControl = false;
var dirty = false;
$(document).ready(function( ) {
$('form').submit(function( ) { dirty = false });
$(window).unload(function( ) {
if ( dirty && confirm('Save?') ) {
__doPastBack(defaultSubmitControl || $('form :submit[id]').get(0).id, '');
}
});
});
···
dirty = true;
···
Now, if that still causes the same issue (unload triggering before submit), you could try a different event tree, so instead of calling __doPostBack directly you do...
setTimeout(function( ) {
__doPastBack(defaultSubmitControl || $('form :submit[id]').get(0).id, '');
}, 1); // I think using 0 (zero) works too
I haven't tried this and it's from the top of my head, but I think it could be a way to solve it.
You could always create an inherited page class that has a custom OnLoad / OnUnload method that adds in immediate execution JavaScript.
Then you don't have to handle it at a control specific level but rather the form / page level.
Got this to work by basically tracking the mouse position. Keep in mind you can still get positive values to your Y value (hence my < 50 line of code), but as long as your submit buttons are more than 100 pixels down you should be fine.
Here is the Javascript I added to track mouse changes and capture the onbeforeunload event:
<script language="JavaScript1.2">
<!--
// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false
// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)
// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;
// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0
// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else { // grab the x-y pos.s if browser is NS
tempX = e.pageX
tempY = e.pageY
}
// catch possible negative values in NS4
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
// show the position values in the form named Show
// in the text fields named MouseX and MouseY
document.Show.MouseX.value = tempX
document.Show.MouseY.value = tempY
return true
}
//-->
</script>
<script type="text/javascript">
window.onbeforeunload = HandleOnClose;
function HandleOnClose(e) {
var posY = 0;
var elem = document.getElementsByName('MouseY');
if (elem[0]) {
posY = elem[0].value;
}
if (posY < 50) { // Your form "submit" buttons will hopefully be more than 100 pixels down due to movement
return "You have not selected an option, are you sure you want to close?";
}
}
</script>
Then just add the following form onto your page:
<form name="Show">
<input type="hidden" name="MouseX" value="0" size="4">
<input type="hidden" name="MouseY" value="0" style="display:block" size="0">
</form>
And that's it! It could use a little cleanup (remove the MouseX, etc), but this worked in my existing ASP.net 3.5 application and thought I would post to help anyone out. Works in IE 7 and Firefox 3.6, haven't tried Chrome yet.
i am looking after this too but what i have find so far is, a solution that uses all the html controls instead of asp.net web controls, have you think of that?
<script type="text/javascript">
$(document).ready(function () {
$("form").dirty_form();
$("#btnCancel").dirty_stopper();
});
</script>

ASP.NET: Scroll to control

I've got a particularly large form in an page. When the form is validated and a field is invalid, I want to scroll the window to that control. Calling the control's Focus() doesn't seem to do this. I've found a JavaScript workaround to scroll the window to the control, but is there anything built into ASP.NET?
Page.MaintainScrollPositionOnPostBack = False
Page.SetFocus(txtManagerName)
Are you using a Validation Summary on your page?
If so, ASP.NET renders some javascript to automatically scroll to the top of the page which may well override the automatic behaviour of the client side validation to focus the last invalid control.
Also, have you turned client side validation off?
If you take a look at the javascript generated by the client side validation you should see methods like this:
function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) &&
IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
Note the call to ValidatorSetFocus, which is a rather long method that attempts to set the focus to the control in question, or if you have multiple errors, to the last control that was validated, using (eventually) the following lines:
if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
To get this behaviour to work, you would ideally need to ensure that all your validators are set to be client-side - server side validators will obviously require a postback, and that might affect things (i.e. lose focus/position) - and setting MaintainScrollPositionOnPostBack to true would probably cause the page to reload to the submit button, rather than the invalid form element.
Using the server side .Focus method will cause ASP.NET to render out some javascript "on the page load" (i.e. near the bottom of the page) but this could be being overriden by one of the other mechanisms dicussed above.
SO I believe the problem is because I was trying to focus on HtmlGenericControls instead of WebControls.
I just ended up doing a workaround based off of:
http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
http://www.codeproject.com/KB/aspnet/ViewControl.aspx
...in the interest of time.
public static void ScrollTo(this HtmlGenericControl control)
{
control.Page.RegisterClientScriptBlock("ScrollTo", string.Format(#"
<script type='text/javascript'>
$(document).ready(function() {{
var element = document.getElementById('{0}');
element.scrollIntoView();
element.focus();
}});
</script>
", control.ClientID));
}
Usage:
if (!this.PropertyForm.Validate())
{
this.PropertyForm.ErrorMessage.ScrollTo();
failed = true;
}
(Although it appears Page.RegisterClientScriptBlock() is deprecated for Page.ClientScript.RegisterClientScriptBlock()).
Adding MaintainScrollPositionOnPostback is the closest that ASP.NET has built in, but won't necessarily jump to the invalid field(s).
<%# Page MaintainScrollPositionOnPostback="true" %>
Very simple solution is to set the SetFocusOnError property of the RequiredFieldValidator (or whichever validator control you are using) to true
Are you sure Focus() won't do what you're describing? Under the hood, it is essentially doing the "JavaScript workaround" - it writes some JS to the page which calls focus() on the control with the matching ID:
Whichever control had Focus() called last before the page finishes processing writes this to the page:
<script type="text/javascript">
//<![CDATA[
WebForm_AutoFocus('txtFocus2');//]]>
</script>
Please insert these into your OnClick event
Page.MaintainScrollPositionOnPostBack = false;
Page.SetFocus("cliendID");
// or
Page.setFocus(control);
You should looks into jQuery and the ScrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
I've achieved something similar using basic HTML fragments. You just leave an element with a known ID:
<span id="CONTROL-ID"></span>
And then either via script, on on the server side change the url:
window.location += "#CONTROL-ID";
In the first case the page won't reload, it will just scroll down to the control.
Paste the following Javascript:
function ScrollToFirstError() {
Page_ClientValidate();
if (Page_IsValid == false) {
var topMostValidator;
var lastOffsetTop;
for (var i = 0; i < Page_Validators.length; i++) {
var vld = Page_Validators[i];
if (vld.isvalid == false) {
if (PageOffset(vld) < lastOffsetTop || lastOffsetTop == undefined) {
topMostValidator = vld;
lastOffsetTop = vld.offsetTop;
}
}
}
topMostValidator.scrollIntoView();
}
return Page_IsValid;
}
function PageOffset(theElement) {
var selectedPosY = 0;
while (theElement != null) {
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
return selectedPosY;
}
Then call ScrollToFirstError() in your OnClientClick of the button that is saving, make sure the button has CausesValidation=true as well.
There you have it.

Resources