0

I have the following code in an ASP page:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <input type="text" id="TextBox1" />
    <input id="Button1" type="button" value="button" />
            <script type = "text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                var textbox = document.getElementById("TextBox1").value;
                if (textbox.length > 0) {
                    alert("Hello world!");
                    window.location.href = "http://westmedgroup.com/search_results.aspx?searchtext=" + textbox + "&folderid=0&searchfor=all&orderby=title&orderdirection=ascending";
                }
                else {
                    alert("Search query empty");
                }
            });
            $('#TextBox1').keyup(function () {
                var $th = $(this);
                $th.val($th.val().replace(/[^a-zA-Z0-9]/g, ''));
            });
            $('#TextBox1').keypress(function (e) {
                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 13) {
                    var textbox = document.getElementById("TextBox1").value;
                    if (textbox.length > 0) {
                        window.location.href = "http://westmedgroup.com/search_results.aspx?searchtext=" + textbox + "&folderid=0&searchfor=all&orderby=title&orderdirection=ascending";
                    }
                    else {
                        e.preventDefault();
                    }
                }
            });
        });
    </script> 
</asp:Content>

When I click the button it does what it is supposed to, if there is a text value then show an alert and then redirect to the search result page otherwise do not re-direct and display a search query empty alert. I am trying to do the same thing for the textbox but everything I hit enter and there is a text value it just refreshes the page without redirecting. How do I modify the code so the textbox and the button works like together.

Si8
  • 9,141
  • 22
  • 109
  • 221
  • 1
    Yeah, I realized this later, I'm used to pure JS. Here's a quick pointer: http://stackoverflow.com/a/4379459/3227403 – pid Jan 24 '14 at 09:11

1 Answers1

1

Pressing enter in the textbox submits the form, you should e.preventDefault() even when you redirect.

pid
  • 11,472
  • 6
  • 34
  • 63
  • @SiKni8: To be honest I don't trust my own words anymore. The input is not type="submit" but type="button", so there should be no implicit form action fired. Can you please "return false" (signaling that the event has been handled)? Please tell what the problem and solution was. I'm curious. – pid Jan 24 '14 at 09:10
  • Actually the `e.preventDefault()` did the trick :) I am still testing though. – Si8 Jan 24 '14 at 13:35