2

I have a search function here:

<form class="form-wrapper cf">
    <input type="text" placeholder="Enter keywords..">
    <button onclick="search_click();">Search</button>
</form>

search_click() is defined as follows:

function search_click(){
    window.location.replace("http://stackoverflow.com");
}

However, every time I click the button, it just reloads the current page and appends a '?' to the end of the URL if it wasn't already there. I've tried doing window.location.href also, but that doesn't work either. If I just replace that line with alert('test');, it does show a popup, so I know it's executing. What's wrong with my code? Or is this a problem with Django?

1 Answer 1

4

The form is actually submitting causing your Javascript to be ignored. Prevent the default event using the following script:

function search_click(event){
    event.preventDefault();
    window.location.replace("http://stackoverflow.com");
}

HTML

<form class="form-wrapper cf">
    <input type="text" placeholder="Enter keywords..">
    <button onclick="search_click(event);">Search</button>
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be bad practice to use preventDefault() ?

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.