Practical Web Programming
Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Wednesday, November 06, 2013

How to Load Your Own jQuery Library When CDN is Down

It's always a good practice to load libraries like jQuery your web applications from CDN (Content Delivery Network). But sometimes (though rare) CDN goes down. The code below makes that you have jQuery loaded in events like this.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">if (typeof jQuery == 'undefined') {  document.write(unescape("%3Cscript src='Scripts/jquery.2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
}</script>

Wednesday, April 03, 2013

JQuery: How to prevent click event handler from being bound multiple times

A simple trick is to add a class to the element and bound only if the element don't have that class yet.

<script type="text/javascript">
    $('#button:not(.bound)')
        .addClass('bound')
        .bind('click', onClick);
 
 
    function onClick() {
        alert('You clicked me!');
    }
</script>

Thursday, March 08, 2012

jQuery: How to Use jQuery UI Autocomplete

Earlier today I was migrating the jQuery Autocomplete plugin to jQuery UI Autocomplete and I was having a hard time making it work - the selection list was not displaying. I went to the jQuery UI site but could not find an example and not even a document showing how to handle the data from a dynamic script when using the "source" option. After some testing at home and a lot of hair pulling, I finally got it to display the list.

See the code example below:


<!DOCTYPE html>
<html>
<head>
<title>jQuery: How to Use jQuery UI Autocomplete</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

<script>
$(document).ready(function(){
$("#ac").autocomplete({
source: function(request, response)
{
$.ajax({
url: "data.php",
type: "POST",
dataType: "json",
data:{
term: request.term
},
success: function(data){
//alert(data);
response( $.map( data, function(item)
{
return item;
}));
}
});
},
minLength: 2
});
});
</script>

</head>
<body>
<input type="text" id="ac" />
</body>
</html>


The dynamic script that returns the data to be displayed in the selection list. NOTE: The data returned is just for this demo. In a real application, this is where you put your code to query the database based on what the user type.

// The text that the user type in the textbox.
$search_phrase = $_REQUEST["term"];

$arr = array();
$arr[] = "111";
$arr[] = "222";
$arr[] = "333";

echo json_encode($arr);
?>


Recent Post