Jan 7 2009

Mootools: Add / Remove input from a form using clone

UPDATE: This script was updated, since there was a bug in IE. Thanks Phil for sending this in ! :)

When creating web forms, you will often need to allow multiple entries for a certain input field. Take a look at this example, you will see that it is possible to add/delete an input using Mootools clone function.

First, here is the basic HTML form:

<form name="myForm" action="mootools_row_clone_post.php" method="post">
<div id="input_container" style="padding:10px;">
Example: You can add/delete input fields since you don't kow how many your users will need.
<br />
After submitting you will see the resulting array from PHP
<div id="div_1"><input type="text" name="my_input[]" id="input_1" size="30" maxlength="30" /> <input class="bt_plus" type="button" value="+" /></div>
</div>
<div style="padding:10px;"><input type="submit" value="Submit" /></div>
</form>

Here are the 2 JavaScript functions that are required for this to work. I have added comments so that you can follow what is being done.

window.addEvent('domready', function() {
$$('input.bt_plus').each(function(el) {
el.addEvent('click', addRow);
});
});

function delRow(el) {
// destroying element
this.getParent().destroy();
}

function addRow() {
// ID of div element that was clicked, with 'div_' removed
clickID = parseInt(this.getParent().get('id').replace('div_',''));
// Generate ID of element to be created
newID = (clickID+1);
// Creating and adding new element
newClone = $('div_'+clickID).clone().injectAfter('div_'+clickID);
// Setting new div's element id
newClone.set('id', 'div_'+newID)
// Making sure the new field does not have a value carried from clone
newClone.getFirst('input').set('value', '');
// Setting new input text id
newClone.getFirst('input').set('id', 'input_'+newID);
// Adding click event on button, it will call addRow function
newClone.getFirst('input').getNext('input').addEvent('click', addRow);

// Changing value of the button that was clicked
this.set('value', '-');
// removing current event that is used to addrow
this.removeEvent('click', addRow);
// adding event to remove row
this.addEvent('click', delRow);
}

That is all that you needs in order to get the add/delete input script working. I find this rather useful when you don’t know the number of times your input will be required by your users.


Dec 22 2008

PHP: Form validation, Date (YYYY-MM-DD)

Here is function that will check the validity of a date entered in the following way: YYYY-MM-DD, ie 2008-12-22. This function make use of PHP’s checkdate function so leap years are taken into consideration.

function valid_date($fdate){
	$return = false;
	$arr_check = split("-",$fdate);
	if (count($arr_check) < 3) {
		$return = false;
	} else {
		$return = checkdate($arr_check[1],$arr_check[2],$arr_check[0]);
	}
        return $return;
}

Dec 18 2008

PHP: Form validation, Canadian Postal Code

Validating a Canadian postal code in PHP can be done with a simple Regular Expression. PHP’s preg_match function will return 0 (no match) or 1 (if there are 1 or more matches). To validate a Canadian postal code, you can use the following:

$value = 'A1B 2C3'; // Postal Code to validate
preg_match("/^[a-zA-Z][0-9][a-zA-Z] ?[0-9][a-zA-Z][0-9]$/", $value);

Note that the letters may be upper case or lower case.

More validation routines will follow.


Dec 12 2008

Mootools: Content scroller with mouse wheel support

You often have a limited amount of space to display your content. You can either keep it real short to fit the space available, or you can create your own content scroller. This article will show you how to create one using Mootools. The mouse wheel support was also added for more functionality. You can view an example here.

First, here is the HTML you will need to get this scroller started.

<div id="scroll_container">
<div id="scroll_container_content">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum quis risus in ipsum molestie dictum. Morbi felis leo, cursus vitae, fringilla eget, mattis gravida, sem. Curabitur ligula felis, dignissim non, volutpat ac, blandit non, tortor. Morbi laoreet justo accumsan ligula. Phasellus id justo sit amet justo facilisis lacinia. Nam dapibus enim viverra dui. Aliquam rhoncus sapien sit amet felis. Donec tempor ligula eget nisi. Integer mattis tortor a enim. Praesent tellus augue, suscipit vitae, aliquet vel, auctor eget, leo. Morbi ut sem sit amet dui dignissim blandit. Integer nibh. In enim justo, venenatis sit amet, mollis at, cursus id, justo. Aenean pharetra elit. Curabitur non velit. Aliquam elit neque, venenatis at, tincidunt non, sodales sed, sapien. Nunc metus neque, viverra ac, accumsan nec, vehicula nec, dolor. Quisque sit amet neque a dui dignissim tincidunt. Integer nisi ipsum, varius vel, laoreet vel, mattis quis, eros.

The rest of your content...</div>
</div>
<div id="scollbar_container">
<div id="scroll_up"><a onclick="mySlide.set(mySlide.step-10)" href="javascript://"><img src="_images/slider_up.gif" border="0" alt="" /></a></div>
<div id="scroll_down"><a onclick="mySlide.set(mySlide.step+10)" href="javascript://"><img src="_images/slider_down.gif" border="0" alt="" /></a></div>
</div>

The first two div tags are used for your content, the other ones are used to hold your scrollbar with the scrolling object and the up/down arrows.

/* container visible size, with overflow hidden to hide the rest of the content*/
#scroll_container {
margin:0px;
width: 500px;
height: 300px;
overflow:hidden;
margin-right:10px;
float:left;
}
/* The actual content*/
#scroll_container_content {
padding:0px;
margin:0px;
width: 500px;
}
/* The knob used to scroll down the scrollbar */
#scroll_knob {
position:relative;
height: 15px;
width: 15px;
background-image:url(_images/slider_block.gif);
background-repeat:no-repeat;
cursor: pointer;
}
/* The scroll up arrow*/
#scroll_up {
height:11px;
width:15px;
}
/* The scroll down arrow*/
#scroll_down {
height:11px;
width:15px;
}
/* The full scroll bar */
#scollbar_container {
padding:10px 10px 0 0;
height: 300px;
width: 15px;
float:left;
}
/* The scroll area (between the up and down) */
#scroll_area {
height: 280px;
width: 15px;
background-color:#cdcdcd;
}

Don’t forget to adjust the width and height per your own specifications! At this step you should be able to look at the result and see only what you want to see, the rest being hidden.

Now we just need to add our javascript that will make it all work…

window.addEvent('domready', function() {
if ($('scroll_container_content') != null) {
if ( ($('scroll_container_content').getSize().y) > ($('scroll_container').getSize().y) ) {

// Initiate scroller for our content
myScrollFx = new Fx.Scroll('scroll_container', {
wait: false
});

// Initiate scroll bar
mySlide = new Slider($('scroll_area'), $('scroll_knob'), {
steps: $('scroll_container_content').getSize().y-($('scroll_container').getSize().y),
mode: 'vertical',
onChange: function(step){
$('scroll_container').scrollTo(0,step);
}
}).set(0);
scroller();
}
else {
$('scroll_area').setStyle('visibility','hidden');
}
}
});

function scroller() {
document.addEvent('mousewheel', function(e) {
e = new Event(e).stop();
var step = mySlide.step - e.wheel * 10;
mySlide.set(step);
});
}

When the DOM is ready, we check that the div we want to scroll actually exists. We first initiate our Scroller, then our Slider. We also call our Scroller function which will add functionality for the mouse wheel support.

You should now have a working scroller with mouse wheel support.


Dec 5 2008

Mootools: Sortables with auto-save

Mootools Sortables plugin is quite useful and neat. You can use it to order items with drag & drop and then save the new order in your database. The order can also easily be updated upon every change in your list order. Here is an example.

To accomplish that, you would first create your HTML list of items to sort (under our list the div with id “confirm” is used to display the results of our actions):


<ul id="list">
<li id="item_1">Item #1</li>
<li id="item_2">Item #2</li>
<li id="item_3">Item #3</li>
<li id="item_4">Item #4</li>
<li id="item_5">Item #5</li>
</ul>
<div id="confirm"></div>

Then you initiate your Mootools Sortables:

window.addEvent('domready', function() {
var thisSortables = new Sortables($('list'), {
constrain: true,
clone: true,
revert: true,
});
});

In the previous code, we just told the Sortables plugin to make the list with id “list” sortable, we also added some options that you can look at in the Mootools documentation. Now we can add Events to that Sortable list. We will add the onStart and onComplete Events to our Sortable list, these will be triggered every time an element has started to be dragged and upon the release of the dragging. The onStart event will remove the text from the confirm div. Then the onComplete event serializes our data and sends it to our php script using a Mootools Request. Each items in our list is given an ID which consists of a name and an id from our MySQL database. Therefore, I can extract the ID of each element and send it to my PHP script along with it’s new order. Here is the final Sortables script:

window.addEvent('domready', function() {
var thisSortables = new Sortables($('list'), {
constrain: true,
clone: true,
revert: true,
onStart: function() {
$('confirm').set('html', '');
},
onComplete: function() {
this.serialize(function(el, index) {
var updateOrderRequest = new Request.HTML({
url: 'sortables_update.php',
method: 'post',
data: {'itemID': el.id.replace("item_",""), 'new_pos':(index+1)}
}).send();
});
$('confirm').set('html', 'New order was saved successfully.');
}
});
});

Your PHP script will be able to use $_POST['itemID'] and $_POST['new_pos'] in order to update your database.

There you go, you can now save your Sortables information everytime it changes !