4

So i wanted to open a new page replacing the current one, i found that the method should be putting the second parameter on _self but nothing happen... By the way, if i use the _blank parameter or i left it empty it opens in a new page. The rest of the function works good, but i can't find a way to close the current page and open the new one that i want. Here is the javascript and the html buttom that call the function.

    <button id="rgstr_btn" type="submit" class="btn btn-info" onClick="store()">Register</button>   
      <script>
                function store() {
                localStorage.setItem('nome', nome.value);
                localStorage.setItem('pw', pw.value);
                window.open('url', '_self');
            }
</script>
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Poli
  • 89
  • 1
  • 2
  • 8
  • 1
    Why not just set `window.location.href`? – Pointy Jan 28 '18 at 15:06
  • Does this button reside in a ```form``` tag? In that case add a ```type="button"``` attribute, otherwise it also submits the form (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-type), which may clash with your own page loading efforts. – tevemadar Jan 28 '18 at 15:21
  • You are right man thank you very much now it works – Poli Jan 28 '18 at 15:30
  • ok, I added it as an answer then – tevemadar Jan 28 '18 at 16:01

2 Answers2

5

Button has a type attribute which defaults to submit: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-type
While this does not affect "everyday" buttons, if the button resides in a form, this way it will submit the form, and result in some page loading, which clashes with your own attempt. You can just add a type="button" attribute to the button to avoid that:

<button id="rgstr_btn" type="button" class="btn btn-info" onClick="store()">Register</button>
                       ^^^^^^^^^^^^^
tevemadar
  • 12,389
  • 3
  • 21
  • 49
3

windows.open() opens the URL in a new window.

To replace the URL in the current window, use:

window.location.href = 'http://example.com';
iBug
  • 35,554
  • 7
  • 89
  • 134
debe
  • 1,752
  • 2
  • 12
  • 11
  • 2
    Still nothing... it looks like the page reloads because it deletes the fields of the form that is in the page but it doesn't open any page – Poli Jan 28 '18 at 15:24