Friday 26 April 2013

Javascript/Jquery tricks

Apply below tricks in your code and see the results.  

1. Calling  server side function from javascript


        function CallServerSideFuncFromJavascript(name, sender) {
        var url = "/testfolder/myfunc";

        var data = "value=" + name;
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            success: function (value) {
                if (value != "Null") {
                    sender.SetText(value);
                }
            }
        });
    }


2. Validating SSN through javascript


    function ValidateSSN(s, e) {
        var value = s.GetValue();

        if (value != null && value.trim().length > 0) {
            len = 10 - value.trim().length;

            value = len > 0 ? new Array(len).join('0') + value : value

            s.SetValue(value.toUpperCase());
        }

    }


3. Restrict user entering specific values:

<input type="text" onkeypress="return  ValidateText(event);" />

    function ValidateText(evt)
{
var value = String.fromCharCode(evt.which ? evt.which : evt.keyCode);
if(value=="^" || value=="<" || value=="*")
{
return false;
}
return true;
}

4. Enable/ Disable button through jquery


To disable a button:

$("input[type=submit]").attr("disabled", "disabled");
or
$("#btnSubmit").attr("disabled", "disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").attr("disabled", "disabled");
});


To enable a button:

$("input[type=submit]").removeAttr("disabled");
or
$("#btnSubmit").removeAttr("disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").removeAttr("disabled");
});

We can use it with any html control. functionality will be same.


5. Check if text in  textbox is selected or not.

 function CheckTextSelectionInTextBox(ctrl) {
        if (document.selection != undefined) {
            var sel = document.selection.createRange();
            selectedText = sel.text;
            if (selectedText != "") {
                return true;
            }
        }
        // Mozilla version
        else if (ctrl.selectionStart != undefined) {
            if (ctrl.selectionStart != ctrl.selectionEnd) {
                return true;
            }
        }
        return false;
    }

<input type="text" onkeypress="return CheckTextSelectionInTextBox(this); " />




I will get back soon with more solutions and tricks.

No comments:

Post a Comment