Mouse middle button does not work - asp.net

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.

Related

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

Is it possible to force a menu popout to trigger on click instead of mouseover?

I use a ASP.NET Menu control with Orientation=Horizontal. It is kind of irritating that the popout menus appear on mouseover, which causes it to show by accident if you move the mouse over the menu when you want to click on something right below the menu. Then the menu popout hides the element you actually wanted to click on!
Is it possible to change the functionality so that the popout requires a mouse click instead of mouseover?
Well, I found a solution myself (kind of a hack...).
This solution requires use of AJAX to capture the menu item onclick postback event, so it can be picked up client side in javascript before doing the actual postback when you click the menu item.
First, I override these functions that is defined by the Menu control
to ignore the menu popout in the mouseover event:
var activeMenuItem = null;
function Menu_HoverStatic(item) {
// Register the active item to be able to access it from AJAX
// initialize postback event
activeMenuItem = item
// Apply the style formatting on mouseover (colors etc).
// This was also called in the original Menu_HoverStatic function.
Menu_HoverRoot(item);
}
function Menu_Unhover(item) {
activeMenuItem = null; // This is the only difference to the original
var node = (item.tagName.toLowerCase() == "td") ?
item:
item.cells[0];
var nodeTable = WebForm_GetElementByTagName(node, "table");
if (nodeTable.hoverClass) {
WebForm_RemoveClassName(nodeTable, nodeTable.hoverClass);
}
node = nodeTable.rows[0].cells[0].childNodes[0];
if (node.hoverHyperLinkClass) {
WebForm_RemoveClassName(node, node.hoverHyperLinkClass);
}
Menu_Collapse(node);
}
// Then I added a renamed copy of the original `Menu_HoverStatic` function:
function Menu_ClickStatic() {
// Pick up the active menu item that is set in the
// overridden Menu_HoverStatic function.
// In the original, the item was input parameter.
var item = activeMenuItem;
// The rest is identical to the original Menu_HoverStatic.
var node = Menu_HoverRoot(item);
var data = Menu_GetData(item);
if (!data) return;
__disappearAfter = data.disappearAfter;
Menu_Expand(node, data.horizontalOffset, data.verticalOffset);
}
Then I snap up the onclick postback event in AJAX that is triggered by the menu. This must be done to cancel the onclick postback and display the menu popout instead.
// Get the Page Request Manager that provides all the .NET
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Register postback event for asyncronous AJAX postbacks
if (prm) prm.add_initializeRequest(InitializePostback);
function InitializePostback(sender, args) {
var element = args.get_postBackElement();
//Check if the postback element is the menu
if (element.id == 'myMenu') {
// Name of the menu element that triggered is the postback argument
var postbackArguments = document.getElementById('__EVENTARGUMENT');
if (postbackArguments)
// Check on the menu item name to pick up only the menu items that shall
// trigger the popout (not the items that does an actual command).
if (postbackArguments.value == 'MenuTopItem1'
|| postbackArguments.value == 'MenuTopItem2'
|| postbackArguments.value == 'MenuTopItem3') {
// Abort and cancel the postback
prm.abortPostBack();
args.set_cancel(true);
Menu_ClickStatic(); // Call my own copy of the original function
return;
}
}
}
Note:
I found out the details about these functions by using the script viewer in Firebug.
The soluton provided above doesn't work in everone's case. One can also try this out, it worked in my solution-
var jq = jQuery.noConflict();
jq(document).ready(function () {
jq(document).on('click', '#ctl_id_Here', function () {
Menu_HoverStatic(this);
Menu_HoverRoot(this);
});
jq(document).on('click', '#ctl_id_Here', function () {
Menu_HoverStatic(this);
Menu_HoverRoot(this);
});
});
3 Steps:
Stop the current hovering effects:
On page load (or on ready), write following line: $('#Menu1').find('ul .level2').css('display','none');
Once you do that, it'll stop the hovering effect of that menu. But once you do that, then you would only be able to open the submenu by making it display block, so for that I wrote following lines, onclick of an image inside the menu: $('#Menu1').find('ul .level2').css('display','block');
Open the menu on click of an element: I don't think need to explain it. Just make menu display block on click of the identified element.
Close the opened menu: 2 ways to do it: First; Use property Disapperafter as below:
Second: Write below code to close it onclick of anywhere else on the screen:
$('body').click(function(evnt) {
if($(evnt.target).parents('table#menu').length == 0)
{
$('#MenuInvitePatient').find('ul .level2').css('display','none');
return;
}
else
{
return;
}
});

Calling my own function during with onClick

How do I call a user-define function such as this one using the onClick attribute of a input button? More specifically what special steps must I take in JQuery and what would the HTML markup look like? Thanks
function simClick(keyCode) {
var e = jQuery.Event("keypress");
e.keyCode = 8;
$(document).trigger(e);
}
<input type="button" ID="delBtn" class="calcBtn" value="Del" onclick="???????" />
HTML
<input type="button" ID="delBtn" class="calcBtn" value="Del" />
Javascript in separate file
// When the DOM is ready
$(function() {
// Function that is executed w keypress or button click
doThis = function() {
// Stuff to do
}
// To do when element with ID delBtn is clicked
$("#delBtn").click(function() {
// Stuff to do when input is clicked
doThis();
});
// To do when key is pressed
$(document).keydown(function(event) {
// Stuff to do when key is pressed
// Can check which key was pressed here.
var code = (event.keyCode ? event.keyCode : event.which);
if(code == 8) { //Enter keycode
doThis();
}
});
});
There are many ways to attach a handler to when that button is clicked. Take a look at jQuery selectors.
You could also use the attribute equals selector
$("input[value='Del']")...... // For the input with a value of Del
I'm not sure what you quoted JS has to do with the input button, since it looks like you're trying to work with a keypress instead of a click in that function.... But the above jQuery is how you capture a click on that input button.
Take a look at, "Which key was pressed?"

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