Skip to content
Mingtao edited this page Jul 10, 2018 · 68 revisions

jQuery

Basic CSS selector

Selector Description
E F descendants
E > F direct child
E + F direct next sibling
E ~ F next siblings
E[A] has attribute A of any value
E[A^V] start with V
E[A$=V] end with V
E[A!=V] not equal to V, or not have attribute A
E[A*=V] contains V

Position filter

Selector Description
:first first match
:last last match
:first-child first child match
:last-child last child match
:only-child no sibling element, example
:nth-child(n) nth child
:nth-child(even odd)
:nth-child(Xn+Y) every X element + Y example
:even even element
:odd odd element
:eq(n) nth element (starting with 0) example
:gt(n) after nth element example
:lt(n) before nth element example

Custom filter

:button :checkbox :checked :disabled :enabled :file :hidden :image :input :password :radio :reset :selected :submit :visible
Selector Description
:animated ?
:contains('food') element contains the text food
:has(selector) element contains at least one element that matches the specified selector
:header <h1> - <h6>
:not(selector) negates
:parent element that has children (including text), but not empty elements
:text input[type=text]

Wrapped element set methods

toArray(), get(n), first(), last(), eq(n), index(element)

Ready handler

$(function($){
    alert('$ = ' + $);
});

Loop through an array

$.each([2,3], function( index, value ) {
    console.log(index + ":" + value);  
});

Loop through an array of jQuery elements

$('input:radio:checked').each(function () {
    if ($(this).attr('data-showOnClick') != null) {			
        alert($(this));
    }		
});

Select a radio button, Check/Uncheck a checkbox

$("#id).prop("checked", true);

Check a radio button by its name and value

$("input[name='gender'][value='F']").prop("checked", true);

Check radio button's value given the name attribute

var value = $("input[name='gender']:checked");

Check if a checkbox is checked

$('#id').is(":checked");

Click function

$("#id").click(function(event) {
    alert($(this));
});

On function, bind function to dynamically generated elements

$( "#dataTable tbody" ).on( "click", "tr", function() {
    console.log( $( this ).text() );
});

Numbers-only (number and dot), Digits-only (number), Alphanumeric-only (letters and numbers)

//Enable numbers only for numerical inputs 
function numbersOnlyInputs(){
$(".numbers-only").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        // 110 and 190 are for dot(.)
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        // Allow: Ctrl+A, Command+A
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === 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.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
}

function digitsOnlyInputs(){
    $(".digits-only").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === 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.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
}

function alphanumericInputs(){
    $(".alphanumeric-only").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
        }
        if (e.keyCode >= 96 && e.keyCode <= 105){ //0-9 on small keyboard
            return; 
        }
        if (e.keyCode >= 48 && e.keyCode <= 57 && !e.shiftKey){ //0-9 on big keyboard
            return;
        }
        if (e.keyCode >= 65 && e.keyCode <= 90) { //a-zA-Z
            return;
        }
        e.preventDefault();
    });
}

check date is in dd-MM-yyyy or dd/MM/yyyy format

var dateReg = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
dateReg.test(myDate);

replace multiple space with single space

val.replace(/\s+/g, " ");

Check if a date is future date

function isFutureDate(element){
    var selectedDate = element.datepicker('getDate');
    var now = new Date();
    now.setHours(23,59,59,59);
    return selecteDate > now;
} 

Simulate clicking a hyperlink

$('a')[0].click(); //$('a').click() doesn't work

quickly create table

http://jsfiddle.net/sunmingtao/hy734452/8/embedded/result/

Rounding up to 2 decimal points

$('#id').val($('#id').val().toFixed(2));

Check if not undefined

function notNull(v){
    return typeof v !== 'undefined' && v !== null;
}

Sort array in descending order

arr.sort(function(a, b){return b-a});

Convert array to comma separated string

arr.join(", ");

Add custom function to Array prototype

if (!Array.prototype.contains) {
    Array.prototype.contains = function(item) {
        return this.indexOf(item) >= 0;
    }
}

SQL

Oracle

select TO_DATE('1981-08-20, 18:00:00', 'yyyy-mm-dd, HH24:mi:ss') from dual;
select TO_CHAR(SYSDATE, 'yyyy-mm-dd, HH24:mi:ss') from dual;

epoch milliseconds

select (sysdate - TO_DATE('1970-01-01 00:00:00', 'yyyy-mm-dd hh24:mi:ss'))*1000*24*60*60 from dual;
Parameter Explanation
yy Year
YYYY 4-digit year
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
DD Day of month (1-31).
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).

DB2

Find the the column that violates Not null constraint

SELECT * FROM SYSCAT.COLUMNS WHERE TABNAME = 'TISH_ATTACHMENTS' AND COLNO = '13' 

Linux/Unix command

Redirect both stdout and stdin to a file

ls -ld /tmp /tnt > output.txt 2>&1

Groovy

Loop through map list

map.each { id, value ->
  println id +" "+value
}
list.each {
  println it
}

Transform collection

def listAfterTransform = list.collect {
    it + "yes"       
}

SQL

import groovy.sql.Sql;
Sql sql = Sql.newInstance(dbUrl, dbUser, dbPassword, "oracle.jdbc.OracleDriver")
def param = []
param.push('abc')
sql.eachRow(SQL_STR, param) { row ->
    println row.col1 + " " + row.col2          
}

#Intellij

Command Description
Command+Alt+T Wrap try catch

#JVM Print out class loading info. VM Arguments: -verbose:class

Vi help