<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material Icons" rel="stylesheet" />
<link rel="stylesheet" href="styles.css" />
<title>Search</title>
</head>
<body>
<div >
<div >
<a href="./advanced.html">Advanced Search</a>
<a href="./images.html">Images</a>
</div>
</div>
<div >
<img
src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
alt="google img"
/>
<div >
<div >
<span > search </span>
<form action="https://google.com/search">
<input type="text" name="q" autofocus>
<span > mic </span>
</form>
</div>
<div >
<button type="submit" name="q" onclick='location.href="https://google.com/search?q="'>Google Search</button>
</div>
</div>
</body>
</html>
Here is my Code. I have made my Google Search button clickable but it sends me to a generic google page. How do I change it so it searches whatever I type into the text box?
CodePudding user response:
Thats because you are not specifying the query parameter properly. Remove the onclick
attribute of the button. google replaces the spaces between words with character, so we have to perform this operation and then assign the url.
<script>
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
let query = e.target.querySelector('input[name="q"]').value;
query = query.replace(' ', ' ');
window.location.href = "https://google.com/search?q=" 'query'
});
</script>
CodePudding user response:
To submit the form to the url specified under form action attribute you need to add the submit button within the form tags. Therefore the code (div of ) can be simply edited as follows:
<div >
<div >
<span > search </span>
<form method="get" action="https://google.com/search">
<input type="text" name="q" autofocus>
<span > mic </span>
<button type="submit"> Google Search</button>
</form>
</div>
</div>