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
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";
};