Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: Focus

  1. #1
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Focus

    So I'm a noobie at JavaScript and I'm messing around and learning things here and there well I ran into a small problem. I made a simple form like a search form and created a function that check and see if the input field that is suppose to be where for example the user types in her/her search term. And the message pops up and displays everything like it should but after it shows the message the form continues on and goes onto the next page. And I don't want that. I just want it to end everything until the user types in a search term. So here is my script.

    Code:
    <script type="text/javascript">
    function myFun() {
    	
    	var find = document.getElementById('find');
    	
    	if(document.getElementById('find').value=='') {
    	alert("You must type in a search term.");
    	find.focus();
    	return false;
    	}
    }
    
    </script>
    Thanks for the help.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,613
    Thanks
    80
    Thanked 4,635 Times in 4,597 Posts
    Show where and how you *call* that function.

    If you are doing something like:
    Code:
    <form ... onsubmit="myFun( );">
    then you need to change it to
    Code:
    <form ... onsubmit="return myFun( );">
    Same would apply if you are using an image button or submit button and doing onclick="myFun( )"

    If something other than those, show more code.

  • #3
    Regular Coder
    Join Date
    Jan 2008
    Posts
    334
    Thanks
    9
    Thanked 0 Times in 0 Posts
    The code is called by this here:

    Code:
    <form action="http://localhost" method="get" onsubmit="myFun()">
    <input name="input" id="find" type="text" />
    <input name="submit" value="Search" type="submit" />
    </form>
    Sorry it took me so long I took a little nap. lol long day. Even with onsubmit="myFun()" it still goes onto the other page.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,613
    Thanks
    80
    Thanked 4,635 Times in 4,597 Posts
    *READ* what I wrote. I even put it in red. Maybe bigger will help?

    Code:
    <form action="http://localhost" method="get" onsubmit="return myFun()">
    If you don't have that return in there, you are effectively saying "always return true."

    Yes, you *also* need the return in your function.

    And, incidentally, your function never returns a true value, explicitly. Usually isn't needed, but play it safe!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •