Posts

Showing posts with the label Javascript

Disable button after click in asp.net

To prevent double submit a form by user we need to restrict the user to click the button again. The idea is that we will use JavaScript to disable the button once user clicks first time. Add the following lines on .aspx page <asp:Button ID="btnProcess" runat="server" onclick="btnProcess_Click" Text="Process" /> Add the following line on .aspx.cs page (Page_Load). string strProcessScript = "this.value='Processing...';this.disabled=true;"; btnProcess.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(btnProcess, "").ToString()); This will disable Button, and then change the text of the button " Processing... ", and then continue on with the server side event btnProcess_OnClick event handler.

File extension validation using javascript in MVC

This is article which demonstrate the validation of allowed file extension for upload of files in MVC using javascript. In this article i have used validation for valid image format like Jpeg, Jpg,Gif and png image format. If users ties to upload any other file apart from above mentioned file then the javascript function will shows proper message to user to select appropriate files. I have used html input file control for uploading of files in MVC application. following is the html code for it. <body> <div style="height:50px; padding-bottom:20px;"> @using (@Html.BeginForm("Create","FileUpload",FormMethod.Post,new{ enctype = "multipart/form-data"})) { <input type="file" id="file1" name="sdf" style=" margin-top:0px;" onchange="if( CheckExtention(this.value) ) {parent.ShowHideImage(true);this.form.submit();}" /> } </div> </body> and followi

Numeric validation on textbox/input on keydown event using JQuery

This is simple way to implement the numeric validation on textbox or input control using jquery. Firstly you need to use jquery selector for binding the keydown event to input control. Once you bind it it will only allow numeric keys and reject the alphabetical keys. Following is the code snippet of the numeric validation using Jquery. $(document).ready(function () { $("#MobileNo").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.k

Call server side methods asynchronously without having a postback using callback in asp.net

Callback is another fabulous way to communicate with server for light weight tasks. While working in ASP.NET, sometimes we need to call server side methods asynchronously without having a postback. Sometimes it is either a full page postback or partial page postback. To Implement callback in asp.net following interfaces to me implement in the asp.net page ICallback ICallbackEventHandler Let us first implement ICallbackEventHandler to call the server side method asynchronously step-by-step. The following are the definition of two methods which we need to implement. RaiseCallbackEvent method invoke through JavaScript function. public void RaiseCallbackEvent(string eventArgument) { //populate Customer object to return Customer customer = new Customer(); customer.Name = "Muhammad Adnan"; customer.Age = 24; //javascript serialization of Customer object System.Web.Script.Serialization.JavaScriptSerializer jss; jss = new System.Web.Script.Serializa

Populate Dropdown with jquery using JSON request in asp.net mvc3

In this Article, I am going to demonstrate to fill the dropdownlist with J query using JSON in asp.net mvc3 . To achieve this task we need to write the following JavaScript code in view ( .cshtml page). @{ ViewBag.Title = "Products"; } <script type="text/javascript"> jquery(document).ready(function () { jquery("ddlCategory").change(function () { var idModel = jquery("#ddlCategory").val(); jquery.getJSON("product/items/", { category: idModel }, function (carData) { var select =jquery("#ddlitems"); select.empty(); select.append($('<option/>', { value: 0, text: "" })); jquery.each(carData, function (index, itemData) {

ASP.NET Redirect to open a new browser window using javascript window.Open method

To  redirect the page in new window there is no readymade methode in asp.net. To overcome this lack of readymade function, we need to do some custom coding and it will only achieve by using javascript Window.Open Methode. I have created the methode in c#.nnet to redirect the desired page in new window. Following is my methode defination.. public static void Redirect(string url, string target, string windowFeatures) { HttpContext context = HttpContext.Current; Page page = (Page)context.Handler; string script; if (!String.IsNullOrEmpty(windowFeatures)) { script = @"window.open(""{0}"", ""{1}"", ""{2}"");"; } else { script = @"window.open(""{0}"", ""{1}"");"; } script = String.Format(script, url

Highlight gridview row in update panel without posting back in asp net

When user selects particular row of gridview then that row should be highlighted. but in asp.net you do not have mechanism to to this task automatically. For this purpose you need to write some custom code, which includes some JavaScript code. to highlight the row selected by user follow the step below For this you have to write this code in your code behind file in OnRowCreated event or your can also write this code in OnRowDataBound event of grid... protected void ctlGridView_OnRowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')"); } } then add following script to your aspx page in script tag <script language="javascript" type="text/javascript"> var gridViewCtlId = '<%=ctlGridView.ClientID%>

How to get/find height and width of window using javascript

By knowing heigth and width of window we can place divs, messages,status wherever we want by using top left property of element. for that you should provide value of top and left to view in different monitors to get dynamic top left position you must find out the window width & height. following code will demostrate you to find out the window width & height which supports in  almost all browsers .   function windimension(){ if(window.innerHeight !==undefined) { var width= window.innerWidth; var height=window.innerHeight]; // most browsers } else{ // IE varieties var D= (document.body.clientWidth)? document.body: document.documentElement; var width= D.clientWidth; var height=D.clientHeight; } } Hope this will help u.......

Adding events to DOM Elements in javascript by For IE, Mozilla, Opera browsers

To add events to DOM element Dynamically using javascript needs to write different code for different browsers. Browsers Like Mozilla, Opera support the "W3C DOM Level 2 event binding mechanism"  which uses a function on DOM elements called addEventListener.  Following the way to  add events to DOM element Dynamically for all browser. if (window.addEventListener != null) { // Method for browsers that support addEventListener, e.g. Firefox, Opera, Safari window.addEventListener("focus", FocusFunction, true); window.addEventListener("blur", FocusLostFunction, true); } else { // e.g. Internet Explorer (also would work on Opera) window.attachEvent("onfocus", FocusFunction); document.attachEvent("onfocusout", FocusLostFunction); //focusout only works on document in IE }  Hope this will help you guys........

Creation of Date Format function using javascript and Jquery

If you want to format the datetime string of database in your html file you need to get help from JavaScript.In javascript there is no pre define function exists to format date time string in dd MMM yyy. To accomplish the above task you need to write custom code. The following  is the custom function by using that you can format your date-time string in dd MMM yyyy format first you need to write array which has all months var gsMonthNames = new Array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ); Then add following function in html file function dFormat(date) { var result = ''; if (date != '') { var dateArray = date.split('/'); if (dateArray.length > 1) { result = dateArray[1] + " " + gsMonthNames[parseInt(dateArray[0])-1] + "

Add Comma automatically while entering amounts in textbox using Javascript

Use following JavaScript function to add comma in numeric input in textbox function Comma(Num) { Num += ''; Num = Num.replace(/,/g, ''); x = Num.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d)((\d)(\d{2}?)+)$/; while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2'); return x1 + x2; } Use following event of input textbox to call above function onkeyup = "javascript:this.value=Comma(this.value);"

Prompt user before navigate away from current page where user typed some text using javascript

In your application suppose user putting the data, then user accidently click the outside link or clode button of browser. In this situation user may loose his entered data. To avoid this we can propmt user about his unsaved data by using symple javascript code. This code will prompt the user about unsaved data in current page. following is the javascript code snippet  <html> <head> <title>window.onbeforeunload example</title> <script type="text/javascript"> var unsaved = false; window.onbeforeunload = function() { if (unsaved) { return "You have unsaved data. Are you sure you wish to leave this page."; } }; </script> </head> <body> <input type="text" id="input1" onkeydown="unsaved = true;"/> <input type="submit" id="input1" onclick="unsaved = true;"/> </body> </html> Try your self and let me know your c

Javascript print() method not printing Images ? then no problem i have a solution

If you are using window.Print() method of javascript to print the page but it prints only letters and does not print images of the page then use following solution for this problem firstly try to use absolute url path in images src attribute like http://something.com/imger.jpg then it will be render correctly secondly copy and paste below code in script tag  function printContent(id){ var str=document.getElementById(id).innerHTML newwin=window.open('','printwin','left=0,top=0,width=1,height=1,menubar=no') newwin.document.write('<HTML>\n<HEAD>\n') newwin.document.write('\n') newwin.document.write('<script>\n') newwin.document.write('function chkstate(){\n') newwin.document.write('if(document.readyState=="complete"){\n') newwin.document.write('window.close()\n') newwin.document.write('}\n') newwin.document.write('else{\n') newwin.document.write('setTime