Nasrul Hazim Bin Mohamad

jQuery Mobile: Set Selected Item for jQM Select


There’s a minor different how to set selected item in drop down list in jQuery Mobile. We can’t set by using standard jQuery $().val(value);. Here the workaround

$("#selector option[value='your-value']").attr('selected', 'selected');  

Reference: Is there a way to set the selected value in JQM select?

Bootstrap DatePicker I18N – Malay


Setting up for Malay Language. Copy & paste the following, save it as and include in your HTML pages as needed.

$.fn.datepicker.dates['my'] = {
    days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"],
    daysShort: ["Ahd", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab"],
    daysMin: ["Ah", "Is", "Sl", "Rb", "Kh", "Jm", "Sa"],
    months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"],
    monthsShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
    today: "Hari Ini",
    clear: "Bersihkan"

Sample usage:

    language: 'my',
    format: "MM yyyy",
    startDate: "Januari 2000",
    minViewMode: 1
Bootstrap DatePicker - Malay

Bootstrap DatePicker – Malay

Reference: Bootstrap DatePicker I18N

jQuery: Create Loading Indicator with ajaxSend & ajaxComplete


Referring to my earlier post jQuery: Show Loading…, a better way to show & hide loading icon – by binding to ajaxSend and ajaxComplete event.

The Html Markup

 <div id="loading" class="overlay-loading">
    <i class="loading-icon fa fa-5x fa-circle-o-notch fa-spin"></i>


.overlay-loading {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.8;
    filter: alpha(opacity=80);
    z-index: 2000;
.loading-icon {
    position: absolute;
    top: 50%;
    left: 50%;

The JavaScript

$(document).bind("ajaxSend", function(){
 }).bind("ajaxComplete", function(){


  1. Ajax Events
  2. JsFiddle
  3. FontAwesome

jQuery: Get Non-empty Text Area Inputs


Simple solutions to get non-empty text area inputs. Let say you have a list or text area like the following:

<textarea name="remark[about_us] id="remark-about_us"></textarea>
<textarea name="remark[about_us2] id="remark-about_us2"></textarea>
<textarea name="remark[about_us3] id="remark-about_us3"></textarea>
<textarea name="remark[about_us4] id="remark-about_us4"></textarea>
<textarea name="remark[about_us5] id="remark-about_us5"></textarea>
var remarks = $('[name^=remark]');
$.each( remarks, function( index, value ){
	var remark = $.trim($('#';
	if(remark.length != 0) { 
		console.log( + ' - ' + value.value);
	} else {
		console.log( + ' - empty');

Here a sample I have on my current working project.

Get Non-Empty Text Area

jQuery Plugin: MySQL DateTime to Input Date Format


Simple solutions to convert MySQL DateTime to Input Date Format. You may change the format as your requirement.

  getInputDateFromMySQLDate: function(value) {
  	var t = value.split(/[- :]/);

	var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
	var day = ("0" + d.getDate()).slice(-2);
	var month = ("0" + (d.getMonth() + 1)).slice(-2);

	return d.getFullYear()+"-"+(month)+"-"+(day);
  getDateFromMySQLDate: function(value){
  	var t = value.split(/[- :]/);

	return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);



Web Services: Slim Framework + Eloquent(Laravel)


Setting up the Restful API is easy with Slim Framework & Eloquent(Laravel). Here are the steps:

  1. Install required components via composer – Slim Framework + Eloquent(Laravel)
  2. Create a database called web_services and create users table.
  3. Setting up Eloquent
  4. Setting up Routes
  5. Final Touch
Web Service Restful API

Web Service Restful API

Install the necessary components using composer – create a composer.json and save it in a working directory and run composer install.

    "name": "Web Services",    
    "require": {
        "php": ">=5.3.0",
        "slim/slim": "2.*",
        "slim/views": "0.1.*",
        "illuminate/database": "5.0.*",
        "illuminate/events": "5.0.*"
    "autoload": {
        "classmap": [

We’re creating a simple web services for Users – Simple CRUD. Create a database called web_services and run the following SQL statement to create user table.

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)

Next, setting up the Eloquent. Create a database.php in config folder(Please create this folder in the working directory) folder.

$database = [
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'web_services',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',

use IlluminateDatabaseCapsuleManager as Capsule;

$capsule = new Capsule;


// Set the event dispatcher used by Eloquent models... (optional)
use IlluminateEventsDispatcher;
use IlluminateContainerContainer;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())

Once we’re done with Eloquent, next we going to set up the routes for Users CRUD operations. Save your time, copy & paste the following codes and save it in config/routes.php.


$app->get('/api/users', function () {
    echo User::all()->toJson();

$app->get('/api/users/:id',  function($id) {
	try {
		echo User::find($id)->toJson();
	} catch (Exception $e) {
		echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';

$app->get('/api/users/search/:query', function($query) {
	echo User::where('name', '=', $query)->get()->toJson();

$app->post('/api/users/add', function() use ($app) {
    try {
        $user = new User;

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully add new user"}';
        } else {
             echo '{"message":"Failed to add new user"}';
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';


$app->put('/api/users/update/:id', function($id) use ($app) {
    try {
        $user = User::find($id);

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully update user info"}';
        } else {
             echo '{"message":"Failed update user info"}';
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';

$app->delete('/api/users/:id', function($id) {
	$user = User::find($id);
    if($user->delete()) {
        echo '{"message":"Successfully delete user"}';
    } else {
         echo '{"message":"Failed to delete user"}';

OK, here the final touch! 2 things to do, one the index.php and the other one is .htaccess. Here the index.php. Please take note, we require the header("Access-Control-Allow-Origin: *");, to ensured that we can access this Restful API from other domains. There might be security issues. Comments are welcomed.

try {
	header("Access-Control-Allow-Origin: *");
	require 'vendor/autoload.php';
	require 'config/database.php';
	require 'config/initialize.php';
} catch (Exception $e) {
	echo '{"error":{"text":'. 'Unable to start up the web service. ' . $e->getMessage() .'}}';

The .htaccess.

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Source code available at: Web Service(Restful API)

I Have 3 demo available:

  1. Web Service App
  2. Web Service Demo
  3. Web Service Mobile Demo


Phalcon: Multiple-Module Skeleton



I’ve been learning Phalcon Framework recently and end up built a Multiple-Module Skeleton app – basically to ease development process to manage modules. Looking forward to add in more features. I have it on GitHub.

I have the directory structure as follow:

Phalcon - Multi Modules Structure - NHM - 1.0 - 20150313

Phalcon – Multi Modules Structure – NHM – 1.0 – 20150313

Hope to get some feedbacks.

Jazakumullahu khairan.

jQuery: Word Count & Words Limit

    function wordCount(selector,label,limit) {
        var words = $(selector).val().match(/S+/g);
        var length = words.length;

        if (length &gt; limit) {
            var trimmed = $(selector).val().split(/s+/, limit).join(&quot; &quot;);
            $(selector).val(trimmed + &quot; &quot;);
        else {
            $(label).text(length + '/' + limit + ' words');

// Usage
wordCount('#text-input', '#word-count-indicator', 1000);

jQuery: Get Sentence at Number…

function getSentence(selector,index) {
        var sentences = $(selector).val().split('.');
        if(sentences.length &gt; 2) { // valid for paraphraph with more than 2 sentences.
            if(index == 'first') {
                return sentences[0];
            } else if( index == 'last') {
                if(sentences[sentences.length - 1] == &quot;&quot;) {
                    return sentences[sentences.length - 2];
                } else {
                    sentences[sentences.length - 1]
            } else {
                return sentences[index - 1]; 
        } else {
            return 'Sentence Not Found.';


&lt;span id=&quot;paragraph&quot;&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur at erat finibus, aliquam ligula eget, ullamcorper felis. Nunc quis nibh sollicitudin lectus malesuada congue fermentum ut libero. Nam varius nisi non tincidunt pulvinar. In ut elit at odio blandit fermentum nec eu justo. Sed a maximus quam, ut faucibus lacus. In et luctus nisi. Nam commodo iaculis tellus sed pharetra. Pellentesque semper tellus quis maximus tristique. Pellentesque rutrum libero non suscipit convallis. Pellentesque eleifend, metus maximus rutrum ultricies, quam sem ultricies dui, quis cursus diam nibh ac dolor. Pellentesque fringilla dictum nunc et rhoncus. Curabitur elit leo, auctor a laoreet eget, aliquet ac nisi. Fusce a odio vestibulum, consequat diam vel, ultricies eros. Etiam suscipit sem imperdiet mauris ornare, a consequat purus suscipit.Nam feugiat lacus ut ante dictum, ut interdum eros ultricies. Sed ornare dui ac enim pulvinar, pulvinar gravida dolor pulvinar. Nunc tincidunt lectus at augue porttitor, sit amet ultricies ligula imperdiet. Phasellus id nulla cursus felis tristique tempor. Donec vitae dolor at magna vestibulum ullamcorper id et nibh. Proin euismod tempus velit. Quisque ultrices hendrerit mauris. Vestibulum gravida molestie enim a aliquam.Nam a posuere diam, sed tincidunt nisl. Duis magna metus, vulputate finibus massa quis, porta aliquet sem. Aliquam erat volutpat. Nam vestibulum sapien at metus pretium facilisis. Mauris nec tincidunt libero. Duis quis mauris a nisi pellentesque gravida non non felis. Vestibulum imperdiet quam ante, eget dapibus nunc convallis non. Mauris sed quam efficitur ligula finibus volutpat sit amet non ipsum.&lt;/span&gt;
getSentence('#paragraph',7); // will get sentence no. 7

HTML5: Get Current Position

(function($) {
    var methods = {
        current : function()
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position, error);

            function position(pos) {
                var latitude = pos.coords.latitude;
                var longitude = pos.coords.longitude;

                alert('Latitude: ' + latitude + ', Longitude: ' + longitude);

            function error(err) {
                alert('ERROR(' + err.code + '): ' + err.message);
    $.fn.Location = function(method) {
        if (methods[method])
            return methods[method].apply(this,, 1));
        else if (typeof method === 'object' || !method)
            return methods.init.apply(this, arguments);
            $.error('Method ' + method + ' does not exist on jQuery.Ika');