Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why html can´t read this javascript function?

I am trying to recreate the google main page however my problem is with the I am feeling lucky button when I press the I am feeling lucky button the function luck() is not being recognized.

Error:

Uncaught TypeError TypeError: luck is not a function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Search</title>
        <link rel="stylesheet" href="style.css">
        <script type="text/javascript" src="combinados.js"></script>
        <script type="text/javascript">
            function luck() {
                var query = document.querySelector(".search").value;
                window.location.href = "https://www.google.com/search?q=" + encodeURIComponent(query) + "&btnI";
            };
         </script>

    </head>
    <body >
        <form class="bar" action="https://www.google.com/search">
            <input class="search" type="text" name="q">
            <input id ="search" type="submit" value="Google Search">
            <input id ="luck" type="button" value="I am feeling lucky" onclick="luck()">
            
        </form>
        <ul id="links">
            <li><a href="imagesearch.html">Image Search </a></li>
            <br>
            <li><a href="advancedsearch.html">Advanced Search </a></li>
        </ul>
    </body>
</html>

Why doesn’t this code work?

>Solution :

In your code, you have the id of the <input>, and function name is same. So, when the button is clicked, the browser tries to execute the luck() function but there’s an HTML element with the id of luck, which creates confusion.

To fix this, you can either change you function name or <input> id.

Here’s an example where I changed the function name to feelingLucky().

<input id="luck" type="button" value="I am feeling lucky" onclick="feelingLucky()">
function feelingLucky() {
    var query = document.querySelector(".search").value;
    window.location.href = "https://www.google.com/search?q=" + encodeURIComponent(query) + "&btnI";
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading