Jquery background request using $.get() with ASP.NET - Solving Issues - asp.net

I am working on an ASP.NET application that makes some AJAX background request using jQuery (I'm new to jQuery :)).
My jQuery codes are as following:
$(document).ready(function () {
$("#ctl00_cphContent_txtOrgName").keypress(function () {
var orgNameLen = $("#ctl00_cphContent_txtOrgName").val().length;
if (orgNameLen <= 4) {
$("#orgNameHints").empty();
$("#orgNameHints").css('display', 'none');
return;
}
$("#orgNameHints").css({ "visibility": "visible" });
$("#orgNameHints").html("Checking...");
var OrgName = $(this).val();
$.get("ProcessOrgName.aspx?n=" + OrgName, function (data) {
$("#orgNameHints").html(data);
$("#orgNameHints").show();
});
});
$("#ctl00_cphContent_txtOrgName").blur(function () {
$("#orgNameHints").empty();
$("#orgNameHints").css({ "visibility": "hidden" });
});
});
And ASP codes are:
<asp:TextBox ID="txtOrgName" runat="server" MaxLength="100"></asp:TextBox>
<div id="orgNameHints" style="border: 1px solid silver; display:none; position:absolute; padding: 5px; background: #EFEFEF; z-index: 100;"></div>
Here txtOrgName is the textbox that is used to check existing records with same data in background (Just like the hinting of search keywords in google). The .get() method will post the search keyword as querystring at ProcessOrgName.aspx, which returns the list of such existing records from the database.
Everyting works fine here, but the problems I am facing are:
Keypress() event invokes search like, if I am searching for
stackoverflow it will query for stackoverflo where w is missing. So, is there any way to get accurate result.
When I search for a keyword it is displays fine, but when I press backspace
to clear my textbox, it will still display the same results untill I
press backspace 2 times more after the textbox is already clear. So,
can u guys please give any idea to make it so that it does not
display the result in case I press backspace.
Any other way to display and hide the div named orgNameHints as show(); and hide(); does not work in my case, and I want it to be more accurate!
There will be some instances when the user will copy-paste the keywords instead of typing, so it should get search results in that case as well.
Any help is really appreciated.

This could be a result of when you are capturing the text; keypress/keyup/keydown. I think you might want to run this script on keyup() event. Refer to http://www.bloggingdeveloper.com/post/KeyPress-KeyDown-KeyUp-The-Difference-Between-Javascript-Key-Events.aspx for more information on this.
Refer to 1
Why does show/hide not work? Alternatively, you could use fadeIn/fadeOut or $("elem").css({display:none})
For pasting (CTL+V), I believe that is on a keydown() event, if (e.keyCode == 86) //86 is Paste event. As far as a mouse paste, I am not sure..couldn't find any good info on this.
Here is a starter block of code for you, with a fiddle link below.
$(document).ready(function(){
function DoWork(){
$("#searchOutput").append("<li>" + $("#tb1").val() + "</li>");
}
$("#tb1").keyup(DoWork);
$("#tb1").keydown(function(e){
if(e.keyCode == 86){
DoWork();
}
});
});​
http://jsfiddle.net/TNCodeMonkey/CnDGw/3/
Best of luck!

Related

closing an open div when body / html element is clicked in meteor

so i'm working on a meteor project and am trying to get a drop down menu to close when the user clicks outside of it. i've done this before using jquery and normal html but this time we're using velocity.js and meteor.
so on the link that opens the drop down div, i have this:
Template.layout.events({
'click #profile-btn': function () {
if (userTog == false) {
$('#user-menu').velocity("fadeIn", { duration: 150 });
userTog = true;
}
else if (userTog == true) {
$('#user-menu').velocity("fadeOut", { duration: 150 });
userTog = false;
}
},
.....
and then i use a meteor package to deal with events on the body as this isnt supported right now..
Template.body.events({
'click html': function(e, data, tpl) {
userTog = false;
$('#user-menu').velocity("fadeOut", { duration: 150 });
e.stopPropagation();
}});
however the above is just not working.. it basically just makes the menu appear then disappear straight away. is it something to do with velocity.js, meteor or am i just doing it plain wrong ?!?
any advice would be greatly appreciated!
I just had to make a material design select box, so I feel your pain :-). Here's how I solved it:
Normally, you can only focus an input or an anchor. A trick I stumbled upon is that using tabindex="0" in your element attributes allows it to gain focus, even if it's a div. What's this mean? Well, if you can focus() an element, that means you can blur() it. So, when you click the button for the dropdown, add a line at the end of the event handler like $('.dropdown-menu').focus(). Then, to escape that, just create an event handler like 'blur .dropdown-menu': function() {*..hide..*}. That way, you don't have these ugly global event watchers.
The downside is that you get a glowing blue outline (for accessibility reasons). You can get rid of this by having a line like outline: 0; in your css.
PS, the reason why yours wasn't working is because 'click #profile-btn' bubbles up to the body, so it executes both. To fix it, you need to stop that bubblin via e.stopPropagation();.

How to set UseSubmitBehavior="False" in one place for the whole web application

I want all of the buttons in my asp.net web forms application to have UseSubmitBehavior="False" but I don't want to go through all my pages trying to hunt down each and every last button and set the property individually.
I am hoping there is a way to do this globally, for example in the web.config file. Thanks!
This is not a page property or something like that
this is a button property which allowes submit via __doPostBack
You Can't do this globally via web.config ( or in any other way).
The reason for wanting to set UseSubmitBehavior="False" is to stop the form from submitting when the user presses enter. If this is your goal then the following will interest you:
Another way to do this is to use JavaScript. This shifts the overhead of MikeSmithDev's suggestion to the client which might be more acceptable depending on your scenario.
Please note that the following JavaScript makes use of the jQuery library:
$(document).ready(function () {
preventSubmitOnEnter();
});
function preventSubmitOnEnter() {
$(window).keypress(function (e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
return false;
}
}
});
}

AsyncFileUpload control

Regarding the AsyncFileUpload control in .net, the control will execute the file upload once i select a file. In my concern is, is it possible to disable the upload once i select a file so that i could process the upload asynchronously with a submit button.
I know this is old, but I beat my head on this for a while, so for whoever might be interested.
My first thought was to disable the file input underneath the control.
I was able to disable the control but unfortunately, it stopped working. When the server fired AsyncFileUpload_UploadComplete the input was diabled so there wasn't a file to read.
<script>
function disableFileUpload(on) {
if (on) {
$('#ajax-file-input input:file').attr('disabled', true);
} else {
$(#ajax-file-input 'input:file').attr('disabled', false);
}
}
function AsyncFileUpload_CheckExtension(sender, args) {
disableFileUpload(true);
return true;
}
function AsyncFileUpload_OnClientUploadComplete(sender, args) {
disableFileUpload(false);
var data = eval('(' + args.d + ')');
for (var key in data) {
var obj = data[key];
for (var prop in obj) {
console.log(prop + " = " + obj[prop]);
}
}
doThingsWith(data);
}
</script>
<div id="ajax-file-input">
<ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1"
OnUploadedComplete="AsyncFileUpload_UploadComplete"
OnClientUploadStarted="AsyncFileUpload_CheckExtension"
OnClientUploadComplete="AsyncFileUpload_OnClientUploadComplete"
runat="server" />
</div>
I ended up positioning a semi-transparent png on top of the control and showing and hiding it to make the control innaccesible.
Hope this helps.
function disableFileUpload(on) {
if (on) {
$("#file-disabled").show();
} else {
$("#file-disabled").hide();
}
}
Simple answer is No. I've had similar asyncupload issues just like those ones. My advice is to stay away from him if you need to control upload with a button, add and remove selected files (you will probably need this later on) and use some javascript manipulation.
Search for the SWFUpload, is a flash component that can be integrated with .NET with ease. It offers multiple javascript options and events. :D
Check the following links:
Official site
Demonstration
As far as I know that the only event exposed by AsyncFileUpload is the UploadComplete event and UploadError. There aren't events specifically that expose functionality to manually initiate the upload. Perhaps some trick in JavaScript could do it but I have not seen such a workaround before.

jQuery.click(): Can I get a reference to the synthetic event object passed to event handlers?

I have an <a> inside a <TD>, and I'm trying to have clicks on the <TD>, but outside the <A>, act like they were clicks on the <a>. I'm almost there:
HTML:
<TD class="somethingPretty">
Text
</td>
JS:
$('.anchor').click(function(ev){return confirm("go ahead?");});
$('somethingPretty').click(function(ev){
if($('.anchor').click()){
document.location = $('.anchor').attr('href');
}
}
The problem with this is that jQuery.click returns undefined, and I can't see how to get at the event object that's passed to the click handlers so I can interrogate it with isPropagationStopped and isDefaultPrevented. What's the right way to solve this problem?
Sometimes asking the question clearly is the best way to find an answer. Some strategic poking around the jQuery source led me to the following solution(using the markup above):
$('.somethingPretty').click(function(ev){
var syntheticClick = new $.Event("click");
syntheticClick.stopPropagation();
$('.anchor').trigger(syntheticClick);
if(syntheticClick.isDefaultPrevented()) return;
document.location = $('.anchor').attr('href');
}
This works for all event handlers except live-bound ones (those don't execute; my users will have to learn to click the anchor itself for them!). The tricky part here is that trigger takes a jQuery.Event in addition to the documented string.
How about this?
var a = $('.somethingPretty .anchor');
var td = $('.somethingPretty');
a.click( function(ev) { return confirm("go ahead?"); } );
td.click( function() { a.click(); } );
Did you try something like:
$("td.outer").add("td.outer a").click(function() {
// do stuff
});
You're going to want to find some way to ensure that whatever is in the function runs only once, since a click on the <a> will count both as a click on the <td> and the <a>.

How do I interrupt an ASP.NET button postback with BlockUI and Jquery

I have an ASP.NET page with a number of ASP:Button instances on it. For some, I need to show a confirmation prompt and, should the user choose yes, the original postback method is called. Otherwise, the overall process is cancelled.
I've got an example running but I get inconsistent results, mainly in FF3 where I get an exception thrown:
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame ::
I've looked this error up but I'm drawing a loss as to where I'm going wrong. Here's my example case. Note, for now I'm just using the css class as a lookup. Longer term I can embed the clientID of the control into my JS if it proves necessary :).
Html fragment:
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStartClicked" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).get()[0].click);
$(this).unbind("click");
}).click(function(){
var oldclick = $(document).data("startclick");
alert("hello");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
return false;
});
My code behind is relatively simple, the OnStart method simply executes a Response.Write
I've only just started looking into bind, unbind and trigger so my usage here is pretty much 'first time'.
Thanks for any help or advice.
S
EDIT:
This describes what I'm trying to do and also gives a run down of the kind of pitfalls:
http://www.nabble.com/onClick-prepend-td15194791s27240.html
How about this?
$(document).ready( function() {
$('.startbutton').click(function() {
return confirm('Are you sure?');
})
});
I've solved my problem for IE7 and FF3.
The trick is to make the postback work as an 'onclick' via an ASP.NET attribute on the button (see below). In Javascript this gets pulled out as a function reference when you read the click in JQuery.
To make it work, you then clear the onclick attribute (after saving it) and call it later on.
My code below shows it in action. This code isn't complete as I'm part way through making this into a generic prompt for my application. Its also a bit badly laid out! But at least it shows the principle.
ASP.NET button
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStart" UseSubmitBehavior="false" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).attr("onclick"));
$(this).removeAttr("onclick");
}).click(function(){
$.blockUI({ message: $('#confirm'), css: { width: '383', cursor: 'auto' } });
$("#yes").click(function(){
$.unblockUI();
var oldclick = $(document).data("startclick");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
});
$("#no").click(function(){
$.unblockUI();
});
return false;
});
Your problem comes from here :
$(document).data("startclick", $(this).get()[0].click);
...
var oldclick = $(document).data("startclick");
...
oldclick();
Here, you try to intercept a native event listener but there are two errors :
Using unbind will not remove the native event listener, just the ones added with jQuery
click is, AFAIK, a IE only method used to simulate a click, it not the event handler itself
You'll have to use onclick instead set its value to null instead of using unbind. Finally, don't store it in $(document).data(...), you'll have some problems when you add other buttons. Here is a sample code you can use :
$("selector").each(function()
{
var oldclick = this.onclick;
this.onclick = null;
$(this).click(function()
{
if (confirm("yes or no ?")) oldclick();
});
});
for mi works:
this.OnClientClick = "$.blockUI({ message: $('#ConfirmacionBOX'), css: { width: '275px' } });return false;";
This is a button (is a button class)

Resources