How to filter through an array for a user input in js?












0















I'm trying to build a random quote machine where a user can put in a topic word, an algorithm searches for that word within a list of quotes, makes a new list of quotes that contain that word, and then randomly returns a quote out of the filtered list. If there is no word in the list, it would return any random quote. I can't figure out how to make a filtered list in JavaScript. So far I've got:



<body>
<p id="quoteDisplay"></p>
</body>
<form>
<input type="text" id="topic" />
<button onclick="wiseQuote()">Quote</button>
</form>

<script type="text/javascript">
var quotes = [
"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
"You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
"Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
"In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
"Everything in moderation, including moderation - Oscar Wilde",
"Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
"Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
"The truth is rarely pure and never simple. - Oscar Wilde",
"A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
"Perhaps one did not want to be loved so much as to be understood. - George Orwell",
"Facts do not cease to exist because they are ignored. - Aldous Huxley",
"Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
"A thing is not necessarily true because a man dies for it. - Oscar Wilde",
"The unexamined life is not worth living. - Socrates"
]

if (topic != null){
filteredQuotes = quotes.filter(function(){
return ;
});
}

if (filteredQuotes.length) {
randomIndex = Math.floor(Math.random() * filteredQuotes.length);
filteredQuote = filteredQuotes[randomIndex];
} else {
randomIndex = Math.floor(Math.random() * quotes.length);
filteredQuote = quotes[randomIndex];
}

document.getElementById('quoteDisplay').innerHTML = filteredQuote;
}

</script>


This is the first project I'm building so I hope this code is not too much of a mess!! Thank you all so much in advance :)










share|improve this question





























    0















    I'm trying to build a random quote machine where a user can put in a topic word, an algorithm searches for that word within a list of quotes, makes a new list of quotes that contain that word, and then randomly returns a quote out of the filtered list. If there is no word in the list, it would return any random quote. I can't figure out how to make a filtered list in JavaScript. So far I've got:



    <body>
    <p id="quoteDisplay"></p>
    </body>
    <form>
    <input type="text" id="topic" />
    <button onclick="wiseQuote()">Quote</button>
    </form>

    <script type="text/javascript">
    var quotes = [
    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
    "Everything in moderation, including moderation - Oscar Wilde",
    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
    "The truth is rarely pure and never simple. - Oscar Wilde",
    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
    "The unexamined life is not worth living. - Socrates"
    ]

    if (topic != null){
    filteredQuotes = quotes.filter(function(){
    return ;
    });
    }

    if (filteredQuotes.length) {
    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
    filteredQuote = filteredQuotes[randomIndex];
    } else {
    randomIndex = Math.floor(Math.random() * quotes.length);
    filteredQuote = quotes[randomIndex];
    }

    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
    }

    </script>


    This is the first project I'm building so I hope this code is not too much of a mess!! Thank you all so much in advance :)










    share|improve this question



























      0












      0








      0








      I'm trying to build a random quote machine where a user can put in a topic word, an algorithm searches for that word within a list of quotes, makes a new list of quotes that contain that word, and then randomly returns a quote out of the filtered list. If there is no word in the list, it would return any random quote. I can't figure out how to make a filtered list in JavaScript. So far I've got:



      <body>
      <p id="quoteDisplay"></p>
      </body>
      <form>
      <input type="text" id="topic" />
      <button onclick="wiseQuote()">Quote</button>
      </form>

      <script type="text/javascript">
      var quotes = [
      "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
      "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
      "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
      "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
      "Everything in moderation, including moderation - Oscar Wilde",
      "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
      "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
      "The truth is rarely pure and never simple. - Oscar Wilde",
      "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
      "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
      "Facts do not cease to exist because they are ignored. - Aldous Huxley",
      "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
      "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
      "The unexamined life is not worth living. - Socrates"
      ]

      if (topic != null){
      filteredQuotes = quotes.filter(function(){
      return ;
      });
      }

      if (filteredQuotes.length) {
      randomIndex = Math.floor(Math.random() * filteredQuotes.length);
      filteredQuote = filteredQuotes[randomIndex];
      } else {
      randomIndex = Math.floor(Math.random() * quotes.length);
      filteredQuote = quotes[randomIndex];
      }

      document.getElementById('quoteDisplay').innerHTML = filteredQuote;
      }

      </script>


      This is the first project I'm building so I hope this code is not too much of a mess!! Thank you all so much in advance :)










      share|improve this question
















      I'm trying to build a random quote machine where a user can put in a topic word, an algorithm searches for that word within a list of quotes, makes a new list of quotes that contain that word, and then randomly returns a quote out of the filtered list. If there is no word in the list, it would return any random quote. I can't figure out how to make a filtered list in JavaScript. So far I've got:



      <body>
      <p id="quoteDisplay"></p>
      </body>
      <form>
      <input type="text" id="topic" />
      <button onclick="wiseQuote()">Quote</button>
      </form>

      <script type="text/javascript">
      var quotes = [
      "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
      "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
      "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
      "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
      "Everything in moderation, including moderation - Oscar Wilde",
      "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
      "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
      "The truth is rarely pure and never simple. - Oscar Wilde",
      "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
      "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
      "Facts do not cease to exist because they are ignored. - Aldous Huxley",
      "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
      "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
      "The unexamined life is not worth living. - Socrates"
      ]

      if (topic != null){
      filteredQuotes = quotes.filter(function(){
      return ;
      });
      }

      if (filteredQuotes.length) {
      randomIndex = Math.floor(Math.random() * filteredQuotes.length);
      filteredQuote = filteredQuotes[randomIndex];
      } else {
      randomIndex = Math.floor(Math.random() * quotes.length);
      filteredQuote = quotes[randomIndex];
      }

      document.getElementById('quoteDisplay').innerHTML = filteredQuote;
      }

      </script>


      This is the first project I'm building so I hope this code is not too much of a mess!! Thank you all so much in advance :)







      javascript arrays filter






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 9:51







      mulan

















      asked Nov 20 '18 at 7:27









      mulanmulan

      13




      13
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.



          function wiseQuote(){
          // get value of input
          var topic = document.getElementById("topic").value;
          // filter array based of input value
          var filteredQuotes = quotes.filter(function(val) {
          return val.indexOf(topic) > -1;
          });
          // replace filtered array with origin array if it is empty
          filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
          // generate random number
          var rand = Math.floor(Math.random()*(filteredQuotes.length));
          // insert target item into html
          document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
          }





          function wiseQuote(){
          var topic = document.getElementById("topic").value;
          var filteredQuotes = quotes.filter(function(val) {
          return val.indexOf(topic) > -1;
          });
          filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
          var rand = Math.floor(Math.random()*(filteredQuotes.length));
          document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
          }

          var quotes = [
          "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
          "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
          "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
          "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
          "Everything in moderation, including moderation - Oscar Wilde",
          "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
          "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
          "The truth is rarely pure and never simple. - Oscar Wilde",
          "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
          "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
          "Facts do not cease to exist because they are ignored. - Aldous Huxley",
          "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
          "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
          "The unexamined life is not worth living. - Socrates"
          ];

          <p id="quoteDisplay"></p>
          <form>
          <input type="text" id="topic" />
          <button type="button" onclick="wiseQuote()">Quote</button>
          </form>








          share|improve this answer































            0














            Below is a working solution; however I want to address a few things with your original code to help you out.




            • You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.

            • You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.


            • Array.prototype.filter() expects you to return true or false, nothing else will work.

            • Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.

            • I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().





            function wiseQuote(){
            var topic = document.getElementById("topic").value;
            var randomIndex;
            var filteredQuotes;
            var filteredQuote;

            if (topic != null){
            filteredQuotes = quotes.filter(function(quote){
            return quote.includes(topic);
            });
            }

            if (filteredQuotes.length) {
            randomIndex = Math.floor(Math.random() * filteredQuotes.length);
            filteredQuote = filteredQuotes[randomIndex];
            } else {
            randomIndex = Math.floor(Math.random() * quotes.length);
            filteredQuote = quotes[randomIndex];
            }

            document.getElementById('quoteDisplay').innerHTML = filteredQuote;
            }

            var quotes = [
            "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
            "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
            "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
            "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
            "Everything in moderation, including moderation - Oscar Wilde",
            "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
            "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
            "The truth is rarely pure and never simple. - Oscar Wilde",
            "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
            "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
            "Facts do not cease to exist because they are ignored. - Aldous Huxley",
            "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
            "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
            "The unexamined life is not worth living. - Socrates"
            ];

            <input type="text" id="topic" />
            <button onclick="wiseQuote()">Quote</button>
            <p id="quoteDisplay"></p>








            share|improve this answer


























            • Thank you both ever so much!! It works and the comments are super helpful :)

              – mulan
              Nov 20 '18 at 8:08











            • You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

              – AnonymousSB
              Nov 20 '18 at 8:13











            • Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

              – mulan
              Nov 20 '18 at 8:42













            • Updated with a more organized solution to that problem.

              – AnonymousSB
              Nov 20 '18 at 8:46











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388139%2fhow-to-filter-through-an-array-for-a-user-input-in-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.



            function wiseQuote(){
            // get value of input
            var topic = document.getElementById("topic").value;
            // filter array based of input value
            var filteredQuotes = quotes.filter(function(val) {
            return val.indexOf(topic) > -1;
            });
            // replace filtered array with origin array if it is empty
            filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
            // generate random number
            var rand = Math.floor(Math.random()*(filteredQuotes.length));
            // insert target item into html
            document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
            }





            function wiseQuote(){
            var topic = document.getElementById("topic").value;
            var filteredQuotes = quotes.filter(function(val) {
            return val.indexOf(topic) > -1;
            });
            filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
            var rand = Math.floor(Math.random()*(filteredQuotes.length));
            document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
            }

            var quotes = [
            "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
            "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
            "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
            "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
            "Everything in moderation, including moderation - Oscar Wilde",
            "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
            "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
            "The truth is rarely pure and never simple. - Oscar Wilde",
            "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
            "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
            "Facts do not cease to exist because they are ignored. - Aldous Huxley",
            "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
            "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
            "The unexamined life is not worth living. - Socrates"
            ];

            <p id="quoteDisplay"></p>
            <form>
            <input type="text" id="topic" />
            <button type="button" onclick="wiseQuote()">Quote</button>
            </form>








            share|improve this answer




























              0














              You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.



              function wiseQuote(){
              // get value of input
              var topic = document.getElementById("topic").value;
              // filter array based of input value
              var filteredQuotes = quotes.filter(function(val) {
              return val.indexOf(topic) > -1;
              });
              // replace filtered array with origin array if it is empty
              filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
              // generate random number
              var rand = Math.floor(Math.random()*(filteredQuotes.length));
              // insert target item into html
              document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
              }





              function wiseQuote(){
              var topic = document.getElementById("topic").value;
              var filteredQuotes = quotes.filter(function(val) {
              return val.indexOf(topic) > -1;
              });
              filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
              var rand = Math.floor(Math.random()*(filteredQuotes.length));
              document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
              }

              var quotes = [
              "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
              "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
              "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
              "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
              "Everything in moderation, including moderation - Oscar Wilde",
              "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
              "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
              "The truth is rarely pure and never simple. - Oscar Wilde",
              "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
              "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
              "Facts do not cease to exist because they are ignored. - Aldous Huxley",
              "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
              "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
              "The unexamined life is not worth living. - Socrates"
              ];

              <p id="quoteDisplay"></p>
              <form>
              <input type="text" id="topic" />
              <button type="button" onclick="wiseQuote()">Quote</button>
              </form>








              share|improve this answer


























                0












                0








                0







                You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.



                function wiseQuote(){
                // get value of input
                var topic = document.getElementById("topic").value;
                // filter array based of input value
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                // replace filtered array with origin array if it is empty
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                // generate random number
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                // insert target item into html
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }





                function wiseQuote(){
                var topic = document.getElementById("topic").value;
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }

                var quotes = [
                "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                "Everything in moderation, including moderation - Oscar Wilde",
                "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                "The truth is rarely pure and never simple. - Oscar Wilde",
                "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                "The unexamined life is not worth living. - Socrates"
                ];

                <p id="quoteDisplay"></p>
                <form>
                <input type="text" id="topic" />
                <button type="button" onclick="wiseQuote()">Quote</button>
                </form>








                share|improve this answer













                You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.



                function wiseQuote(){
                // get value of input
                var topic = document.getElementById("topic").value;
                // filter array based of input value
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                // replace filtered array with origin array if it is empty
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                // generate random number
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                // insert target item into html
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }





                function wiseQuote(){
                var topic = document.getElementById("topic").value;
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }

                var quotes = [
                "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                "Everything in moderation, including moderation - Oscar Wilde",
                "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                "The truth is rarely pure and never simple. - Oscar Wilde",
                "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                "The unexamined life is not worth living. - Socrates"
                ];

                <p id="quoteDisplay"></p>
                <form>
                <input type="text" id="topic" />
                <button type="button" onclick="wiseQuote()">Quote</button>
                </form>








                function wiseQuote(){
                var topic = document.getElementById("topic").value;
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }

                var quotes = [
                "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                "Everything in moderation, including moderation - Oscar Wilde",
                "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                "The truth is rarely pure and never simple. - Oscar Wilde",
                "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                "The unexamined life is not worth living. - Socrates"
                ];

                <p id="quoteDisplay"></p>
                <form>
                <input type="text" id="topic" />
                <button type="button" onclick="wiseQuote()">Quote</button>
                </form>





                function wiseQuote(){
                var topic = document.getElementById("topic").value;
                var filteredQuotes = quotes.filter(function(val) {
                return val.indexOf(topic) > -1;
                });
                filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
                var rand = Math.floor(Math.random()*(filteredQuotes.length));
                document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
                }

                var quotes = [
                "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                "Everything in moderation, including moderation - Oscar Wilde",
                "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                "The truth is rarely pure and never simple. - Oscar Wilde",
                "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                "The unexamined life is not worth living. - Socrates"
                ];

                <p id="quoteDisplay"></p>
                <form>
                <input type="text" id="topic" />
                <button type="button" onclick="wiseQuote()">Quote</button>
                </form>






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 '18 at 7:42









                MohammadMohammad

                15.4k123461




                15.4k123461

























                    0














                    Below is a working solution; however I want to address a few things with your original code to help you out.




                    • You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.

                    • You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.


                    • Array.prototype.filter() expects you to return true or false, nothing else will work.

                    • Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.

                    • I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().





                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>








                    share|improve this answer


























                    • Thank you both ever so much!! It works and the comments are super helpful :)

                      – mulan
                      Nov 20 '18 at 8:08











                    • You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                      – AnonymousSB
                      Nov 20 '18 at 8:13











                    • Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                      – mulan
                      Nov 20 '18 at 8:42













                    • Updated with a more organized solution to that problem.

                      – AnonymousSB
                      Nov 20 '18 at 8:46
















                    0














                    Below is a working solution; however I want to address a few things with your original code to help you out.




                    • You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.

                    • You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.


                    • Array.prototype.filter() expects you to return true or false, nothing else will work.

                    • Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.

                    • I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().





                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>








                    share|improve this answer


























                    • Thank you both ever so much!! It works and the comments are super helpful :)

                      – mulan
                      Nov 20 '18 at 8:08











                    • You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                      – AnonymousSB
                      Nov 20 '18 at 8:13











                    • Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                      – mulan
                      Nov 20 '18 at 8:42













                    • Updated with a more organized solution to that problem.

                      – AnonymousSB
                      Nov 20 '18 at 8:46














                    0












                    0








                    0







                    Below is a working solution; however I want to address a few things with your original code to help you out.




                    • You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.

                    • You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.


                    • Array.prototype.filter() expects you to return true or false, nothing else will work.

                    • Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.

                    • I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().





                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>








                    share|improve this answer















                    Below is a working solution; however I want to address a few things with your original code to help you out.




                    • You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.

                    • You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.


                    • Array.prototype.filter() expects you to return true or false, nothing else will work.

                    • Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.

                    • I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().





                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>








                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>





                    function wiseQuote(){
                    var topic = document.getElementById("topic").value;
                    var randomIndex;
                    var filteredQuotes;
                    var filteredQuote;

                    if (topic != null){
                    filteredQuotes = quotes.filter(function(quote){
                    return quote.includes(topic);
                    });
                    }

                    if (filteredQuotes.length) {
                    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
                    filteredQuote = filteredQuotes[randomIndex];
                    } else {
                    randomIndex = Math.floor(Math.random() * quotes.length);
                    filteredQuote = quotes[randomIndex];
                    }

                    document.getElementById('quoteDisplay').innerHTML = filteredQuote;
                    }

                    var quotes = [
                    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
                    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
                    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
                    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
                    "Everything in moderation, including moderation - Oscar Wilde",
                    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
                    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
                    "The truth is rarely pure and never simple. - Oscar Wilde",
                    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
                    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
                    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
                    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
                    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
                    "The unexamined life is not worth living. - Socrates"
                    ];

                    <input type="text" id="topic" />
                    <button onclick="wiseQuote()">Quote</button>
                    <p id="quoteDisplay"></p>






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 20 '18 at 8:46

























                    answered Nov 20 '18 at 7:47









                    AnonymousSBAnonymousSB

                    2,184221




                    2,184221













                    • Thank you both ever so much!! It works and the comments are super helpful :)

                      – mulan
                      Nov 20 '18 at 8:08











                    • You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                      – AnonymousSB
                      Nov 20 '18 at 8:13











                    • Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                      – mulan
                      Nov 20 '18 at 8:42













                    • Updated with a more organized solution to that problem.

                      – AnonymousSB
                      Nov 20 '18 at 8:46



















                    • Thank you both ever so much!! It works and the comments are super helpful :)

                      – mulan
                      Nov 20 '18 at 8:08











                    • You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                      – AnonymousSB
                      Nov 20 '18 at 8:13











                    • Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                      – mulan
                      Nov 20 '18 at 8:42













                    • Updated with a more organized solution to that problem.

                      – AnonymousSB
                      Nov 20 '18 at 8:46

















                    Thank you both ever so much!! It works and the comments are super helpful :)

                    – mulan
                    Nov 20 '18 at 8:08





                    Thank you both ever so much!! It works and the comments are super helpful :)

                    – mulan
                    Nov 20 '18 at 8:08













                    You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                    – AnonymousSB
                    Nov 20 '18 at 8:13





                    You're welcome. I also updated my answer with some information of why I removed the <form> element in my example.

                    – AnonymousSB
                    Nov 20 '18 at 8:13













                    Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                    – mulan
                    Nov 20 '18 at 8:42







                    Thank you so much, you're lovely and the comments are suped helpful! With your code, however, a tiny thing: if you entered a topic that didn't have a corresponding quote (like "jeans"), it'd come up with "undefined". Guess that's because the "else" applied to if "topic = null". I fixed it by mixing your guys codes up and adding filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes; randomIndex = Math.floor(Math.random() * quotes.length); filteredQuote = quotes[randomIndex]; before the "else" part :)

                    – mulan
                    Nov 20 '18 at 8:42















                    Updated with a more organized solution to that problem.

                    – AnonymousSB
                    Nov 20 '18 at 8:46





                    Updated with a more organized solution to that problem.

                    – AnonymousSB
                    Nov 20 '18 at 8:46


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388139%2fhow-to-filter-through-an-array-for-a-user-input-in-js%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    SQL update select statement

                    'app-layout' is not a known element: how to share Component with different Modules