Thursday, October 6, 2011

Text suggestion while writing in textbox using Javascript

Requirements: None, just javascript but good knowledge of that.

Using:
file.html
  1. <html>
  2. <body>
  3.       <input type="text" id="notrequired" onKeyUp="hint(this)" />
  4.        <div id="hintwords"></div>
  5. </body>
  6. <script type="text/javascript">
  7. function hint(me)
  8. {
  9. var arr = new Array('test','it','will','work');
  10. var iter = 0;
  11. var mat = new Array();
  12. var len = me.value.length;
  13. if(len>0)
  14. {
  15. for(iter=0 ; iter < arr.length; iter++)
  16. {
  17. var val = me.value;
  18. //alert(val);
  19. var patt = new RegExp( val ,'gi');
  20. var result = patt.exec(arr[iter]);
  21. if(result == val)
  22. {
  23. //alert(arr[iter]);
  24. mat.push(arr[iter]);
  25. }
  26. }
  27. //alert(mat[0]);
  28. var str = '';
  29. for(iter = 0; iter < mat.length ; iter++)
  30. {
  31. if(str == '')
  32. {
  33. str = str + mat[iter]
  34. }
  35. else
  36. {
  37. str = str + ',' + mat[iter]
  38. }
  39. }
  40. document.getElementById('hintwords').innerHTML = str;
  41. }
  42. else
  43. {
  44. document.getElementById('hintwords').innerHTML = '';
  45. }
  46. }
  47. </script>
  48. </html>
Explanation:
           I will be explaining just the lines that are important and needed to be explain.
     9.   array is created of the words that are needed to be hinted.
    13.  checking if the length of value of text in textbox is greater than 0.
    15.  looping on the length of the array of words.
    20.  making a regular expression using of the value of textbox. Here the regex generated will be the same as the value of textbox.
     21. checking for the match using exec() of regex.
     26. if there is match then the word that is from the array of word is pushed into new array mat.
     35. if the str has no value then this line is exceuted and string is concatenated to str.
     39. else this line concatenated to str.
     42. is just writing the str in the div hintwords.
     46. if the textbox has no value or empty then no hint is shown

                                                                                        No comments:

                                                                                        Post a Comment

                                                                                        Thank you for your comment!