Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript onclick redirect

I have this text field and button here

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

and when the user clicks on the submit button this function is suppose to run

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value();
        window.location = "http://www.example.com/search/?Query=" + Searchtxt;
    }
</script>

But nothing happens, what I expecting to happen is when the user clicks on the submit button, take the value from the search text box and redirect the user to the url + the value of the search text box...

What am I doing wrong?

like image 643
user1269625 Avatar asked Oct 09 '12 14:10

user1269625


People also ask

How do I redirect a clicked button?

The first way through which you can redirect from one page to another is by clicking a button. You can use a form for this purpose. The form tag in HTML has an attribute action where you can give the URL of the webpage, where you want the form button to redirect. The form tag also has another attribute method.

How do I redirect a button to another page?

By using HTML Anchor Tags <a>.. </a>, you can Redirect on a Single Button Click [html button click redirect]. To use HTML Anchor tags to redirect your User to Another page, you need to write your HTML Button between these HTML Anchor Tag's starting <a> and Closing </a> Tags.

How do you redirect to another page using onclick event in react?

To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.


2 Answers

There are several issues in your code :

  • You are handling the click event of a submit button, whose default behavior is to post a request to the server and reload the page. You have to inhibit this behavior by returning false from your handler:

    onclick="SubmitFrm(); return false;"
    
  • value cannot be called because it is a property, not a method:

    var Searchtxt = document.getElementById("txtSearch").value;
    
  • The search query you are sending in the query string has to be encoded:

    window.location = "http://www.mysite.com/search/?Query="
        + encodeURIComponent(Searchtxt);
    
like image 196
Frédéric Hamidi Avatar answered Oct 12 '22 04:10

Frédéric Hamidi


Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"
like image 44
Ian Avatar answered Oct 12 '22 04:10

Ian