Posts

Showing posts with the label JavaScript

Donate

Url Variable Returns Forward Slash "/" instead of absolute Url in Controller Action

Hi, When passing a url from a controller action to an Ajax $.post() result that is to navigate to the landing page, using the code below generates only a forward slash which is the root symbol instead of an absolute url. If the url value (/) will be used in window.location.href , it will cause an IIS page not found error. var url = new UrlHelper(Request.RequestContext).Action( "Index" , "Customer" ); return Json( new { Url = url }); So, to return the absolute url of the controller action in the current context, replace UrlHelper class with Url.Action() method. It is important to include the Request.Url.Scheme in the parameter to pass the correct protocol of the url. The code below will return an absolute url such as: http://localhost:7088 for the landing page. var url = this .Url.Action( "Index" , "Customer" , null , Request.Url.Scheme); return Json( new { Url = url });

window.location.href not opening website

Hello, The code below does not open the link, instead opens a blank page or IIS error. This issue occurs in all major browsers. window.location.href = 'www.nba.com' ; In order to fix the issue,you must prepend the correct protocol before the website such as (http:// or https:// or ftp://). If the protocol is omitted, the link is interpreted as a file in the website. window.location.href = 'http://www.nba.com' ; Cheers!

Enable ASP.NET Control After Validation Of Prior Control Succeeded Using JavaScript In ASP.NET

Given you have a simple form below with two TextBox controls. The second TextBox is disabled during pageload. Ifyou want to enable the second TextBox control if the validation of the first/prior control succeeded, the solution for this is using client side approach which is to check the visibility property through JavaScript/jQuery. HTML Code 1 2 3 4 5 6 7 8 9 10 11 <div id= "ContactForm" > <asp:Label id= "lblEmail" Text= "Email Address:" AssociatedControlID= "txtEmail" Runat= "server" /> <asp:TextBox id= "txtEmail" Runat= "server" /> <asp:RegularExpressionValidator id= "regEmail" ControlToValidate= "txtEmail" Text= "(Invalid email)" ValidationExpression= "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Runat= "server" /> <asp:Label id= &qu

ASP.NET Trigger Onchange Event Of DropDownList Inside GridView Using jQuery

Image
There was a question in a forum if how can we trigger an onchange event of a DropDownList control inside a GridView template field. This time using unobtrusive approach. So in order to understand a bit further, the GridView control when rendered to the browser becomes a table element while DropDownList becomes a Select control. So, to trigger the event we need to traverse the GridView control then find the Select control and attach a change event. Here's a solution using jQuery. HTML Markup: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <asp:GridView ID= "gvItem" runat= "server" AutoGenerateColumns= "False" > <Columns> <asp:BoundField DataField= "ID" HeaderText= "ID" /> <asp:BoundField DataField= "ProductName" HeaderText= "ProductName" /> <asp:TemplateField HeaderText= "Time Slot" > <

Check If Images Are Not Rendered Correctly To The Browser Using JavaScript

Hello, Here's a function to hide divs if it's children specifically images does not render correctly to the browser or an error has occured. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 function ImageDivHandler() { $( "div.gallery" ).each( function () { if ($( this ).children().length == 0) { $( this ).hide(); } else { var img = $( this ).find( ".image-responsive" ); if (img != null || img != undefined ) { imgSrc = $( this ).find( ".image-responsive" ).attr( "src" ); if (imgSrc == "" || imgSrc == null || imgSrc == "null" ) { $( this ).find( ".image-responsive" ).closest( "div.gallery" ).hide(); } else { $( this ).find( ".image-responsive" ).error( function () { $( this ).closest( "div.gallery" ).hide();

How To Reset Cascading Dropdown Controls Using JavaScript And jQuery

Hi, Recently, I have encountered an issue on how to reset cascading dropdown controls in cross browsing mode (IE/Firefox/Chrome) using JavaScript and jQuery. After creating code spikes, I come up with a solution that works across major browsers. Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 $( ".reset-link" ).click( function () { ResetCascade($( this )); }); function ResetCascade(itemReset) { var formID = $(itemReset).closest( '.contact-form' ); if (formID != null ) { var firstDropDown = $(formID).find( '.cascading_group' ).find( '.firstDropDownDiv select' ); var secondDropDown = $(formID).find( '.cascading_group' ).find( '.secondDropDownDiv select' ); var thirdDropDown = $(formID).find( '.cascading_group' ).find( '.thirdDropDownDiv select' ); if (firstDropDown != null ) { var valueId = $(firstD

Update ASP.NET Web Forms Label Control Value Using Continuous Mouse Down Click

Starting today, I'm going to contribute source code in vbforums.com( Visual Basic Forum ). The community helped me way back since VB 6.0 and VBA. And in turn, it's time to give back as an experienced member. :) Here's a an ASP.NET application I posted in ASP.NET code bank on how to update label values continuously on mouse hold. Update Label Value using jQuery/Javascript in ASP.NET Reference: Easily do a continuous action on mouse hold using javascript Cheers! :)

Simple Array Manipulation Using Knockout.js (Add, Remove All, Remove Item, Show)

Image
Most of KnockoutJS features involves binding of a viewmodel object to the a view. But there are special cases where in you want to manipulate ordinary arrays without using ko.observableArray(). So to expound more on this post, here's a sample code below: KnockoutJS code: $(document).ready( function () { function ProductViewModel() { //product array this .Products = [{ id: '1' , name: 'Wax' }, { id: '2' , name: 'Cotton Buds' }, { id: '3' , name: 'Nova' }, { id: '4' , name: 'Milo' } ]; //insert product this .Add = function () { console.log( 'Insert Activity' ); this .Products.push({ id: '5' , name: 'Test' }); console.log( 'Total products: ' + this .Products.length); };

Simple Knockout.js Example In ASP.NET Web Forms

Image
Intrigued with emerging Javascript framework called knockout, I decided to try a simple example myself. As defined by Wikipedia: Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore: 1. A clear separation between domain data, view components and data to be displayed 2. The presence of a clearly defined layer of specialized code to manage the relationships between the view components The features of Knockout are based on Declarative bindings: A. Automatic UI refresh (when the data model's state changes, the UI updates automatically) B. Dependency tracking C. Templating (using a native template engine although other templating engines can be used, such as jquery.tmpl) I come to a conclusion that this has similar approach to WPF MVVM. So, to get started with, download the latest Knockout.js framework here: Knockout Home Page and add reference to your html or aspx markup: Code: <!

Add Placeholder (Watermark) To Html.TextBoxFor() Helper In ASP.NET MVC 4

Image
After working with simple form html elements, I decided to give it a try applying the placeholder jquery framework to ASP.NET MVC4 application. The steps are similar in this post: Placeholder attribute in HTML5 form Elements except that the target controls are HTML Helpers. Basically, TextBoxFor() helper when rendered to the browser is an input text element. So, let's give it a spin. On your _Layout.cshtml, reference the jquery and placeholder scripts. <script type= "text/javascript" src= "~/Scripts/jquery-1.7.1.min.js" ></script> <script type= "text/javascript" src= "~/Scripts/placeholders.jquery.min.js" ></script> and in your MVC Form, apply it to TextBoxFor() as shown below: @model TextBoxFor.Models.Movie @{ ViewBag.Title = "CreateMovie"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Movi

Placeholder Attribute In HTML5 Not Showing On IE 9 And Below (Watermark Feature)

Image
Given this html markup for input text element for accepting email value: <input type= "email" name= "inEmail" id= "inEmail" required= "required" placeholder= "yourname@domain.com" /> The place holder shows correctly on firefox and google chrome but not on IE 9. After searching the internet, I found placeholder framework that will fix place holders in IE 9 and below. The steps are as follows: 1. Download the placeholder script here: Placeholder js 2. Add reference to jquery and placeholder on your html file. <script src= "../Scripts/jquery-1.7.1.min.js" type= "text/javascript" ></script> <script src= "placeholders.jquery.min.js" type= "text/javascript" ></script> IE demo: That's it... :)

Debugging jQuery Or Javascript Code Not Working In ASP.NET MVC 2 (VS 2010)

In an application where there is internal jquery code in your MVC project, placing a breakpoint won't work when you want to enable debugging mode. After searching, a workaround has been provided by Microsoft Team. The solution is to transfer the javascript/jQuery script to an external .js file instead of embedding it in your .aspx script.Refer to the workaround. Solution: http://connect.microsoft.com/VisualStudio/feedback/details/652428/mvc-3-mvc-2-debug-ignores-javascript-breakpoints Cheers! Greg

How To Highlight GridView Row On Click In ASP.NET Web Forms

This is based from the article of Vincent Maverick Durano's blog on HIGHLIGHT GRIDVIEW ROW ON CLICK AND RETAIN SELECTED ROW ON POST BACK. I just added some statements on javascript to check if the selected row is less than total gridview row count and server side code for paging. JAVASCRIPT CODE: <script type= "text/javascript" > var prevRowIndex; function ChangeRowColor(row, rowIndex) { var parent = document.getElementById(row); var currentRowIndex = parseInt(rowIndex) + 1; //count number of gridview rows var rowscount = $( "#<%=grdCustomer.ClientID %> tr" ).length; if (prevRowIndex == currentRowIndex) { return ; } else if (prevRowIndex != null ) { parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF" ; } //check if current index is a number... if (IsNumeric(currentRowIndex)) { //check if row index

JQuery Calculator Example In ASP.NET Web Forms

Image
The image above is a jquery/javascript calculator developed in ASP.NET 4.0 web template. Here's the functions. I'wont be posting all codes since it will took up space in my post. I'll just post the sqrt() and a number scripts. The ASPX markup uses plain css for centering and aligning the buttons and html controls. No asp.net server controls are involved. For the jquery processing, im using the id selector. /* show zero to textbox on page load */ $( "#txtCalc" ).ready( function () { $( "#txtCalc" ).val( "0" ); }); //square root $( "#btnSqrt" ).click( function () { var text = $( "#txtCalc" ).val(); //if invalid input,do not execute codes below if (text.search( "Invalid" ) != -1) { return ; } if (text.length == 1) { if (text == "0" ) { return ; }

How To Debug JavaScript Code In Visual Studio 2008 Or Visual Studio 2010

Here are the simple steps to debug js code in your aspx markup. 1. Open Visual Studio 2008/2010 2. Click Tools then options 3. Expand debugging node then click checkboxes Manages,Native,Script. 4. In your web.config file,make sure to set compilation debug to true. <compilation debug= "true" > <assemblies> <add assembly= "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly= "System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly= "System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly= "System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> </assemblies> </compilation> 5. Choo

JavaScript Object Oriented Programming Using Prototype

Hello, In JavaScript, each Object can inherit properties from another object, called it's prototype . When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype. Each object is associated with a prototype which comes from the constructor function from which it is created. (Source: http://mckoss.com/jscript/object.htm ) Here's an example i created: <html> <head> <script type= "text/javascript" language= "javascript" > function NumberManip() { var result = 0; } NumberManip.prototype.add = function (num1, num2) { this .result = num1 + num2; } NumberManip.prototype.subtract = function (num1, num2) { this .result = num1 - num2; }

URL Rewritting Resolve URL In My External CSS And JavaScript Files

I have applied url rewritting from scott: URL Rewriting Tutorial to make my url's SEO friendly. However, my css and javascript files are created internally (w/ in the page itself). When i tried separating my css and .js files, I usually encountered javascript errors such as: 1. GetCustomerDetail is undefined [based from Mozilla Firebug] 2. Microsoft JS runtime error: object required [Internet explorer] I tried googling for hours about object required and have'nt found an answer. As i read again scott's article, the last paragraph was a hint regarding how to resolve CSS and image external links. The solution I came up with was using Control.ResolveUrl() so that my external javascript and css files will work. src= '<%= Page.ResolveUrl("yourjsfile")%>' 2: href= '<%= Page.ResolveUrl("yourcssfile")%>' A good resource, but haven't tested yet. Westwind Tutorial FROM MSDN: MSDN

Validation In ASP.NET WebForm Not Working For Confirm Dialog

In this scenario, I have a series of textbox controls that has required field validations and a save button with the following attribute property set in pageload event: btnSave.Attributes.Add( "onclick" , "return confirm ('Proceed saving or updating this record?')" ); In most cases, this works fine, but the problem is if i clicked ok in the confirm dialog of javascript, the validation of required fields will be bypassed. So the solution would be to modify the script to return false if cancel is pressed in the confirm dialog of javascript so that validation will work.Here is the modified script: btnSave.Attributes.Add( "onclick" , "if(!confirm ('Proceed saving or updating this record?')) return false;" ); If the user will click ok, in the javascript confirm dialog, validations will be executed.

Access DOM Elements in ASP.NET WebForms Master And Content Pages Using ClientID And jQuery

The example below will display Bill Murstein in asp.net textbox Example: 1 2 3 4 5 6 var name = 'Bill Murstein' ; //javascript DOM document .getElementById( '<%=txtCustomerName.ClientID%>' ).value = name; //jQuery Counterpart $( '[id$=txtCustomerName]' ).val(name);

jQuery In ASP.NET Web Forms Ajax Does Not Work After Partial Postback

I encountered a problem with jquery in asp.net ajax with master page content. During first pageload, the jquery script works fine, but after partial postback, the jquery script does not work. After a few googling activity, I came upon this site: http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/ This explains how to use document.ready, pageload, and Application.init. In my previous code, i've used document.ready since my aspx page was not ajax enabled. But since, Im switching my application to ajax ready, the solution I came upon was using function pageLoad() instead of document.ready(). Example: 1 2 3 4 5 6 7 function Pageload() { $( "#txtsomething" ).blur( function () { //your js code here var x = 25 + 25 ; alert(x); }); } Hope this insight will help other developers out there... Here is the summary from the direct link: $(document).ready() Ideal for onetime initialization. Optimization black magic; may

Donate