Thursday, March 21, 2019

Laravel Row reorder implementation

I was able to get this working in Laravel using Yajra Datatables as a Service.Here is the example below, hopefully you get the idea.

In my DataTable Builder:
return $this->builder()
    ->columns([
        'id' => [ 'visible' => false ], // record id
        'sortsequence' => [ ... ],  // db column containing order sequence
        ...,
    ])
    ->parameters([
        ...
        'rowReorder' => [
            'selector' => 'tr>td:not(:last-child)', // I allow all columns for dragdrop except the last
            'dataSrc' => 'sortsequence',
            'update' => false // this is key to prevent DT auto update
        ]
    ]); 

Blade:
/ includes DataTables JS/CSS plus the folliowing:
...
<meta name="csrf-token" content="{{ csrf_token() }}”>
...
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css”>
...
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){  
 $.ajaxSetup({
     headers: {
         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
 });
 var table = $('#dataTableBuilder').DataTable();
 table.on( 'row-reorder', function ( e, diff, edit ) {
     var myArray = [];
     for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
         var rowData = table.row( diff[i].node ).data();
  myArray.push({
      id: rowData.id,   // record id from datatable
      position: diff[i].newData  // new position
  });
     }
    var jsonString = JSON.stringify(myArray);
    $.ajax({
                url     : '{{ URL::to('myurl/reorder') }}',
                type    : 'POST',
                data    : jsonString,
                dataType: 'json',
                success : function ( json ) 
                {
          $('#dataTableBuilder').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                 // handle json response
                    });
                }
            });
 });

});
</script>
Route:
Route::post('myurl/reorder', 'MyController@reorder')->name('myname.reorder');
MyController :
/**
 * Reorder a listing of the resource.
 *
 * @return Response
 */
public function reorder(Request $request)
{
    $count = 0;

    if (count($request->json()->all())) {
        $ids = $request->json()->all();
        foreach($ids as $i => $key)
        {
            $id = $key['id'];
            $position = $key['position'];
            $mymodel = MyModel::find($id);
            $mymodel->sortsequence = $position;
            if($mymodel->save())
            {
                $count++;
            }
        }
        $response = 'send response records updated goes here';
        return response()->json( $response );
    } else {
        $response = 'send nothing to sort response goes here';
        return response()->json( $response );
    }
}

 Thanks for partially share by the exninja

Tuesday, September 25, 2018

PHPWord - Convert html to docx with header and footer layouts

Here is the simple and additional reasons to set the header with logo and address contents, and footer with positions on easy way.


       /* Convert HTML to word */
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->setDefaultFontSize($fontSize);
        $phpWord->setDefaultFontName($fontFamily);
        $phpWord->setDefaultParagraphStyle(
           [
                'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(0),
                'spacing' => 120,
                'lineHeight' => 1,
           ]
        );

        if ($addresstxt && ($headerlogoposition != $headercompanyposition)) {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE,
                'posHorizontal' => $headerlogoposition,
                'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
                'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN
            ];
        } else {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'alignment' => $headerlogoposition
            ];
        }
        $section = $phpWord->addSection();
        if($headerLogo || $addresstxt) {
            $header = $section->addHeader();

            if ($headerLogo) {
                $header->addImage($headerLogo, $imageStyle);
            }

            if ($addresstxt) {
                $textlines = explode("\n", $addresstxt);
                for ($i = 0; $i < sizeof($textlines); $i++) {
                    $header->addText($textlines[$i], ['size' => $headerfontsize], ['alignment' => $headercompanyposition]);
                }
            }
        }

        if ($footerTxt) {
            $footer = $section->addFooter();
            $footer->addText($footerTxt, ['size' => $footerfontsize], ['alignment' => $footerposition]);
        }

        $html = mb_convert_encoding($templateHtml, 'HTML-ENTITIES', 'UTF-8');
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($fileUrl);
       

Friday, September 21, 2018

Jquery - Allow only numeric data when entering in the input

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -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();
        }
    });
});

Thursday, August 02, 2018

Yii2 Relational Data

For example, the customer data is related with the order data because one customer may have placed one or multiple orders. With appropriate declaration of this relation, you'll be able to access a customer's order information using the expression $customer->orders which gives back the customer's order information in terms of an array of Order Active Record instances.


class Customer extends ActiveRecord
{
    // ...
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }
}

class Order extends ActiveRecord
{
    // ...
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }
}


After declaring relations, you can access relational data through relation names. This is just like accessing an object property defined by the relation method. For this reason, we call it relation property. For example,

// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);

// SELECT * FROM `order` WHERE `customer_id` = 123
// $orders is an array of Order objects
$orders = $customer->orders;

Relations via a Junction Table

class Order extends ActiveRecord
{
    public function getOrderItems()
    {
        return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
    }

    public function getItems()
    {
        return $this->hasMany(Item::className(), ['id' => 'item_id'])
            ->via('orderItems');
    }
}

The usage of relations declared with a junction table is the same as that of normal relations. For example,

// SELECT * FROM `order` WHERE `id` = 100
$order = Order::findOne(100);

// SELECT * FROM `order_item` WHERE `order_id` = 100
// SELECT * FROM `item` WHERE `item_id` IN (...)
// returns an array of Item objects
$items = $order->items;

Monday, July 09, 2018

Jquery - How to copy text to clipboard on button click

This is how it works:
  1. Creates a temporary hidden text field.
  2. Copies the content of the element to that text field.
  3. Selects the content of the text field.
  4. Executes the command copy like: document.execCommand("copy").
  5. Removes the temporary text field.
You can see a quick demo here:

https://codepen.io/vasashiner/pen/BPBmoj

Tuesday, June 12, 2018

Html Simple Tooltip

i have referred the simple tooltip, that is how can we used in our site. 

HTML :

<p data-tip="This is the text of the tooltip">This is a paragraph of text that has a tooltip.</p>

<div data-tip="This is the text of the tooltip2">
    <input type="text" name="test" value="44"/>
</div>

CSS:

[data-tip] {
    position:relative;
}

[data-tip]:before {
    content:'';
    /* hides the tooltip when not hovered */
    display:none;
    content:'';
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 5px solid #1a1a1a;  
    position:absolute;
    top:30px;
    left:35px;
    z-index:8;
    font-size:0;
    line-height:0;
    width:0;
    height:0;
}

[data-tip]:after {
    display:none;
    content:attr(data-tip);
    position:absolute;
    top:35px;
    left:0px;
    padding:5px 8px;
    background:#1a1a1a;
    color:#fff;
    z-index:9;
    font-size: 0.75em;
    height:18px;
    line-height:18px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    white-space:nowrap;
    word-wrap:normal;
}

[data-tip]:hover:before,
[data-tip]:hover:after {
    display:block;
}

Fiddle : http://jsfiddle.net/ch0b7x6a/

Sunday, June 10, 2018

Jquery - Format number to 2 decimal places

Here is the below example for the discount calculation and get the value with 2 decimals.

$("#discount").change(function() {
    var list = $("#list").val();
    var discount = $("#discount").val();
    var price = $("#price");
    var temp = discount * list;
    var temp1 = list - temp;
    var total = temp1.toFixed(2);

    price.val(total);
});

Wednesday, April 25, 2018

Google map auto complete input text based on country

Here is the below example to enter the text in the input to get the Google geo locations automatically.







Tuesday, February 27, 2018

Regular Expression to get a string between parentheses



This article is based on the regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"

I expect five hundred dollars ($500).
would return
$500
So You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");

//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

Thursday, February 15, 2018

Hierarchical data in MySQL: parents and children in one query

The idea is, how to implement a hierarchical query in MySQL (using the ancestry chains version) for a single row, such that it picks up the parents (if any) and any children (if any).

We need to combine two queries here:
  1. Original hierarchical query that returns all descendants of a given id (a descendancy chain)
  2. A query that would return all ancestors of a given id (an ancestry chain)
An id can have only one parent, that's why we can employ a linked list technique to build an ancestry chain, like shown in this article:

Here's the query to to this (no functions required):


SELECT  CONCAT(REPEAT('    ', level  - 1), _id) AS treeitem, parent, level
FROM    (
        SELECT  @r AS _id,
                (
                SELECT  @r := parent
                FROM    t_hierarchy
                WHERE   id = _id
                ) AS parent,
                @l := @l + 1 AS level
        FROM    (
                SELECT  @r := 1218,
                        @l := 0,
                        @cl := 0
                ) vars,
                t_hierarchy h
        WHERE   @r <> 0
        ORDER BY
                level DESC
        ) qi

Click to see more details. Thanks to Quassnoi to made my day easy!!  

Tuesday, October 24, 2017

laravel 5 - Properly handle TokenMismatchException

In laravel 5 , When the token is expired you could get the TokenMismatchException. So we can avoid the exception and redirect back to the page with some error notification messages is best for the users.

I searched around and could not find a 100% definitive solution to this. I was able to find this bit of code but it does not seem to make any difference: App\Exceptions\Handler.php

 
public function render($request, Exception $exception){ 
  if ($exception instanceof TokenMismatchException){ 
    return redirect(url()->previous())->with('alert-danger', 
"Oops! Seems you couldn't submit form for a long time. 
Please try again."); 
    }
    return parent::render($request, $exception); 
 }

Friday, August 25, 2017

jQuery push multiple values in input tag


Just set value to input store it in some temporary variable, append the value you want to store and set the value of input to this temporary variable eg.

<input id="user" type="text" name="user" class="form-control" />
<input id="user_id" type="hidden" name="user_id" value="" />

var oldValue = $("#user_id").val();
var arr = oldValue === "" ? [] : oldValue.split(',');
arr.push(yardval);
var newValue = arr.join(',');
$("#user_id").val(newValue);
 
 

Monday, August 14, 2017

Tinymce aws s3 upload plugin

Tinymce editor have lots of plugins and it is very useful. Today i have shared one of the useful plugin with you peoples.

Feature of this plugin:
- Upload the file in the tinymce and it will save the file in the aws s3 bucket and return the URL.


Please refer the URL for source code and  implementation : https://github.com/OGPoyraz/tinymce-aws-s3-upload-plugin

Special thanks to !!!

Thursday, August 10, 2017

Laravel - TNTSearch driver with Laravel Scout

Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. i have recommend using Laravel Scout for querying large databases, this will be where it will be at it’s most useful and powerful.

For More Refer : https://laravel-news.com/tntsearch-with-laravel-scout

Monday, July 03, 2017

Yii Form Validation With Ajax submit button

Step 1: @ your controller action
public function actionMyAction()
{       
    $model=new User;             
    $this->performAjaxValidation($model);  

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        $valid=$model->validate();            
        if($valid){

           //do anything here
             echo CJSON::encode(array(
                  'status'=>'success'
             ));
            Yii::app()->end();
            }
            else{
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
            }
   }
}
Step 2: @ your view Your form may look like this
<?php
$form=$this->beginWidget('CActiveForm', array(
        'id'=>'user-form',
        'enableAjaxValidation'=>true,
        'action'=>$this->createUrl('myController/MyAction'),
        'enableClientValidation'=>true,
     
));
   ?>
<div class="errorMessage" id="formResult"></div>
<div id="AjaxLoader" style="display: none">
<img src="<?php echo Yii::app()->request->baseUrl; ?>
/images/spinner.gif"></img></div>
<div class="row-user-single">
    <?php echo $form->labelEx($model,'attribute1'); ?>
    <?php echo $form->passwordField($model,'attribute1',
    array('size'=>60,'maxlength'=>500)); ?>
    <?php echo $form->error($model,'attribute1'); ?>
</div>

<div class="row-user-single">
    <?php echo $form->labelEx($model,'attribute2'); ?>
    <?php echo $form->passwordField($model,'attribute2',
array('size'=>60,'maxlength'=>500)); ?>
    <?php echo $form->error($model,'attribute2'); ?>
</div>
<div class="buttons">

 <?php echo CHtml::ajaxSubmitButton('Save',
CHtml::normalizeUrl(array('myController/MyAction','render'=>true)),
    array(
        'dataType'=>'json',
        'type'=>'post',
        'success'=>'function(data) {
            $("#AjaxLoader").hide();  
           if(data.status=="success"){
            $("#formResult").html("form submitted successfully.");
            $("#user-form")[0].reset();
           }
            else{
           $.each(data, function(key, val) {
           $("#user-form #"+key+"_em_").text(val);                                                    
           $("#user-form #"+key+"_em_").show();
           });
           }       
       }',                    
        'beforeSend'=>'function(){                        
              $("#AjaxLoader").show();
         }'
        ),array('id'=>'mybtn','class'=>'class1 class2')); ?>
<?php $this->endWidget();?>
there are only two things to be noted as follows:
1. @ your controller call validate of your model and return a json object if form is invalid
2. @ your view break this json object (OR traverse through it) and show the error messages under respective elements of the form.

For more refer please go to the link . Thanks to  riyazMuhammed 
 

Tuesday, June 13, 2017

Yii CListView ajax load more

Below solution is works fine.
 
InfiniteScroll Extension Path : 

https://github.com/erikuus/Yii-Extensions/tree/master/widgets
 
Implementation:

<?php
        $this->widget('zii.widgets.CListView', array(
                    'dataProvider'=>$dataProvider,
                    'itemView'=>'/jobs/viewJobList',
                    'summaryText'=>false,
                    'emptyText'=>"<p> No Jobs!!!</p>",
                    'id'=>'ajaxJobListView',
                   'template' => '{items} {pager}',
                   'ajaxUpdate'=>true,
                    'pager' => array(
                        'class' => 'ext.infiniteScroll.IasPager',
                        'rowSelector'=>'.row',
                        'listViewId' => 'ajaxJobListView',
                        'header' => '',
                        'loaderText'=>Yii::t('app','Loading'),
                        'options' => array('history' => false, 'triggerPageTreshold' => 1,

 'trigger'=>Yii::t('app','Load More')),
                    ),
                'afterAjaxUpdate'=>"function(id, data) {
                    $.ias({
                        'history': false,
                        'triggerPageTreshold': 1,
                        'trigger': Yii::t('app','Load More'),
                        'container': '#ajaxJobListView',
                        'item': '.row',
                        'pagination': '#ajaxJobListView .pager',
                        'next': '#ajaxJobListView .next:not(.disabled):not(.hidden) a',
                        'loader': Yii::t('app','Loading')
                    });
                }",
            ));?>

Wednesday, April 05, 2017

jQuery - How to convert a Title to a URL slug

Title : <input type="text" name="title" id="title"><br>
Slug  : <input type="text" name="slug-title" id="slug-title">


var slug = function(str) {
    var slug1 = '';
    var trimmed = $.trim(str);
    slug1 = trimmed.replace(/[^a-z0-9-]/gi, '-').
    replace(/-+/g, '-').
    replace(/^-|-$/g, '');
    return slug1.toLowerCase();
}
       
$("#title").keyup(function(){       
    var Text = $(this).val();
    $('#slug-title').val(slug(Text));             
});

$("#slug-title").keyup(function(){       
    var Text = $(this).val();
    $('#slug-title').val(slug(Text));             
});

Output:
Title: 123@345#456&421*322
Slug : 123-345-456-421-322

Demo : https://jsfiddle.net/vasashiner/Ltg06sax/

Monday, March 20, 2017

Yii2 gridview sum of column value

Here is some of the sample code to get the sum of the column values in the footer in the gridview. It was 100% working in the gridview in Yii2.

All you need to change is the values

 [
   'label' => 'cost',
   'attribute' => 'cost',
   'value' => function ($model, $key, $index, $widget) {
                            return $model->cost;
                    },
   'footer' => $cost,
 ],

The above code should be added in the gridview with footer enabled.

'showFooter' =>true,

Here cost the value which need to be totaled, so you need to change according to your needs. You also need to add the below code in the view page.

<?php
$cost = 0;
if (!empty($dataProvider->getModels())) {
 foreach ($dataProvider->getModels() as $key => $val) {
     $cost += $val->cost;
    }
}
?>

Use this code and calculate sum of values in the footer in the Yii2 Gridview.

Thanks for the code to make it easy. For more refere go to techken.in

Friday, March 10, 2017

Opencart .htacess file with page speed

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 month"
ExpiresByType image/jpeg "access 1 month"
ExpiresByType image/gif "access 1 month"
ExpiresByType image/png "access 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month" 
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType font/opentype "access 1 month"
ExpiresByType application/x-font-woff "access 1 month"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_mime.c>
 AddType application/x-javascript .js
 AddType text/css .css
</IfModule>

<IfModule mod_deflate.c>
 AddOutputFilterByType DEFLATE text/css application/x-javascript text/x-component text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/javascript
 <IfModule mod_setenvif.c>
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
 </IfModule>
 <IfModule mod_headers.c>
  Header append Vary User-Agent env=!dont-vary
 </IfModule>
</IfModule>

# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.
# 2. In your opencart directory rename htaccess.txt to .htaccess.
# For any support issues please visit: http://www.opencart.com

Options +FollowSymlinks

# Prevent Directoy listing
Options -Indexes

# Prevent Direct Access to files
<FilesMatch "(?i)((\.tpl|\.ini|\.log|(?<!robots)\.txt))">
 Order deny,allow
 Deny from all
</FilesMatch>

# SEO URL Settings
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]
# If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/

RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?route=common/home[?\s] [NC]
RewriteRule ^ /? [R=301,L]

RewriteCond %{QUERY_STRING} ^$ [OR]
RewriteCond %{REQUEST_URI} !index\.php/?$
RewriteRule ((^|/)index\.php)+/?(.*)$ /$3 [R=301,L,QSA,NC]


### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that.

# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off

# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off

# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M

# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M

# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200

# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200

# 7. disable open_basedir limitations
# php_admin_value open_basedir none

# Use PHPcur as default
AddHandler application/x-httpd-phpcur .php
<IfModule mod_suphp.c>
    suPHP_ConfigPath /opt/phpcur/lib
</IfModule>

Friday, March 03, 2017

jquery difference between map vs each function

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});


// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array.  For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5)
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]