Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Spell Checker

  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Spell Checker

    Hello, I am working on a project. I am mostly new with javascript. I have taken a java script class before(was not very helpful).

    I am now trying to learn more on my own. I have this spell check program I have been creating.

    I am unsure how to loop through my array(wordlist array) and then compare my array to the variable(wordVar), which is entered by the user.

    The idea is that if the variable exists in the array then the program will display Correct spelling. If it is wrong I would like to show the correct spelling of the word. However, right now I am more interested in looping through my array and comparing the variable

    Here is my javascript and my form:

    Code:
    	<script type="text/javascript">
    	<!-- 
    		
    		//wordlist array declared and populated
    		var wordlist = new Array(6);
    			wordlist[0] = "dog";
    			wordlist[1] = "potato";
    			wordlist[2] = "napkin";
    			wordlist[3] = "knife";
    			wordlist[4] = "pumpkin";
    			wordlist[5] = "probably";
    			wordlist[6] = "wednesday";
    			document.write("Result of array is - "+wordlist[0]);
    
    			
    			function readText (form) {
    			wordVar =form.inputbox.value;
    			alert ("You Entered: " + wordVar + ". Did you mean " + wordlist[0] + "?" );
    			//alert(wordlist);
    			//next loop through wordlist array and compare words somehow. switch input to all lower
    }
    -->
    	</script>
    The Form

    Code:
    <form name="myForm">
    		<P>
    		<input type="text" name="inputbox" value="">
    		<input type="button" name="button1" Value="Read" onClick="readText(this.form)">
    		</p>
    		</form>

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Something like this.


    Code:
    function readText (form) {
    var found = false;
    wordVar = form.inputbox.value.toLowerCase();
    for (var i=0; i<wordlist.length; i++) {
    if (wordlist[i] == wordVar) {
    alert ("The word " + wordVar + " was found in the list");
    found = true;
    }
    }
    if (!found) {
    alert ("The word" + wordVar + " was not found in the list");
    }
    But you will not be able to display the correct spelling of a mis-spelled word. How will you know whether hog is a mis-spelling of dog or of hot? The number of possible mis-spellings of a given word is huge or almost infinite.

    A more modern and better way to populate your array is

    Code:
    var wordlist = ["dog", "potato", "napkin", "knife", "pumpkin", "probably", "wednesday"];
    Be aware that the <!-- and //--> comment (hiding) tags have not been necessary since IE3 (i.e. since September 1997). If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code.


    The cheese in the mousetrap is always free.
    Last edited by Philip M; 02-04-2013 at 04:22 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    of interest, the 1000 most common english words:
    Code:
    words="a ability able about above accept access according account achieve across act action activity actually add addition admit advantage advice affair affect after again against age ago agree agreement air all allow almost along already also although always among amount an analysis and animal announce another answer any anyone anything anyway appear application apply approach appropriate area argue argument arm army around arrive art as ask aspect association assume at attempt attention attitude authority available avoid award aware away baby back bad bank base basic basis be bear because become bed before begin behaviour behind believe benefit better between beyond big bill bit black blood board body book both box boy break bring brother build building business but buy by call campaign can capital car care carry case catch cause cell central centre century certain certainly chance change chapter character charge child choice choose church circumstance city claim class clear clearly client close club colour come commission committee common community company compare competition computer concern concerned condition conference consider contain continue contract control cos cost could council country couple course court cover create culture cup current customer cut dark data date daughter day dead deal death decide decision defence degree demand department depend describe design despite detail determine develop development die difference different difficult difficulty direction director discover discuss discussion disease division do doctor dog door doubt down draw drive drop due during duty each early easy eat economic economy education effect effort either election element else encourage end energy enjoy enough ensure enter environment especially establish even evening event ever every everyone everything evidence exactly example exist expect experience explain express eye face fact factor fail fall family far father feature feel feeling few field fight figure fill film final finally financial find fine finish fire firm floor fly follow following food foot for force foreign forget form former forward free friend from front full function fund further future game garden general generally get girl give glass go goal good government great ground group grow growth hair half hand happen happy hard have he head health hear heart heavy help her here herself high him himself his history hit hold home hope horse hospital hotel hour house how however human husband i idea identify if image important improve in include including income increase indeed indicate individual industrial industry information instance instead institution intend interest international into introduce investment involve issue it item its itself job join just keep kill kind king know knowledge labour land language large last late later law lead leader learn least leave left leg legal less let letter level library lie life light like likely line list listen little live local long look lose loss lot love low machine main maintain major majority make man manage management manager many market material matter may maybe me mean means measure meet meeting member memory mention method might mile military mind minister minute miss model modern moment money month more morning most mother move movement much music must my myself name national natural nature near nearly necessary need never new news next nice night no nor normal not note nothing now number obtain obviously occur of off offer office officer often oil okay old on once one only open operate operation opportunity or order organisation original other our out outside over own page paper parent part particular particularly party pass patient pattern pay people per percent performance perhaps period person personal pick picture piece place plan plant play player please point police policy political poor popular population position possible pound power practice prepare present president press pressure prevent previous price prime principle private probably problem procedure process produce product production professional profit programme project property proposal prove provide provision public publish pull pupil purpose put quality question quickly quite raise range rate rather reach read ready real really reason receive recent recently record red reduce refer reflect refuse region relate relation relationship remain remember remove replace report represent require research resource respect response responsibility rest result return reveal right rise risk road role room round royal rule run sale same save say scheme school science sea season seat secretary section sector security see seek seem sell send sense series serious serve service set several shall share she shop short should show side sign significant similar simple simply since single sit site situation size skill small smile so social society some someone something sometimes son soon sorry sort sound source space speak special specific spend staff stage stand standard start state statement station stay step still stone stop story street strong structure student study style subject success successful such suddenly suffer suggest summer support suppose sure surface system table take talk task tax teach teacher team technique technology tell tend term test than thank that the their them themselves then theory there therefore these they thing think this those though thought through throughout throw thus time title to today together too top total towards town trade train training treat treatment tree TRUE try turn type under understand union unit university unless until up upon us use used useful user usually value variety various version very view village visit voice wait walk wall want war watch water way we wear week well what whatever when where whether which while white who whole whom whose why wide wife will win window wish with within without woman wonder word work worker world would write wrong yeah year yes yesterday yet you young your yourself".split(" ");
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •