I have this code that needs to be adapted to work with something similar to the code below the commented line. If I can make it without many changes would be perfect so that I don't need to change the CSS and so. Any help? Many thanks in advance.
<!-- The code to be adapted is this: -->
<form action="" id="search-form">
<fieldset>
<input type="text" /><input type="submit" value="Search" />
</fieldset>
</form>
<!-- The new code that I got from the web and that needs to be adapted to the old one
is the following: -->
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" Blah "");
}
</script>
CodePudding user response:
I'm imagining you probably want something like
document.querySelector("#searchButton").addEventListener("click", ()=>{
const value = document.querySelector("#searchBox").value;
const url = `https://www.google.com/search?q=${encodeURIComponent(value)}`;
window.location.replace(url);
});
<fieldset>
<input type="text" id="searchBox">
<Button id="searchButton">Search</button>
</fieldset>
The id attribute on HTML elements allows you to access them via JavaScript. There's a wealth of tutorials online if you want to learn JavaScript deeply, but the basics of what this is doing is:
- It finds the HTML element with the
idofsearchButton, and adds aclicklistener to it --- this gets triggered whenever that element is clicked. - In that listener, we find the value of the text input with the
idofsearchBox. - We compose our new URL. One thing I've added here is a call to
encodeURIComponentto correctly handle the cases where they try searching for something which contains a character which isn't valid in a URL --- for example, the space character etc.
CodePudding user response:
It was not working as I wanted, but a little trick made it work. Here is my final code:
<form action="" id="search-form">
<fieldset>
<input type="text" id="searchBox">
<input type="submit" value="Search" />
</fieldset>
</form>
<script>
let myvar;
document.querySelector(".submit").addEventListener("click", ()=>{
const value = document.querySelector("#searchBox").value;
myvar = `https://www.google.com/search?q=${encodeURIComponent(value)}`;
setTimeout(callurl, 1);
return false;
});
function callurl() {
location.assign(myvar);
return false;
}
</script>
