I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Fiddle Demo