Javascript Examples


Search Google Map

$.njDialerPlugin.doSearchMap = function()
{
    var pcode = $.njDialerPlugin.getFieldValue("Appointment_Postcode");
    var suburb = $.njDialerPlugin.getFieldValue("Appointment_Suburb");
    if (pcode.length > 0)
        $('#postcodeframe').attr('src',"https://www.google.com/maps/embed/v1/search?key=AIzaSyAoSLuzVRogAohSdgrUSBgM4aWe9j3puPY&q=Australia," + pcode);
    else
        $('#postcodeframe').attr('src',"https://www.google.com/maps/embed/v1/search?key=AIzaSyAoSLuzVRogAohSdgrUSBgM4aWe9j3puPY&q=Australia," + suburb);
};



Load google maps api


/**
 * Load the google maps api
 */
$.njDialerPlugin.loadGoogleApiScript = function()
{
    var googleApiKey = "AIzaSyCjs7zt2OknZhQ_dQ8LVwd2lot9TghdkZs";
    
    // make certain our custom location field is cleared before we start.
    $.njDialerPlugin.location = null;
    
    var googleApiScript = "https://maps.googleapis.com/maps/api/js?key=" + googleApiKey + "&libraries=places"
    
    var loaded = true;
    
    try
    {
        google === undefined;
    }
      catch(e)
    {
        loaded = false; 
    }
    
    
    if (!loaded)
    {
            $.getScript( googleApiScript )
        	.done(function( script, textStatus ) 
        	{
                $.njDialerPlugin.initMap();
            }
        );

    }
    else
        $.njDialerPlugin.initMap();

}


Populate Google address

/**
 * Take the returned Place and populate our address fields.
 */
$.njDialerPlugin.fillInAddress = function() 
{
    // Get the place details from the autocomplete object.
    debugger;
    
    var place = autocomplete.getPlace();
    
    if (place == null || place == undefined)
        return;

    var streetNo = "";
    var streetName="";
    

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) 
    {
        var addressType = place.address_components[i].types[0];
        switch (addressType)
        {
            case "street_number":
                streetNo = place.address_components[i].long_name;
                break;
            case "route":
               streetName = place.address_components[i].long_name;
                break;
            case "locality":
                $.njDialerPlugin.setFieldValueByName("Appointment_Suburb", place.address_components[i].long_name);
                break;
//            case "administrative_area_level_2":
//                $.njDialerPlugin.setFieldValueByName("", place.address_components[i].long_name);
//                break;
//            case "administrative_area_level_1":
//                $.njDialerPlugin.setFieldValueByName("", place.address_components[i].long_name);
 //               break;
            case "postal_code":
                $.njDialerPlugin.setFieldValueByName("Appointment_Postcode", place.address_components[i].long_name);
                break;

                
        }
    }
     $.njDialerPlugin.setFieldValueByName("Appointment_Street", streetNo + " " + streetName);
     
     
     geocodePlaceId(place.place_id);
}

$.njDialerPlugin.initMap = function()
{
    var searchField = document.getElementById('addressSearchField');
    
    var options = 
    {
        componentRestrictions: {country: 'au'},
        zoom: 15,
        center: {lat: -37.808751, lng: 144.992133}
    };

    autocomplete = new google.maps.places.Autocomplete(searchField, options);
    
    autocomplete.addListener('place_changed', $.njDialerPlugin.fillInAddress);
};


function geocodePlaceId(placeId) 
{
    var geocoder = new google.maps.Geocoder();


    geocoder.geocode({'placeId': placeId}, function(results, status) 
    {
        if (status === 'OK') 
        {
            $.njDialerPlugin.location = results[0].geometry.location;
        } 
        else 
        {
            alert('Geocoding was not successful for the following reason: ' + status);
        }
    });
}


Change Next Page transition

$.njDialerPlugin.getPage('${NjWizardPageName}').onPageNext = function(page,defaultNextPage) {

	var nextPage = defaultNextPage;
	
    var ambulanceReferral = $.njDialerPlugin.getFieldValue("Referred_By_Ambulance_Victoria");
    if (ambulanceReferral == true)
        nextPage = $.njDialerPlugin.getPage("Triage");

	return nextPage;
};


Bind a button


$.njDialerPlugin.getPage('${NjWizardPageName}').onPageEntry = function(page) {
    
    try
    {
        $("#btnSearchMap").unbind('click');           
        $('#btnSearchMap').click(function() {
           try
           {
            // add your action here.
            $.njDialerPlugin.doSearchMap();
           }
           catch(e)
           {
               alert(e);
           }
        });
    }
    catch (e)
    {
        alert(e);
    }
};


Check a Fields Length



$.njDialerPlugin.maxFieldLength = function (label, fieldName, maxLength) {
    
    var valid = true;
    
    var value = $.njDialerPlugin.getFieldValue(fieldName);
 
    if (value != undefined && value != null)
    {   
        if (value.length > maxLength)
        {
            valid = false;
            alert("The field " + label + " is too long. Max length is " + maxLength);
        }
    }
    return valid;
};


Medicare Validation


$.njDialerPlugin.medicareValidator = function (input, validateWithIrn) 
{
    if (!input) 
    {
        return false;
    }

    var medicareNumber;
    var pattern;
    var length;
    var matches;
    var base;
    var checkDigit;
    var total;
    var multipliers;
    var isValid = true;

    pattern = /^(\d{8})(\d)/;
    medicareNumber = input.toString().replace(/ /g, '');
    length = validateWithIrn ? 11 : 10;

    if (medicareNumber.length === length) {
        matches = pattern.exec(medicareNumber);
        if (matches) {
            base = matches[1];
            checkDigit = matches[2];
            total = 0;
            multipliers = [1, 3, 7, 9, 1, 3, 7, 9];

            for (var i = 0; i < multipliers.length; i++) {
                total += base[i] * multipliers[i];
            }
            isValid = (total % 10) === Number(checkDigit);
        } else {
            isValid = false;
        }
    } else {
        isValid = false;
    }

    return isValid;
};


Validate Medicare Expiry

$.njDialerPlugin.validMedicareExpiry = function (label, fieldName, patientNo) 
{
    var valid = true;
    var expiry = $.njDialerPlugin.getFieldValue(fieldName).trim();
    var cardType = $.njDialerPlugin.getFieldValue("CardType_Patient_" + patientNo);
    if (cardType === 'Medicare')
    {
        var expiryPattern = /^(0[1-9]|1[0-2])\/\d{4}$/;
        
        if (!expiryPattern.test(expiry))
        {
            alert("The " + label + " format is invalid. (mm/yyyy) expected");
            valid = false;
        }
    }    
    return valid;
}


Calculate Someones age


$.njDialerPlugin.calculateAge = function(patientNo)
{
    var dateOfBirth = $.njDialerPlugin.getFieldValue("Date_of_Birth_Patient_" + patientNo);

    try
    {
        dateOfBirth = dateOfBirth.trim();
        if (dateOfBirth.length > 0)
        {
            var birthday = $.njDialerPlugin.parseDateDDMMYYY(dateOfBirth);
            if (birthday !== null)
            {
                var ageDifMs = Date.now() - birthday.getTime();
                
                var ageDate = new Date(ageDifMs); // miliseconds from epoch
                var age = Math.abs(ageDate.getUTCFullYear() - 1970);
                $.njDialerPlugin.setFieldValueByName("Age_Patient_" + patientNo, age);
            }
            else
            {
                    alert("Invalid Date Of Birth: " + dateOfBirth + ". Expected dd/mm/yyyy");
            }
        }
        
    }
    catch(e)
    {
        alert("Invalid Date Of Birth: " + dateOfBirth);
    }
};


Parse a date


/**
 * Takes a date string and returns a date object
 * The string must be of the format yyyy/mm/dd
 * If the string is not a valid format then null is returned
 */
$.njDialerPlugin.parseDate = function(stringDate)
{
    var date = null;
    try
    {
        if (stringDate != null)
        {
            stringDate = stringDate.trim();
            if (stringDate.length == 10)
            {
                // validate year as 4 digits, month as 01-12, and day as 01-31 
                var dateParts = stringDate.match (/^(\d{4})\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/);
                if (dateParts) 
                {
                    // make a date
                    date = new Date (+dateParts[1], +dateParts[2] - 1, +dateParts[3]);
                    // check if month stayed the same (ie that day number is valid)
                    if (date.getMonth() !== +dateParts[2] - 1)
                        date = null;
                }
            }
        }
    }
    catch(e)
    {
    }
    return date;
}


Parse a date


/**
 * Takes a date string and returns a date object
 * The string must be of the format yyyy/mm/dd
 * If the string is not a valid format then null is returned
 */
$.njDialerPlugin.parseDateDDMMYYY = function(stringDate)
{
    var date = null;
    try
    {
        if (stringDate != null)
        {
            stringDate = stringDate.trim();
            if (stringDate.length == 10)
            {
                // validate year as 4 digits, month as 01-12, and day as 01-31 
                var dateParts = stringDate.match (/^(0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/(\d{4})$/);
                if (dateParts) 
                {
                    // make a date
                    date = new Date (+dateParts[3], +dateParts[2] - 1, +dateParts[1]);
                    // check if month stayed the same (ie that day number is valid)
                    if (date.getMonth() !== +dateParts[2] - 1)
                        date = null;
                }
            }
        }
    }
    catch(e)
    {
    }
    return date;
}

Parse Date

$.njDialerPlugin.parseDateDDMMYYYHHMM = function (dateString) 
{
    var date = null;
    
    if (dateString.length == 19)
    {
    	var year, month, day, hour, minute, second;
        var dateReg = /(\d{1,2})\/(\d{1,2})\/(\d{4})\s*(\d{1,2}):(\d{2})\s*(am|pm)/;
    
        var result = dateReg.exec(dateString);
        if (result) 
        {
            year = +result[3];
            month = +result[2] - 1;
            day = +result[1];
            hour = +result[4];
            minute = +result[5];
            if (result[6] === 'pm' && hour !== 12) 
            {
                hour += 12;
            }       
            date = new Date(year, month, day, hour, minute);
        }
    }
    return date;
}


Parse datetime

/**
 * Takes a date/time string and returns a date object
 * The string must be of the format yyyy/mm/dd hh:mm
 * If the string is not a valid format then null is returned
 */
$.njDialerPlugin.parseDateTime = function(stringDate)
{
    var date = null;

    try
    {
        if (stringDate != null)
        {
            stringDate = stringDate.trim();
            if (stringDate.length == 16)
            {
                date = new Date(Date.parse(stringDate, "yyyy/MM/dd HH:mm"));
                if (date !== null && date == "Invalid Date")
                    date = null;
            }
        }
    }
    catch(e)
    {
    }
    return date;
}


Parse DAteHHMM


$.njDialerPlugin.parseDateHHMM = function (dateString) 
{
    var date = null;
    
    if (dateString.length == 8 || dateString.length == 7)
    {
    	var year, month, day, hour, minute, second;
        var dateReg = /(\d{1,2}):(\d{2})\s*(am|pm)/;
    
        var result = dateReg.exec(dateString);
        if (result) 
        {
            hour = +result[1];
            minute = +result[2];
            if (result[3] === 'pm' && hour !== 12) 
            {
                hour += 12;
            }       
            var today = new Date();
            date = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hour, minute);
        }
    }
    return date;
}


Validate Email


/*
 * Returns true if the email address is valid
 */
$.njDialerPlugin.validateEmail = function(email) 
{
    var valid = true;
    email = email.trim();
    if (email.length > 0)
    {
        
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        var valid = re.test(email);
        
        if (!valid)
        {
            alert("The entered email address is not valid: " + email);
        }
    }
    return valid;
}



Format Dates



$.njDialerPlugin.formatDDMMYYYHHMM = function(date)  
{
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getFullYear() + " " + strTime;
}


$.njDialerPlugin.formatDate = function (date) 
{
    var hours = date.getHours();
    hours = hours < 10 ? '0'+hours : hours;
    
    var minutes = date.getMinutes();
    minutes = minutes < 10 ? '0'+minutes : minutes;
    
    var strTime = hours + ':' + minutes;
    
    var datestring = $.datepicker.formatDate("yy/mm/dd", date);
    
    return datestring + " " + strTime;
}


Validate Dates

$.njDialerPlugin.validateDate = function (label, fieldName) 
{
    var valid = true;
    var date = $.njDialerPlugin.parseDate($.njDialerPlugin.getFieldValue(fieldName));
    if (date == null)
    {
        alert("The " + label + " date format is invalid. (yyyy/mm/dd)");
        valid = false;
    }
    return valid;
}


Validate Phone No.

     var contactNo = $.njDialerPlugin.getFieldValue("Contact_Preferred_Phone_Number");
        // remove internal whitespace
        contactNo = contactNo.replace(/\s+/g, '').trim();
        if (contactNo.length == 0)
        {
            valid = false;
            alert("You must enter the Preferred Contact Number.");
        }

        if (contactNo.length > 0 && contactNo.length != 10)
        {
            valid = false;
            alert("You must enter a full 10 digit phone no. e.g. 03 8320 8100");
        }