Confirmation dialog on leaving page (Javascript)
If you want to show confirmation dialog before user leaves or reloads the page, you can use Javascript onbeforeunload() event attribute. When unload event fires, it shows a prompt asking whether user wants to leave or reload the page. Most browsers will return the event string, but in some browsers such as Firefox it may not be displayed.
Image Gallery from a Directory using PHP
The PHP code will iterate though all the images in a folder and list them on the webpage as image gallery. The the sky is the limit, you can use it like batch processing code to make thumbnails or store them in the database.
Quick jQuery Form Validation
If you want a quick validation of your form without using any validation plugin, this jQuery snippet could do the trick. This snippet will prevent form submit and change field border color to red, unless user corrects the invalid or empty fields.
$(document).ready(function() {
$("#my_form").submit(function(e) {
//loop through each required field and simply change border color to red for invalid fields
$("#my_form input[required=true], #my_form select[required=true], #my_form textarea[required=true]").each(function(){
var proceed = true;
$(this).css('border-color',''); //reset border color
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
//alert("Field is empty");
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
if(proceed){ //everything looks good
return; //submit form
}
e.preventDefault();
});
});
});
Usage
Just set your form id to “my_form” and add required attribute to each input field you want to validate, as shown in example below.
Get Percentage Function PHP
Sometimes we need to calculate the percentage of certain value in our project. In that circumstances you can use following PHP snippet to do that task.
echo get_percentage(10, 100); //usage
function get_percentage($percentage, $of)
{
//courtesy : http://stackoverflow.com/a/14880194
$percent = $percentage / $of;
return number_format( $percent * 100, 2 ) . '%';;
}