I need to find the longest word in a sentence using JS

1k views Asked by At

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;
3

There are 3 answers

0
mido On BEST ANSWER

try this:

Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>                   
    var btn = document.getElementById("btn1");
    var in1 = document.getElementById("input1");
    var sp1 = document.getElementById("sp1");
    btn.onclick = function(){
        var vals = in1.value.split(' ');
        var val = vals[0];
        vals.forEach(function(v){ if(v.length>val.length) val = v;});
        sp1.textContent = val;
    }
</script>

Fiddle Demo

2
Geir Anders On

Add this to your button:

 onClick="alert(longestWord(document.getElementById('input1').value))"

It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.

0
Mike Robinson On

I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)

Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)

None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"