0

I am building a flask website and am trying to make a search bar that is always on the top menù, I would have liked to handle it in the Python backend but I could not find a way to do that without including whithin each backed page the code to handle it (which if it is the only way is fine) so I decided to try making it work with JavaScript. This is my code (without the parts which I found unrelated to the problem):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<input type="search" id="searchbar"/>
<button id="goto">Search</button>
</form>
<script>
            document.getElementById("goto").addEventListener("click", goTo);
            function goTo()
            {
                var result = document.getElementById("searchbar").value;
                window.location.href = "/users/"+result;
            }
</script>
</body>
</html>

What it is supposed to do is redirect me to "http://myip/users/WhatItyped" while it just adds "/?" to the end of the URL, any idea of why this is?

Update: I found out that if I add an alert before defining result it works

1 Answer 1

1

Try using window.location.pathname

JavaScript Window Location states href points to the full URL, including protocol & hostname. Since you are not changing either of those, you can just change the relative path from the root using pathname.

This has also been answered before: How can I extract and then change the url path using javascript?

Sign up to request clarification or add additional context in comments.

3 Comments

It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.
Unfortunately this did not work but I did find out the problem is correlated with the form tag I put on it which stupidly I did not use in the code here, removing it this worked. Is there any way to make this work with the form tag? Thanks for the help!
i copied your code above, made my change, & it worked in Firefox, so I'm not sure why it didn't work for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.