Vedremo in questa breve guida come far mostrare in una vostra casella di ricerca un testo predefinito, ad esempio “Cerca sul sito…”, che apparirà sempre al caricamento della casella di ricerca. Tale testo predefinito verrà cancellato poi non appena l’utente cliccherà all’interno della casela di ricerca per digitare il proprio testo da volere ricercare. Vedremo come fare utilizzando sia Javascript che jQuery. Questo perchè potete utilizzare il metodo con jQuery se il vostro sito sta già utilizzando la libreria jQuery, in caso contrario, non è consigliabile poiché non è necessario caricare la libreria jQuery soltanto per questo semplice script, che potrete implementare in questo caso con il metodo in Javascript.
Metodo con Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<html> <head> </head> <body> <form method="get" action=""> <input type="text" name="search" id="search" value="" /> <input type="submit" name="submit" value="Cerca" /> </form> <script type="text/javascript"> <!-- var defaultText = "Cerca sul sito..."; var searchBox = document.getElementById("search"); //default text after load searchBox.value = defaultText; //on focus behaviour searchBox.onfocus = function() { if (this.value == defaultText) {//clear text field this.value = ''; } } //on blur behaviour searchBox.onblur = function() { if (this.value == "") {//restore default text this.value = defaultText; } } //--> </script> </body> </html> |
Metodo con jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> <script type="text/javascript"> <!-- $(document).ready(function() { var defaultText = "Cerca sul sito..."; var searchBox = $('#search2'); //set default text on load searchBox.val(defaultText); //on focus behaviour searchBox.focus(function(){ if ($(this).val() == defaultText) {//clear text field $(this).val(''); } }); //on blur behaviour searchBox.blur(function(){ if ($(this).val() == "") {//restore default text $(this).val(defaultText); } }); }); //--> </script> </head> <body> <form method="get" action=""> <input type="text" name="search2" id="search2" value="" /> <input type="submit" name="submit" value="Cerca" /> </form> </body> </html> |