i wrote an java script program that must do the following things : it must take the sentence from the text in the form and then find the number of occurrence of each word in the sentence alphabetically in table as following:
this : 5 times
the : 2 times .....and so on
but in reality my program do the following and doesn't show the result when search button clicked and if we take the function button-pressed() lonely it works as the following:
this :1
this :2
this:3
this:4
this:5
the:1
the:2....and so on
i want to appear the last values without the redundant values ,so any help please this is my code :
<script type = "text/javascript"><!--
function buttonPressed() {
var searchForm = document.getElementById( "searchForm" );
var inputVal = document.getElementById( "inputVal" );
var arr =inputVal.split(" ");
var counts = {};
arr.sort();
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
if(counts[num])
counts[num]=counts[num]+1 ;
else
counts[num]=1;
document.writeln("<table border = \"4\">" );
document.writeln( "<caption><h3>Search's Results: <h3/></caption>" );
document.writeln( "<tr><td>"+arr[i]+" :</td><td>" +counts[num] + "</td></tr></tbody></table>" );
}
} // end function buttonPressed
// --></script>
<form id = "searchForm" action = "">
<h1>The string to search is:<br /></h1>
<p>Enter Sentence You Wnt To Find The Occurrence Of Each Word In It :
<input id = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p></form>
You can also use this:
"mijn naam is niels, niels is mijn naam".split("niels").length - 1
// Will return 2
Which will split on the word, and you will have the number of matches
the main problem that you're trying to output during calculation, your document.writeln
statements are inside for loop
you need to move them out:
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
counts[num] = (counts[num] ? counts[num] : 0) + 1 ;
}
document.writeln("<table border=\"4\">");
document.writeln("<caption><h3>Search's Results: <h3/></caption>");
for (var i in counts) {
document.writeln("<tr><td>"+i+" :</td><td>"+counts[i]+"</td></tr>");
}
document.writeln("</tbody></table>");
NOTE: please read about htmlencode and document.writeln functions, you're doing wrong output, as you're writing to the end of document, for your particular task is ok, but usually you need to do output into particular place on page, for this you will need to assign innerHTML of some div
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.