Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Sunday, November 19, 2017

JQuery Load Javascript Dynamically | Dynamic JS Loading

JQuery Load Javascript Dynamically | Dynamic JS Loading



var script = document.createElement("SCRIPT");
script.src = '//code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
script.onload = function() {
    var nj = jQuery.noConflict(true);
    alert(jn.find("body").length);
};
document.getElementsByTagName("head")[0].appendChild(script);














Friday, November 17, 2017

JQuery Custom Checkbox Example | Checkbox Customization

It's easy to customize checkbox.



if (app === undefined) var app = {};
app.customCheckBox = (function() {
    var prop = null;

    function base() {
        if (!prop) {
            prop = $.prototype.prop;
            $.prototype.prop = function() {
                var elem = $(this), result = prop.apply(this, arguments);
                if (elem.is(".custom-checkbox-base-element")) {
                    elem.trigger("update_view");
                }
                return result;
            };
        }
    }

    return {
        convert: function(page) {
            base();

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').each(function() {
                var cb = $(this);
                cb.after("<span class='custom-checkbox-selection'></span>");
                if (cb.is(":checked")) cb.next().addClass("selected");
                cb.hide();
            });

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').change(function() {
                var cb = $(this);
                cb.next().trigger("update_view");
            });

            page.find('input[type="checkbox"]:not(.custom-checkbox-base-element)').on("update_view", function() {
                $(this).next().trigger("update_view");
            });

            page.find(".custom-checkbox-selection:not(.complete-event-compile)").click(function() {
                var elem = $(this), cb = elem.prev();
                if (elem.is(".selected")) {
                    elem.removeClass("selected").trigger("update_view");
                    cb.prop("checked", false).trigger("change");
                }
                else {
                    elem.addClass("selected").trigger("update_view");
                    cb.prop("checked", true).trigger("change");
                }
            });

            page.find('.custom-checkbox-selection:not(.complete-event-compile)').on("update_view", function() {
                var elem = $(this), cb = elem.prev();
                if (cb.is(":checked")) {
                    elem.addClass("selected");
                }
                else {
                    elem.removeClass("selected");
                }
            });
            page.find(".custom-checkbox-selection").addClass("complete-event-compile");
            page.find('input[type="checkbox"]').addClass("custom-checkbox-base-element");
        }
    };
}());








Thursday, November 16, 2017

JQuery form submission dynamically | Dynamic form submission

Below is the JQuery code snippet shows how to submit form dynamically:



<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("button").click(function () {
            var form = $("<form>", {
                'action': 'your-desired-url-here',
                'target': '_top'
            });
            $(document.body).append(form.hide());
            form.submit();
        });
    });
</script>

<button>Submit</button>










Tuesday, November 14, 2017

JQuery JavaScript Select All Text In Content Editable Div

JQuery JavaScript Select All Text In Content Editable Div


jQuery.fn.selectText = function(){
   var doc = document;
   var element = this[0];
   if (doc.body.createTextRange) {
       var range = document.body.createTextRange();
       range.moveToElementText(element);
       range.select();
   }
   else if (window.getSelection) {
       var selection = window.getSelection();        
       var range = document.createRange();
       range.selectNodeContents(element);
       selection.removeAllRanges();
       selection.addRange(range);
   }
};

JSFiddle link



Saturday, November 11, 2017

Thursday, November 9, 2017

jQuery Number Text Field Validation Using Regex On Input Field

jQuery Number Text Field Validation Using Regex

Below is the full example of how to validate number using regex


var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)");

$(document.body).on("keypress", "input[type='text'].number", function (e) {
    if (e.which == 0 || e.which == 8) return true;
    var v = getTextFieldValue(this, String.fromCharCode(e.which));
    $("div").html(v);
    return pattern.test(v);
});

document.addEventListener("paste", function (e) {
    var v, f = $(e.target), ov = f.val();
    if (window.clipboardData && window.clipboardData.getData) { // IE
        v = window.clipboardData.getData('Text');
    }
    else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
        v = e.originalEvent.clipboardData.getData('text/plain');
    }
    else if (e.clipboardData && e.clipboardData.getData) {
        v = e.clipboardData.getData('text/plain');
    }
    v = getTextFieldValue(f[0], v);
    if (!pattern.test(v)) e.preventDefault();
    $("div").html(v);
});

function getTextFieldValue(input, nv) {
    var v = input.value, i = input.selectionStart, j = input.selectionEnd;

    if (i == 0 && j == v.length) return nv;
    else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j);
    else if (i == 0) return nv + v;
    else return v + nv;
}

$("input[type='text'].number").focus();


And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$

You can experience above example in JsFiddle

You can also check in regex test environment





Thursday, November 2, 2017

JavaScript | jQuery Validate Email Address Using Regex Pattern Check


var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;





And you can check your desired input by:




pattern.test("pritomkucse@gmail.com"); 

Sunday, September 3, 2017

jQuery get exact position of element | get exact left top position of jQuery element

Below is code snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Position of Element</title>
    <script src="jquery-2.1.4.js"></script>
    <script type="text/javascript">
        $(document.body).ready(function() {
            var body = $(document.body), element = body.find(".element"),
                    log = body.find(".log");
            var rect = element[0].getBoundingClientRect();
            log.append("<p>LEFT==" + rect.left + "</p>");
            log.append("<p>TOP==" + rect.top + "</p>");
            log.append("<p>RIGHT==" + rect.right + "</p>");
            log.append("<p>BOTTOM==" + rect.bottom + "</p>");
            log.append("<p>WIDTH==" + rect.width + "</p>");
            log.append("<p>HEIGHT==" + rect.height + "</p>");
        });
    </script>
</head>
<body style="margin:0">
<div style="position:relative;width:100%;height:100%;margin:0">
    <div class="element" style="position:absolute;margin:0;left:170px;top:200px;border:1px solid red;width:100px;height:30px;"></div>
</div>
<div class="log" style="font-weight:bold;"></div>
</body>
</html>

And output is below:


Wednesday, June 21, 2017

JavaScript | jQuery: Manual Ajax Form Submit Using XMLHttpRequest | XMLHttpRequest to Post HTML Form | Upload File Ajax | Submit FormData

It's easy to submit an form using JavaScript ajax request. We also can upload files using ajax form submit. Below is a simple code snippet:


<form name="content_info">
    <input type="file" name="file"/>
    <button type="button" onclick="doPost()">Ajax Submit</button>
</form>

<script type="text/javascript">
    function doPost() {
        var form = document.forms.namedItem("content_info");
        var formData = new FormData(form);
        //or formData = new FormData();
        formData.append("custom_param", "custom_param_value");

        var request = new XMLHttpRequest();
        request.open("POST", "submit.php", true);
        request.responseType = "json";
        request.onload = function(oEvent) {
            console.log(request.status);
            console.log(request);
            console.log(request.response);
            alert(request.status);
        };
        request.onerror = function (error) {
            console.log(error);
        };
        request.setRequestHeader("Custom-Code", "EKKODJIU");
        request.send(formData);
    }
</script>




Saturday, June 3, 2017

jQuery Script: Remove next element by class name

Its very easy to remove next element by checking class is matches or not. You can also remove previous element as well as next element.

$(".base").prev(".search").remove();

<script src="3.2.1/jquery.min.js"></script>

<div class="base">ELEMENT 1</div>
<div class="will_not_remove">ELEMENT WILL NOT REMOVE</div>
<div class="remove">HAS CLASS "REMOVE" BUT WILL NOT REMOVE</div>
<div class="base">ELEMENT 2</div>
<div class="remove">ELEMENT WILL REMOVE</div>

<script type="text/javascript">
    $(".base").next(".remove").remove();
</script>



Thursday, May 18, 2017

jQuery UI Popup Dialog Simple Example

Its fairly easy to implement jQuery popup dialog. You just need to include jQuery UI JS and CSS in your project and need to call the method as follows:

.dialog() with additional options as you want.

$("#dialog-form").dialog({
    title: "Dialog Title",
    width: 500,
    height: 400,
    autoOpen: false,
    modal: true,
    buttons: {
        "Ok": function() {
            $('#buttonExecute').val("Show Dialog - Yes");
            $(this).dialog("close");
        },
        "Cancel": function() {
            $('#buttonExecute').val("Show Dialog - No");
            $(this).dialog("close");
        }
    },
    close: function( event, ui ) {
        console.log(event);
        console.log(ui);
    },
    open: function( event, ui ) {
        $('#buttonExecute').val("Show Dialog - Open");
    }
});

$('#buttonExecute').click(function() {
    $("#dialog-form").dialog("open");
});


Which will show dialog as below screenshot:




You can download full example from below link:

Click here to download.


Wednesday, May 10, 2017

jQuery Nice Select Plugin with Position And OptGroup Support

Nice Select is a small plugin to show html select in stylish way. But there are some limitations such no optgroup support. And positioning is not supported yet. I come up with this two problems and below is the code a screenshot.

First download Nice Select plugin from link below:


https://drive.google.com/drive/folders/0B5nZNPW48dpFcjhqQTItSGkxMlk?usp=sharing

<link rel="stylesheet" type="text/css" href="nice-select.css"/>
<script src="jquery-2.1.1.min.js"></script>
<script src="jquery.nice-select.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("select").niceSelect();
    });
</script>


Friday, April 28, 2017

jQuery UI Sortable and Draggable NOT working on iPad, iPhone or Android

jQuery UI sortable, draggable, re-sizable and all others working fine on browsers with no problems, however when I test it on hand held devices such as iPad, iPod, iPhone and Android it doesn't work. I cannot drag the boxes or sort the order at all.

Touch Punch will fix this issue, and most other jQuery UI on touch device problems. They described the process as hack, but it it is a lifesaver too.

Also you can download library from here.

Friday, March 17, 2017

Copy text value to clipboard using jQuery

Its very important task for us to able to copy some value to clipboard using jQuery. Its now so much easy to make it without any hassle. Almost all browser support it. Its nothing but use some jQuery code to make it easier.


function copyTextToClipboard($value) {
    var $temp = $("<input>");
    $(document.body).append($temp);
    $temp.val($value).select();
    document.execCommand("copy");
    $temp.remove();
    alert("Text copied to your clipboard");
}

Saturday, February 11, 2017

jQuery extend prototype

It is important that you can extent jQuery to improve your work environment. Below is a code snippet to do this as simple:

If you write your code in some-file.js then follow below:


(function () {
    $.prototype.hi = function () {
        this.html("Prototype invoked...")
        return this
    }
})()

Else if you write your code in <script> tag then follow below:


$.prototype.hi = function () {
    this.html("Prototype invoked...")
    return this
}

Example of usage:


$(".class").hi()

Saturday, January 14, 2017

Abort / Cancel jQuery Ajax Request Example




<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var $xhr = $.ajax({
            url: "search.php",
            type: "POST",
            data: {id: 1, name: "Pritom Kumar"},
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-Test-Header1', 'test-value1');
                xhr.setRequestHeader('X-Test-Header2', 'test-value2');
            },
            dataType: "json"
        }).done(function(data, textStatus, jqXHR) {

        }).fail(function(jqXHR, textStatus, errorThrown) {
            alert("Failed With Reason=" + textStatus);
        });
        setTimeout(function() {
            $xhr.abort();
        }, 100);
    });
</script>


Friday, December 30, 2016

TinyMCE Get Word Counts Using jQuery

Sample code snippet (Full TinyMCE Example)

var log = $(".log"), previous_content = "";
var plugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
];
tinymce.init({
    selector: ".rich_editor",
    setup: function (editor) {
        editor.on('change redo undo', function () {
            editor.save();
            var body = tinymce.activeEditor.getBody();
            var content = tinymce.trim(body.innerText || body.textContent);
            if(content != previous_content) {
                content = $.trim(content.replace( /[^\w ]/g, " "));
                var word_count = content == "" ? 0 : content.split( /\s+/ ).length;
                log.prepend("Word_Count=" + word_count + "<br/>");
                log.prepend("Editor_Text=" + content + "<br/>");
                previous_content = content;
            }
        });
    }
});

Sample output


Simple TineMCE Editor Example With jQuery

Download full example from here

Sample code snippet


var plugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker aa_custom_text aa_inline_image",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
];
tinymce.init({
    selector: "textarea.rich_editor",
    height: 400,
    plugins: plugins,
    contextmenu: "link image inserttable | cell row column deletetable",

    toolbar1: "newdocument | aa_custom_text aa_inline_image | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
    toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | insertdatetime preview | forecolor backcolor",
    toolbar3: "table | hr removeformat code | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",

    menubar: false,
    statusbar: false,
    toolbar_items_size: 'small'
});

Sample output


How to insert an item into an array at a specific index javascript

var arr = ["X1", "X2", "X3", "X4", "X5"];

Inserting "X2.2" into position "2" without deleting "0" item
arr.splice(2, 0, "X2.2");

First Array Values:
X1,   X2,   X3,   X4,   X5

After insert new value:
X1,   X2,   X2.2,   X3,   X4,   X5

Create GUID / UUID in JavaScript


<script type="text/javascript">
    function guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }
    alert(guid());
</script>