Wednesday, 19 November 2014

Jquery Tips

//Reset all fields with two lines
function resetFields(){
$('input[type="text"]').val('');
$('select').val('-1');
}

//Get current Date
function currentDate(format) {
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var curDate = "";
if(format == "dd/mm/yyyy") (curDate = (day < 10 ? '0' : '') + day + '/' + (month < 10 ? '0' : '') + month + '/' + d.getFullYear())
    else if(format == "yyyy-mm-dd") (curDate = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day)
    else  (curDate = d.getFullYear() + '/' + (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day)
    return curDate;
}


//For message
function showErrorMessage(elementId,errorMessage){
$(elementId).text(errorMessage).show('fade',1000).hide('fade',2000);
}


//For page reload
function reload(){
location.reload();
}

//For GSTL calculations
<g:set var="totalDefaultFees" value="${0}"></g:set>
<g:set var="totalDefaultFees" value="${totalDefaultFees + due.defaultFeeDue}"></g:set>

//For Date Format in gsp
${formatDate(format:"dd-MM-yyyy", date:holiday.date)}

//Json keys length
Object.keys(data).length

//Populate combobox through map
function populateCombobox(data,elementId){
var options = "<option value=-1>Select..</option>";
$.each(data, function(key, value) {
   options += "<option value="+key+">"+value+"</option>";
});
$(elementId+' option').remove();
$(elementId).append(options);
}


//Remove Particular option in jquery
$("#selectBox option[value='option1']").remove();

//Convert String to Date in Jquery
var d = new Date('1991-09-15');
The date must be 'yyyy-MM-dd' format.. otherwise in jquery the string date can't be converted into date object.

//Convert String to DateTime in jquery
For conversion of DateTime String to date the date format must be like below..
Var d = Date.parse('15/09/1991 05:30 AM')

//Date Comparisions With dates
var d1 = new Date('1991-09-15');
var d2 = new Date('1991-09-14');
(d1 < d2) ? console.log('D2 is bigger') : console.log('D1 is bigger');
Ans : D1 is bigger

//Date Comparisions With datetime
Var d1 = Date.parse('15/09/1991 05:30 AM')
Var d2 = Date.parse('16/09/1991 05:30 AM')
(d1 < d2) ? console.log('D2 is bigger') : console.log('D1 is bigger');
Ans : D2 is bigger


//In text fields enter only alphabets if status is true; otherwise it enters alpha-numeric
function alphabetsValidation(fieldId,status) { $(fieldId).keyup(function(){ var regExp = /^[a-zA-Z]/; // allow only letters var iChars = ""; if(status) iChars = "0123456789!@#$%^&*()+=-_[]\\\';,./{}|\":<>?"; else iChars = "!@#$%^&*()+=-_[]\\\';,./{}|\":<>?"; if (!regExp.test($(fieldId).val())) { $(fieldId).val(''); return false; } else for ( var i = 0; i < $(fieldId).val().length; i++) { if (iChars.indexOf($(fieldId).val().charAt(i)) != -1) { $(fieldId).val(''); return false; } } }); }

1 comment: