Posts

Showing posts with the label jQuery

Donate

Sorting Of <li> Elements Using jQuery sort() Method Not Working (Refresh Page Only) In ASP.NET

Given the simple sorting code below which changes the order of <li> elements to ascending order and assuming that the text content of each li elements are numbers. $( function () { $( '#sortList' ).click( function (e) { // Select all the li items var numbersList = $( '#numbersList li' ); numbersList.sort( function (a, b) { return parseInt ($(a).text(), 10 ) > parseInt ($(a).text(), 10 ); }).appendTo(numbersList.parent()); }); }); The code should work only to find out that the page will only refresh after the button click. And then the re-arranging of the elements are discarded. The simple fix to this issue is to add the preventDefault() to prevent the button's default behavior that is to post back. $( function () { $( '#sortList' ).click( function (e) { e.preventDefault(); var numbersList = $( '#numbersList li' ); numbersList.sort( function (a, b) { var temp1 = parseInt($

$.getJSON() Not Loading JSON File Within Visual Studio Project In ASP.NET Web Forms

Hi, I was trying to load a JSON file located within my Visual Studio project using $.getJSON(), however the code below doesn't work as expected. $.getJSON( '/Assets/misc/employee.json' , function (data) { alert( 'processing!' ); }) .done( function (r) { alert(r.message); }) .fail( function (s) { alert( 'oops the file is missing!' ); }); After investigating for a few hours, I tested the local path of the JSON file such as http://localhost:3766/Assets/misc/employee.json and the result was an exception " HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. ". I remember the solution in one of my ASP.NET project was to set the MimeMap in the web.config inside the system.webServer element. After setting the MimeMap for json files, I can now load local JSON files using $.getJSON(). <system.web

$.validator.unobtrusive.adapters.addBool() Not Working In ASP.NET MVC 5 CheckBoxFor()

Image
Hello, I was testing the addBool() method of jQuery validation to a CheckBoxFor() which will prevent the form from submitting if the checkbox is unchecked. To my surprise, the JavaScript code below doesn't work. @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") <script type= "text/javascript" language= "javascript" > (function ($) { $.validator.addMethod('checkboxrequired', function (value, elem) { var $elem = $(elem); if ($elem.prop('type') == 'checkbox') { if (!$elem.prop('checked')) { return false; } } return true; }); $.validator.unobtrusive.adapters.addBool('checkboxrequired', 'required'); }(jQuery)); </script> After series of investigation, I disc

Return View() Statement Not Redirecting To View In ASP.NET MVC Using $.ajax() Post.

Hello, Normally, you submit client-side data to a controller action via @Html.BeginForm(), then perform processing statements and lastly invoke the return View(); statement inside the controller action which will redirect you to the view which basically works. However, in a scenario where-in you will post data to a controller action using jQuery Control Event such as Button Click , the return View() statement in the controller action won't redirect to the specified view given the sample controller action below. [HttpPost] public ActionResult UpdatedEmpTrainings( string empId) { _context = new EmployeeEntities(); model = new List<EmployeeTrainingsViewModel>(); model = ( from emp_trainings in _context.EmployeeTrainings.AsEnumerable() join training in _context.Trainings.AsEnumerable() on emp_trainings.TrainingID equals training.TrainingID where emp_trainings.EmployeeID == Convert.ToInt32(empId) select new EmployeeTrainingsViewModel {

Using AJAX Control Toolkit AutoCompleteExtender In ASP.NET 4.5 Web Forms

Image
Hello all, I have posted in VBForums codebank on how to integrate Ajax Toolkit's AutoCompleteExtender control in your ASP.NET 4.5 Web Forms project. The thread is in VB.NET but if your using C# just replace the code behind as described in Step 4 with the snippet below. Code Behind private static AdventureWorks2012Entities _context; [ScriptMethod()] [WebMethod] public static List< string > GetCountries( string prefixText, int count) { _context = new AdventureWorks2012Entities(); var result = ( from country in _context.CountryRegions.AsEnumerable() where country.Name.ToLower().StartsWith(prefixText, StringComparison.OrdinalIgnoreCase) select country.Name).Take(count); return result.ToList(); } [ScriptMethod()] [WebMethod] public static object GetCountryInfo( string Country) { _context = new AdventureWorks2012Entities(); var result = ( from country in _context.CountryRegions.AsEnumerable() where country.Name.ToLower().Equals(C

Invalid postback or callback argument in ASP.NET (_doPostBack in jQuery UI Confirmation Dialog)

Hello, I'm currently working with ASP.NET GridView control that shows a confirmation dialog using jQuery UI instead of the classic JavaScript confirm dialog that prompts a user to delete a certain record. However, integrating that with the GridView control was slightly tricky in the sense that I was stuck with Invalid postback or callback argument error. Since this is ASP.NET Webforms, you have to deal with Postback hell issues. :) jQuery UI Dialog that trigger's postback buttons: { "Yes" : function () { __doPostBack(btnUniqueID, '' ); $( this ).dialog( "close" ); }, "No" : function () { $( this ).dialog( "close" ); return false ; } } After doing some research, I came up with two solutions. The first one is to set EnableEventValidation of Page directive to false for page level effect. Or you can set it in web.config for project scope. Page Directive Solution <%@ Page Language= "C#" AutoEventWire

Set Url Parameter Of $.getJSON() Method Using @Url.Action() In ASP.NET MVC

Here's how you set the first parameter of $.getJSON() which is url using @Url.Action() where GetProductDetails is the action name and Product is the controller name. Make sure to surround it with single quotes. Javascript Code: 1 2 3 4 5 function GetProductData(event) { $.getJSON( '@Url.Action("GetProductDetails","Product")' , function (prod) { alert(prod); }); }

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

How To Wrap Text Inside A JqGrid Cell

Image
When showing records from a datasource, you may wonder why a certain JqGrid cell does not wrap the entire text into it's cell. An example would be a lengthy description, notes or remarks, and address. After doing some research, the fix is to add a cellattr to the grid's cell and set it's white space property to normal. JqGrid Address Cell without cellattr property 1 { name: 'Address' , index: 'Address' , width: 200, align: 'left' } JqGrid Address Cell with cellattr property 1 2 3 { name: 'Address' , index: 'Address' , width: 200, align: 'left' , cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal;"' }},

How To Integrate JqGrid In ASP.NET MVC 5

Image
Hi, Here's a simple demo using jqGrid in ASP.NET MVC 5 Visual Basic.NET. The detailed instructions are elaborated in VBForums ASP.NET Codebank. The NuGet packages needed are: 1. Dynamic LINQ Library 2. jqGrid 4.6.0 Sample Screenshot: Setup and Source Code: Using jqGrid with ASP NET-MVC 5 Visual Basic.NET

ASP.NET MVC 5 Client Side Form Validation Using jQuery and Bootstrap

Image
Hello, Here's a VB.NET example on how to perform form validation using jQuery and Bootstrap without Model class. Validation is performed purely on the client side. The steps are explained in detail at VBForums codebank ASP.NET MVC 5 Form Validation using jQuery and Bootstrap without Model class and the source code can be downloaded in github MVCFormValidationJQueryValidateVB . Screenshots: That's it.. :-)

ASP.NET MVC 5 jQuery Validation Form.Validate() Method In External JavaScript File Not Firing

I have an external JavaScript file that validates a form using form.validate() of jQuery validation plugin. $( function () { $( "#frmInput" ).validate({ submitHandler: function (form) { //submit once validation rules are met form.submit(); }, .....other codes here }); }); When integrating it in an MVC 5 application, the validate event does not trigger. I have checked if there are errors using the Chrome developer tools and Firefox but to no avail there is none. The solution I discovered was to change the BundleConfig.cs file and the order of scripts rendering in _Layout.cshtml. After that, form validation now works. Steps: 1. Change BundleConfig.cs codes //change code in BundleConfig.cs From:   bundles.Add( new ScriptBundle( "~/bundles/jqueryval" ) .Include( "~/Scripts/jquery.validate*" ));   //To: (individual bundling of validate and unobtrusive js files)   bundles.

ASP.NET MVC 5 Client-Side Remote Validation Using jQuery

Image
When integrating jQuery validation in ASP.NET MVC, here's how to apply client-side remote validation using javascript code. Below are the snippets and screenshots. Make sure to render the jquery.validate.min.js file in your View or Layout. Email HTML Markup: 1 2 3 4 5 6 7 <div class= "form-group has-feedback" > <label for= "email" class= "control-label col-md-3" >Email Address:</label> <div class= "col-md-9" > <input type= "email" name= "email" id= "email" class= "form-control" placeholder= "Enter email" /> <span class= "glyphicon form-control-feedback" id= "email1" ></span> </div> </div> Custom Javascript Validation 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 $( function () { $( "#frmInput" ).validate({ sub

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" > <

ASP.NET MVC 5 Client-Side Form Validation Using jQuery And Bootstrap With Model Class

Image
Here's a simple client side validation in ASP.NET MVC 5. By default, the application's unobtrusive validation has been set to true in web.config file. For this demo, I did not include a saving process to database. I just added a simple view to indicate a success if the model passed to the controller is valid. See files and screenshots below: Registration.cs (This should be created inside the Model folder) 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 public class Registration { [Required(ErrorMessage = "You must provide your first name")] [Display(Name = "First Name")] public string FirstName { get ; set ; } [Required(ErrorMessage = "You must provide your last name")] [Display(Name = "Last Name")] public string LastName { get ; set ; } [Required(ErrorMessage = "You must provide your middle name")]

$(...).valid is not a function in ASP.NET MVC 5

Image
I created an ASP.NET MVC 5 simple application with entry forms integrating bootstrap and jQuery validation. Upon testing, the valid() built-in function is not recognized by the browser as stated in the title of this post. After series of investigation, I found out that by default, ASP.NET MVC does not render the jQuery validation scripts by default in _Layout.cshtml. Only jQuery core scripts. The fix is to render jqueryval validation scripts in _Layout.cshtml. The scripts have already been bundled in the BundleConfig file. @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @*code fix*@ @Scripts.Render("~/bundles/bootstrap") On page load, the scripts are indeed rendered to the browser using chrome dev tools.

Draggable Is Not A Function In ASP.NET MVC

Image
Here's what I did in order to recognize the draggable function in one of my asp.net mvc page. 1. Add jquery-ui.js to scripts folder. 2. Bundle the js file in BundleConfig.cs 3. Render the bundled script in _Layout.cshtml. Cheers! :-)

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

jQuery Intellisense Not Working In External Javascript File Using Visual Studio 2013

Image
Hello, In order for the jQuery intellisense to work in Visual Studio 2013, perform the following steps. 1. Proceed by clicking Tools -> Options -> Text Editor -> JavaScript -> Intellisense -> References. 2. Change Reference Group to Implicit (Web)   By default a reference has been added to _references.js. If not, add a new reference file under Scripts folder. 3. Open _references.js file using your Visual Studio IDE or any text editor software. 4. Add reference path to jquery files (.js, .min.js, and .intellisense.js). 5. Close Visual Studio and Open it again. (I was struggling for hours as to why performing steps 1 through 4 didn't work. This step fixed the issue) Reference: jQuery intellisense not working in VS 2012 Regards, :)

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

Donate