type:
integration
system:
FoxyCart
name:
multiship_jquery
description:
(FC 0.6.0-) jQuery to automatically create a select box ("drop down") with previously entered ship-to addresses, with showing/hiding of the "New recipient" field.
tag:
multiship
date:
2008-05-23
version:
1.0
developer:
http://www.themancan.com

multiship javascript

Please note: The code on this page is submitted by members of the FoxyCart community, and may not verified by FoxyCart.com LLC in any way, shape, or form. Please double check the code before installing. If you need help with it please post in our forum, but if we cannot offer assistance (due to unfamiliarity with this particular system or language) we apologize in advance.

Description

Quickly and easily add multiple ship-to addresses to your FoxyCart site by including a single javascript file and adding a few classes to your “add to cart” forms. It looks something like this:

Multiship achieved!

This script

  1. checks for the existence of a shipto cookie;
  2. displays a select box (“drop down”) if there are any previously set ship-to recipients in the cookie;
  3. displays a “new recipient” input field if you choose “Add a new recipient…” in the select box;
  4. sets the select box to the previously selected shipto recipient;
  5. should be able to be used on pages with multiple “add to cart” forms.

Installation

  1. Copy the code below into a file named multiship.jquery.js and stick it somewhere on your server.
  2. Include the file in the <head> section of your template, after your foxycart_includes.js file.
  3. The script works by finding input and select elements inside divs with specific classes. You'll need to add, to your “add to cart” form…
    1. <select name=“x:shipto_name_select”></select> inside a div.shipto_select (probably want to give that container div a display:none; it gets shown with the javascript)
    2. <input type=“text” name=“shipto” value=“” /> inside a div.shipto_name
    3. It should look something like this:
      <div class="shipto_container">
      	<!-- the following select element is initially hidden, but is populated and shown with javascript on page load -->
      	<div class="shipto_select" style="display:none">
      		<label>Ship this item to:</label>
      		<select name="x:shipto_name_select">
      		</select>
      	</div>
       
      	<!-- the following text input is kind of a fallback. it is initially hidden by javascript on page load -->
      	<div class="shipto_name">
      		<label>Enter the name of the recipient (or leave it empty to ship it to yourself):</label>
      		<input type="text" name="shipto" value="" />
      	</div>
      </div>
  4. PLEASE make sure your code is valid. If your form is not valid you might get unexpected results. (Try this for Firefox or this.)
  5. That should be it, but TEST. Then test some more.
  6. Finally, test again, and have your friends test.
  7. Report any issues on the forum.

Requirements

  • The foxycart_includes.js file, or jQuery by itself.

Code

/*
	FoxyCart Multiship Javascript
	v1.0
	2008-05-23
 
	INSTRUCTIONS:
	http://wiki.foxycart.com/integration:misc:multiship_javascript
 
	IMPORTANT:
	If you're having problems with this script, MAKE SURE YOUR PAGE IS VALID.
	Seriously, if your page is invalid (particularly with regard to forms
	spanning beyond where they should, like starting in one <td> and going into
	another) this code might have issues.
*/
 
function shipto_initialize() {
	jQuery('div.shipto_select').show();
	jQuery('div.shipto_name').hide();
}
 
// shipto_check checks for the existence of the shipto cookie
// returns an array of values, or false if no cookie found
function shipto_array() {
	if (jQuery.cookie('shipto_names')) {
		// Define the global shipto array
		var shipto_array = jQuery.cookie('shipto_names').split('||');
		shipto_array = unique(shipto_array);
		shipto_array.sort();
		return shipto_array;
	} else {
		return false;
	}
}
 
function shipto_select() {
	// Clear the shipto select boxes first
	jQuery('div.shipto_select').find('select').html('');
	var shipto_options = '';
	var shipto = shipto_array();
	// alert('shipto: ' + shipto);
	if (shipto) {
		// alert('shipto is true');
		jQuery.each(shipto, function(i, val){
			// alert('starting the .each loop with: ' + i + ' = ' + val);
			if (val != 'null' && val != '' && val != 'Me') {
				shipto_options += '<option value="' + val + '">' + val + '<\/option>';
				// alert('and it worked: ' + val);
			}
		});
		shipto_options += '<option value="">- - - - - - - - -<\/option>';
	}
 
	// Add the defaults...
	// This doesn't seem to work perfectly, as the selected="selected" gets ignored for some reason
	shipto_options += '<option value="add_new">Add a new recipient...<\/option>';
	shipto_options += '<option value="">- - - - - - - - -<\/option>';
	shipto_options += '<option selected="selected" value="Me">Yourself<\/option>';
 
	// Set the select boxes with the proper values
	jQuery('div.shipto_select').find('select').html(shipto_options);
 
	// Now add the onchange event
	jQuery('div.shipto_select').find('select').change(function(){
		if (jQuery(this).val() == 'add_new') {
			jQuery(this).parents('form').find('div.shipto_name').show();
			// Set any shipto values. Done this way in case you're adding more than one product at a time.
			jQuery(this).parents('form').find('input[name="shipto"]').val('');
			// alert(jQuery('input[name="shipto"]').attr('name') + jQuery('input[name="shipto"]').val())
		} else {
			jQuery(this).parents('form').find('div.shipto_name').hide();
			// Set any shipto values. Done this way in case you're adding more than one product at a time.
			jQuery(this).parents('form').find('input[name="shipto"]').val(jQuery(this).val());
		}
	});
 
	// Finally, select the last used shipto
	if (jQuery.cookie('shipto_name_recent') != '') {
		jQuery('div.shipto_select').find('select').selectOptions(jQuery.cookie('shipto_name_recent'));
	} else {
		jQuery('div.shipto_select').find('select').selectOptions('Me');
	}
}
 
// Tie any additional product shipto's to the primary shipto
function shipto_multiples() {
	jQuery('input[name="shipto"]').change(function(){
		jQuery(this).parents('form').find('input[name="shipto"]').val(jQuery(this).val());
	});
}
 
// Set the events
jQuery(document).ready(function(){
	shipto_initialize();
	shipto_select();
	shipto_multiples();
});
 
 
// Set the cookie on cart add
// NOTE: This does not yet work with multiple forms on the same page.
// If you need that, chime in on the FoxyCart forums: http://forum.foxycart.com
function fc_PreProcess() {
	// Run any custom scripts you may have before dealing with,
	// or just insert your code here
	if (typeof fc_PreProcess_custom=="function") {
		fc_PreProcess_custom();
	}
	// Set the cookie
	var error = false;
	var shipto_cookie = jQuery.cookie('shipto_names');
	var shipto_new = jQuery('input[name="shipto"]').eq(0).val();
 
	jQuery.cookie('shipto_name_recent', '', {expires: -1, path: '/', domain: location.host.match('[^.]+.[^.]+$')});
	jQuery.cookie('shipto_name_recent', shipto_new, {expires: 300, path: '/', domain: location.host.match('[^.]+.[^.]+$')});
 
	if ((shipto_new != 'undefined') && (shipto_new != 'null') && (shipto_new != 'Me')) {
		jQuery.cookie('shipto_names', '', {expires: -1, path: '/', domain: location.host.match('[^.]+.[^.]+$')});
		jQuery.cookie('shipto_names', shipto_cookie + '||' + shipto_new, {expires: 300, path: '/', domain: location.host.match('[^.]+.[^.]+$')});
	}
	return true;
}
 
function fc_BuildFoxyCart() {
	shipto_initialize();
	shipto_select();
}
 
 
 
 
// ============================================================================
/**
 * Removes duplicates in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function unique(a) {
	tmp = new Array(0);
	for(i=0;i<a.length;i++){
		if(!contains(tmp, a[i])){
			tmp.length+=1;
			tmp[tmp.length-1]=a[i];
		}
	}
	return tmp;
}
/**
 * Returns true if 's' is contained in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function contains(a, e) {
	for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}
// ============================================================================
 
 
 
 
 
 
// ============================================================================
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
 
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
 
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// ============================================================================
 
 
 
// ============================================================================
// http://www.mathias-bank.de/2006/11/01/jquery-plugin-select-box-manipulation/
/*
 *
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Addepted to select an option by Mathias Bank (http://www.mathias-bank.de)
 */
 
/*
 * Selects an option by value
 *
 * @name     selectOptions
 * @author   Mathias Bank (http://www.mathias-bank.de)
 * @param    value specifies, which options should be selected
 * @example  jQuery("#myselect").selectOptions("val1");
 *
 */
jQuery.fn.selectOptions = function(value) {
	this.each(
		function()	{
			if(this.nodeName.toLowerCase() != "select") return;
 
			// get number of options
			var optionsLength = this.options.length;
 
 
			for(var i = 0; i<optionsLength; i++) {
				if (this.options[i].value == value) {
					this.options[i].selected = true;
				};
			}
		}
	)
	return this;
}

Site Tools