ASP.NET (35) SQL (25) JAVASCRIPT (24) HTML (14) STYLE SHEET (6) ASP (4) SCRIPT (1)

Search me out HERE!!

Showing posts with label JAVASCRIPT. Show all posts
Showing posts with label JAVASCRIPT. Show all posts

Autofill textbox with Ajax along with value

See below steps to Autofill textbox with Ajax with list of items along with value. Also value will be fetched once any of item is selected from list.

1. Add onkeyup event on textbox to autofill textbox as user start typing in textbox.

onkeyup=KeyUpEvent('txtSearch','1');


2. Add below javascript method which will be called on keyup event of textbox. This method will be used to make Ajax call and get item list with value.

function KeyUpEvent(txtBoxId, id) {
    try {
        if (txtBoxId != null) {
            $("#" + txtBoxId).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: 'PageName.aspx/ListItemKeyValue',
                        data: "{'prefix':'" + $('#' + txtBoxId).val() + "','Parameter1':'" + id + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                   label: item.split('/')[0],
                                   val: item.split('/')[1]
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                        }
                    });
                },

                select: function (event, ui) { alert(ui.item.val); return false; },
                minLength: 3
            });
        }
    }
    catch (e) {
       alert('Error: ' + e);
    }
}


3. Write below web method in .cs file of page to fetch item from database based on value passed from Javascript method.

[WebMethod]
public string[] ListItemKeyValue(string prefix, int Parameter1)
{
    List items;
    Data objData = new Data();
   
//Fetch data into Datatable    System.Data.DataTable dt = objData.GetListItemKeyValue(Parameter1, prefix).Tables[0];
    items = new List(dt.Rows.Count);
    for (int intI = 0; intI < items.Capacity; intI++)
    {
       items.Add(string.Format("{0}/{1}", dt.Rows[intI]["Name"].ToString(), dt.Rows[intI]["Value"].ToString()));
    }
    return items.ToArray();
}

Getting selected value from RadioButtonList in Javascript


Consider below ASP.Net RadioButtonList control:
<asp:RadioButtonList ID="rbList" runat="Server">
   <asp:ListItem Text="Kapil" Value="1" Selected="True">
   <asp:ListItem Text="Baheti" Value="2">
</asp:RadioButtonList>

You can now get selected radio button value using below javascript:
function GetRadioButtonValue()
{
  var id = <%= rbList.ClientID %>;
  var radio = document.getElementsByName(id);
  for (var i = 0; i < radio.length; i++)
     {
        if (radio[i].checked)
           alert(radio[i].value);
     }
}

Get file name from path using Javascript

Using below javascript function you can get file name from path:

function GetFileName()
{
   var fullPath = 'http://kapilgbaheti.blogspot.in/2012/08/get-file-name-from-path.html';
   var filename = fullPath.replace(/^.*[\\\/]/, '');
   alert(filename);
}

You output will be : get-file-name-from-path.html

Get Screen Width and Screen Height using Javascript

Below is code to get Screen Width and Height using Javascript;

function getScreenInfo()
{
    var w = screen.width;
    var h = screen.height;
    alert("Screen Width :" + w + ", Screen Height:" + h);
}

Note: You cannot get screen width/height in ASP.net server side code, you need to manage it using Javascript.

Disable Copy Paste Cut options in textbox using javascript in ASP.NET

Below is example to disable COPY, PASTE and CUT option in textbox:

<asp:TextBox ID="TextBox1"runat="server"oncopy="return false" oncut="return false" onpaste="return false" ></asp:TextBox> 

Difference between jQuery object and DOM element(Javascript Object)

Below given is relation between JQuery object and DOM element (i.e. Javascript object), Using this you can convert JQuery object into javascript object and apply formulas of javascript on it.

Consider Below Div
<div id="foo"></div>

Now below 3 alert will give same Javascript object (On which javascipt function can be performed)
alert($("#divTest")[0]);  //Jquery
alert($("#divTest").get(0));  //Jquery
alert(document.getElementById("divTest"));  //Javascript

Scroll two div/table together (Horizontal and Vertical)

Below is code to scroll 2 div/table together:


< div id="div1" style="width:400px !important; height: 150px !important; overflow: auto; border: 1px solid Black;" onscroll="scrollDiv('div1', 'div2', 1)" >
    < table border="0" cellpadding="0" cellspacing="0" width="500px" >
        < tr >
            < td align="center" >

< br / >ASP.Net< br / >< br / >SQL Server< br / >< br / >JavaScript< br / >< br / >JQuery< br / >< br / >AJAX< br / >< br / >HTML< br / >< br / >CSS< br / >< br / >

            < /td >
            < td align="center" >

< br / >HTML< br / >< br / >PHP< br / >< br / >WCP< br / >< br / >SilverLight< br / >< br / >Jhoomla< br / >< br / >ASP< br / >< br / >StyleSheet< br / >< br / >

            < /td >
        < /tr >
    < /table >
< /div >

< div id="div2" style="width:400px !important; height: 150px !important; overflow: auto; border: 1px solid Black;" onscroll="scrollDiv('div1', 'div2', 2)" >
    < table border="0" cellpadding="0" cellspacing="0" width="500px" >
        < tr >
            < td align="center" >

< br / >ASP.Net< br / >< br / >SQL Server< br / >< br / >JavaScript< br / >< br / >JQuery< br / >< br / >AJAX< br / >< br / >HTML< br / >< br / >CSS< br / >< br / >

            < /td >
            < td align="center" >

 < br / >HTML< br / >< br / >PHP< br / >< br / >WCP< br / >< br / >SilverLight< br / >< br / >Jhoomla< br / >< br / >ASP< br / >< br / >StyleSheet< br / >< br / >

            < /td >
        < /tr >
    < /table >
< /div >
           
< script type="text/javascript" >
    function scrollDiv(divA, divB, divNo) {
        var div1 = $('#' + divA);
        var div2 = $('#' + divB);
        if (!div1 || !div2) return;
        var control = null;
        if (divNo == 1) control = div1;
        else if (divNo == 2) control = div2;
        if (control == null) return;
        else {
            div1.scrollLeft(control.scrollLeft());
            div2.scrollLeft(control.scrollLeft());
            div1.scrollTop(control.scrollTop());
            div2.scrollTop(control.scrollTop());
        }
    }
< /script >

Handle all javascript errors


Placing this code manage all javascript error from one place
window.onerror=errorhandle
function errorhandle()
{
alert('error occured');
return true
}

Add option to dropdownlist using JavaScript.

//Use following JavaScript to Add option to dropdownlist
function addDropDownOption(Dropdown,text,value)
{
var sportOption = document.createElement(“option”);
sportOption.text = text;
sportOption.value = value;
Dropdown.options.add(sportOption);
}

Get screen resolution and set style from javascript

function setLogoOnLowScreenRes()
{
if ((window.screen.width<=800))
{
//you can apply styling for screen resolution 800
document.getElementById("wrapper").style.marginLeft = "58px";
}
else if((window.screen.width<=1024))
{
//you can apply styling for screen resolution 1024
document.getElementById("wrapper").style.marginLeft = "69px";
}
}

Add to BOOK MARK using Javascript

Below JavaScript can be used to set Book Mark link

JAVASCRIPT:
<script type="text/javascript">
function bookmarksite(title,url){
if (window.sidebar) // firefox
    window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
}
else if(document.all)// ie
    window.external.AddFavorite(url, title);
}
</script>


HTML CODE:
<a href="javascript:bookmarksite('Google', 'http://www.google.com')"> Add to Favorites </a>

To Fetch FORM Element value directly in JAVASCRIPT

Below example show how to fetch Form Element value directly in Javascript without use of Document.form

JAVASCRIPT:
<script language="javascript">
function checkTestForm()
{
    with (window.document.frmTest)
    {
        alert(txtPrice.value);       
    }
   
}

</script>

HTML CODE:
<form id="frmTest" name="frmTest" method="post">
<input type="text" id="txtPrice" name="txtPrice" />
<input type="button" id="btn" name="btn"  value="OK"   onclick="return checkTestForm();" />
</form>

Setting TEXTBOX Background Image and Color Using JavaScript & CSS

Consider below textbox:
<input type="text" id="textbox_name" />

Now you can apply BACKGROUND COLOR or BACKGROUND IMAGE using below JAVASCRIPT or CSS
// USING STYLE CSS
.textbox
{
background-color:#FFFFFF;
background:url(images/test.jpg);
}

// USING JAVASCRIPT
function set_background
{
document.getElementById('textbox_name').style.backgroundColor = '#FFFFFF'; document.getElementById('textbox_name').style.backgroundImage="url(images/test.jpg)";
}

TO FIND BROWSER USING JAVASCRIPT

Using below JavaScript you can get information about browser.

<script language="JavaScript" type="text/javascript">
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;    // For IE
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;  // For Firefox
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;  // For Opera
alert(isIE);
alert(isWin);
alert(isOpera);
</script>

Count Number of letter in Textarea or Textbox using Javascript

Kindly write anything in Textbox:


Characters left

Code:
Javascript Function:
<script language="javascript">
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
</script>


HTML
<form name="frm">
<textarea name="comments" id="comments" cols="30" rows="4" wrap="physical" onKeyDown="textCounter(document.frm.comments,document.frm.remLen1,100)"onKeyUp="textCounter(document.frm.comments,document.frm.remLen1,100)" tabindex="14"> </textarea>
<br />
<input readonly type="text" name="remLen1" style="border:0; width:30px;" size="3" maxlength="3" value="100"> Characters left
</form>


Calendar using Javascript


DEMO:

Date: 


   (Click in Textbox)

Click on below link to Download .js file
Click Here

Code for HTML Page
<script language="javascript" type="application/javascript" src="scw.js"></script>

Date:<input  type="text" name="test" onselect='scwShow(this,event);' onclick='scwShow(this,event);' readonly="readonly" />

How to disable HTML attribute using JAVASCRIPT

Below JavaScript can be used to disable HTML Attributes during run time. (Eg: TextBox, Select Box, Check Box, Radio Button, Etc)

<script>
window.onload= function()
{
          DisableEnableForm(document.frmwitness,true);
 }

function DisableEnableForm(xForm,xHow){
  objElems = xForm.elements;
  for(i=0;i
  {
       var ck = objElems[i].type;
       if(ck=="select-one" || ck=="text")
      {
          objElems[i].disabled = xHow;
       }
   }
}
</script>


Note: You can call above function as per requirement.

VALIDATE FILE EXTENSION USING JAVASCRIPT

This Javascript can be used to allow only few file extension only.

Include Below Script
<script>
    function validateFileExtension(fld)
    {
        if(!/(\.zip|\.rar|\.doc|\.docx|\.ppt|\.xls|\.xlsx|\.pptx|\.jpg|\.jpeg|\.pdf)$/i.test(fld.value))         

       {
            alert("Invalid image file type.");
            fld.value='';
            fld.focus();
            return false;
        }
        return true;
    }

</script>

Call above function in HTML as given below:
<input type="file" name="uploadFile1" id="uploadFile1" onchange="return validateFileExtension(this)" />

Note:
Here as mention in Javascript only file with .zip, .rar, .doc, .docx, .ppt, .xls, .xlsx, .pptx, .jpg, .jpeg, .pdf  will be allowed. This can be changed as per requirement.

Allow only numeric value through Javascript

Below JavaScript will allow only to enter numeric value in Textbox. This javascript can be used for Mobile number, Salary, Budget, etc.

Include below JavaScript
<script language="javascript" type="text/javascript">
function isNumber(field)
{
    var textbox = document.getElementById(field);
    var re = /^[0-9]*$/;
    if (!re.test(textbox.value))
    {
        textbox.value = textbox.value.replace(/[^0-9]/g,"");
    }
}

</script>

Call this fuction in HTML as given below:
<input type="text" name="test" id="test" onkeyup="isNumber('test');" />

HOW TO GET POSITION OF PARTICULAR OBJECT USING JAVASCRIPT

Below JavaScript function is used to get position of any object.

function findPos()
{
      //Here 'myTextbox' is object whose position is calculated.
      obj = document.getElementById('myTextbox');
      var posX = obj.offsetLeft;
      var posY = obj.offsetTop;
      while(obj.offsetParent)
     {
      posX=posX+obj.offsetParent.offsetLeft;
      posY=posY+obj.offsetParent.offsetTop;
      if(obj==document.getElementsByTagName('body')[0]){break}
      else{obj=obj.offsetParent;}
      }
//posX and posY are postion of required object.
}