2

I'm validating a form and after validation, I want to redirect with window.location = xxx but it doesn't work unless I put an alert call after it.

The validation works by handling the onsubmit event of the form.

function isvalid()
    {
        var txt = document.getElementById('txtTitle');
        if (txt.value == '')
        {   alert('Please enter a title'); return false;}
        else 
        {

            var sURL = "get_movies.php?title=" + txt
            window.location.href = sURL;
            //alert('');
            return true;
        }
    }
  • Not sure if this helps, but months ago I notice that _some_ browsers only support `document.location`. But `location.assign()` (without any prefix object) always work. You may want to try that. – Passerby Oct 16 '12 at 05:07
  • after the onsubmit is handled did you return false to stop the event bubbling? – andrean Oct 16 '12 at 05:07
  • try to use `return false` instead of `returns true` – Naresh J Oct 16 '12 at 05:08
  • @andrean I used return false and it worked. I also changed the redirect code to document.location – user1477707 Oct 16 '12 at 15:18
  • @NareshJ thanks, return false works, but can you explain why? – user1477707 Oct 16 '12 at 15:18
  • @user1477707, I explained why it works in my answer (and sorry for the confusion around the typo in the last sentence, it's fixed now) – Nick B Oct 16 '12 at 15:42
  • @user1477707, just for your information, check this link http://stackoverflow.com/questions/855360/when-and-why-to-return-false-in-javascript – Naresh J Oct 17 '12 at 04:55

2 Answers2

1

The form's onsubmit expects either a true or false return value. If you return true, the form will be submitted. Since you want to manually set the window.location on a form submit, it doesn't make sense to return true (you will then have the page fighting over a form submit and a JS redirect.

Put return false in your else block and you should be good to go.

Nick B
  • 7,639
  • 2
  • 32
  • 28
0

Try

document.location = sUrl;

It always works for me.

Hernan Velasquez
  • 2,770
  • 14
  • 21