Stack Overflow Asked by Vuk Stamenkovic on December 16, 2021
I yesterday created a website with functional searchbar. But my problem with it is, I coded it in JavaScript, and I don’t know how to link URL on click to button. https://apex-lang.github.io is my website, check out "Search destination" searchbox to see what I mean. Here is my JavaScript code:
const ac = document.querySelector('.autocomplete');
M.Autocomplete.init(ac, {
data: {
"Aruba": null,
"Cancun Mexico": null,
"Hawaii": null,
"Florida": null,
"California": null,
"Jamacia": null,
"Europe": null,
"Bahamas": null,
"Nova Scotia": null,
"Rialto": null,
}
});
I used MaterializeCSS framework to make this website.
<!-- Section: Search -->
<section id="search" class="section section-search teal darken-1 white-text center scrollspy">
<div class="container">
<div class="row">
<div class="col s12">
<h3>Search Destinations</h3>
<div class="input-field">
<input class="white grey-text autocomplete" placeholder="Aruba, Cancun, etc..." type="text" id="autocomplete-input">
</div>
</div>
</div>
</div>
</section>
This is my HTML Code
You could try to add an onclick function to the list that MaterializeCSS creates (class .autocomplete-content)
Then you can get the target of the click with event.target, then you have access to its properties
for example
document
.querySelector(".autocomplete-content")
.addEventListener(
"click",
e => {
var item= e.target
// what to do on each click
console.log(item.innerHTML)
}
)
tested directly on your site it gives me <span class="highlight">Can</span>cun Mexico
for your site to redirect to the page 'https://apex-lang.github.io/cancun' when clicking to cancun and to 'https://apex-lang.github.io/aruba' when wlicking on aruba :
// first declare a dictionnary with key = text of the item and value = url
var redirections = {
"Aruba": "https://apex-lang.github.io/aruba",
"Cancun Mexico": "https://apex-lang.github.io/cancun"
// add all the items here
// be sure the text is the exact same as in the list given to Autocomplete
}
document
.querySelector(".autocomplete-content")
.addEventListener(
"click",
e => {
var item= e.target
var destination = item.innerText
// only gets the visible text without the tags
window.location = redirections[destination] // redirects the page to the URL
}
)
Answered by gui3 on December 16, 2021
Here is the answer:
<!DOCTYPE html>
<html>
<body>
<input id="age">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction(a) {
a = document.getElementById("age").value;
if (a == "Aruba") {window.open("your link")}
else if (a == "Another country") {window.open("your link")}}
</script>
This works
Answered by user13962354 on December 16, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP