Posts

Showing posts with the label Javascript

Javascript show clock in webpage example

Image
This example show how to insert clock on the website which is not static clock, but like a digital clock. Script for Creating Clock 1: <script type="text/javascript"> 2: function updateClock() { 3: var currentTime = new Date(); 4: var currentHours = currentTime.getHours(); 5: var currentMinutes = currentTime.getMinutes(); 6: var currentSeconds = currentTime.getSeconds(); 7: // Pad the minutes and seconds with leading zeros, if required 8: currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes; 9: currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds; 10: // Choose either "AM" or "PM" as appropriate 11: var timeOfDay = (currentHours < 12) ? "AM" : "PM"; 12: // Convert the hours component to 12-hour format if needed 13: currentHours = (currentHours ...

Passing parameter to page using Javascript

This is an example method using javascript to redirect to the searching page with a parameter from the textbox when click the submits button. Requirement JQuery library HTML <div class="input-group search-btn"> <input id="textSearch" type="text" onkeypress="keypressSearch(e);" class="form-control"> <span class="input-group-btn"> <button class="btn btn-default" onclick="return Search();return false;" type="button">SEARCH</button> </span> </div> Javascript <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> function Search() { var txtField = jQuery("#textSearch").val(); document.location.href = "/Search.aspx?searchtext=" + txtField + "&searchmode=anyword...

Update Panel - Handle async partial-page state with client script

This is a sample script you can put at the master page. So that you dont need to have updatepanel progress every time you add the update panel in you aspx page. Script  <div id="pageUpdating"></div>     <script type="text/javascript">         Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);         function BeginRequestHandler(sender, args) {             //page is begin request, you can put code to lock screen etc.               writePageLoading();         }         Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)         function endRequestHandler(sender, args) {             //page load successfully , end request               RemoveLoading();     ...

Jquery - Basic function for beginner

This is a jQuery basic fucntion that developers need to know. Do something after page load successfully $(document).ready(function() {   //do something }); Select Element by id / class var element = $("#idOfElement"); var elementByClass = $(".className"); if have more than one element with same class name var elementByClass = $(".className")[0]; Get selected value (drop down) var selectedValue = $("#isDropdown").val(); //return selected value Or var selectedValue = $("#isDropdown option:selected").val(); //return selected value Get selected text(drop down) var selectedValue = $("#isDropdown").text(); //return selected text Or var selectedValue = $("#isDropdown option:selected").text(); //return selected text Get Textbox Value var valueTextBox = $("#idTextbox).val();   Show/hide element  $("#idElement).show(); or  $("#idElement).fadeIn(500);  $("#idElement).hide(); or  $("#idElement).fadeOut(5...

[SOLVED] JQuery - AJAX 500 Internal Server Error - JSON - jQueryAjax

Image
The above error always occur if you work with jQuery + Ajax. The error above may have several reason why the error occur and one of the reason is you are using the different parameter name to post to the server. Let say the method getState in webservice require one parameter which will represent country name, you must use the exactly name parameter to request from webservice. The Other Reason Not using JSON.stringify to pass parameter value. If you not supply type in jQuery, it will use GET method which is not accept in your webservice configuration. Add  ( type : "POST ) in your jQuery code to use POST method. You are actually request data from different domain. Cross Domain Request (CORS)which is not allowed. Please read here Content type not supply or not correct. Use " application/json; charset=utf-8 " DataType not not supply or not correct. Use json or jsonp By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Fa...

How to add items list in dropdown list using jquery - Cascading drop down

If you want to create 2 dropdown lists in which the second dropdown value will depend on the selected value from the first dropdown, you need to Implement JSON + Webservice+ JQuery. In my solution, I will use Jquery Ajax to request data from web service and add value to the second dropdown. Scenario Let say the first dropdown will list all Country, and the second dropdown will list all state from the selected country. Solution Create JSON Webservice, you can refer to this link Create custom JQuery function to handle onChange event on dropdown list country. Use return value from web services to the second dropdown items list. Full Code Example Note: The web service will use from the post here <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title></title>     <script type="text/javascript...

How to create JSON webservice in ASP.NET

This example will show how to create Webservice using asp.net and the result will return in format JSON ( JavaScript Object Notation ). Below is the step by step to create webservice: Open Visual studio. Create New Project Add New File in the solution and choose Web Service file( .asmx) Copy paste code below to create your own JSON webservice The Web Service Code /// <summary>     /// Summary description for KenticoJSONTest     /// </summary>     [WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     [System.Web.Script.Services.ScriptService]     public class AjaxWebService : System.Web.Services.WebService     {   ...

Dynamically Add/Remove rows in HTML table using JavaScript

Image
This is very often for web developer when we need to use dynamically generate HTML table using JavaScript. The example will spare the first row(cannot delete) and you can dynamically add new row by clicking the button Add Row or delete the row by clicking the button Delete Row . The Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title>Add/Remove dynamic rows in HTML table </title>     <script language="javascript">            function addRow(tableID) {             var table = document.getElementById(tableID);             var rowCount = table.rows.length;             var row = ...

XMLHttpRequest Example with Webservice asp.net

Image
AJAX is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. If you want to retrieve information from server side and you do not want to fully post the entire page to the server side, you need to use ajax in your web page. This post show example how to use simple XMLHttpRequest Object in your web page to get the information from server side. The Javascript AJAX  <script type="text/javascript">         function createXHR() {             if (typeof XMLHttpRequest != "undefined") {                 return new XMLHttpRequest();             } else if (typeof ActiveXObject != "undefined") {                 if (typeof arguments.call...

Disable Back Browser Button in web Page

Image
This example will show how to disable Back button in your browser. To achieve this objective, the javascript will be use to redirect back to the current page if the user click on the browser back button and give message to user. So let see the example. I'll set the script at HEAD element and use onpageshow and  onload event in the body element. The Javascript put in Head element <script type="text/javascript">         window.history.forward();         function noBack() { window.history.forward(); document.getElementById("Message").innerHTML = "You cannot Go Back"; }     </script> The Html/Aspx/Jsp page : : Head element : <body onpageshow="if (event.persisted) noBack();" onload="noBack();" > : : body content  <div id="Message" style="color:red;">  </div> : : </body> </html> The Output If the user click on the browser back button, the script will a...

Javascript - Inline Code VS External Files

Inline Code <html> <head> <script type="text/javascript"> function a() { alert('hello world'); } </script> </head> <body> : : </body> </html> External Files <html> <head> <script type="text/javascript" src="/scriptone.js"> </script> </head> <body> : : </body> </html> scriptone.js function a() { alert('hello world'); } As you can see from the above example,  what is the advantage to put all script in one file and just call it from html( External Code ) instead of just write it in html( inline code ).? The answer is here :  By using external code, the javascript code is much more maintainability :- javascript Code that is sprinkled throughout various HTML pages turns code maintenance into a problem. It is much easier to have a directory for all javascript files so that developers can edit JavaScript code independent of the markup in which it is u...

ReadOnly TextBox causes page back when enter backspace key

Image
As Mention in the title of this post, the browser behavior always think that user want to go back(to previous page) when back space key in entered. So for the read only text box, the edit mode for the text box is not enable hence the backspace key will cause page to go back to previous page. The solution is to put the JavaScript at the Read Only Text Box to prevent page from go back to previous page. The Script  function preventBackspace(e) {              var evt = e || window.event;              if (evt) {                  var keyCode = evt.charCode || evt.keyCode;                  if (keyCode === 8) {                  ...

Get query string value JavaScript

Image
Query string is a one solution to pass the value from one page to another without use session. It is just keys and value pass through url. Suppose the web application want to get the query string value at client side for the validation on the client side. So i use JavaScript to solve this. Here my JavaScript function to return query string...just pass the key for the query string in the function parameter and you will get the value of query string... Lets take a look at the example : The Javascript        function querystring(key) {             var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');             var r = [], m;             while ((m = re.exec(document.location.search)) != null) r.push(m[1]);             var stringQuery =...