Search code examples
javascriptwindow.locationsubmit-button

javascript/jquery to change location.href


This is my HTML

        <form id="procurar-novo">
          <input type="text" name="procurar" placeholder="Pesquisar no Site" value="">
          <input id="procurar-submit" type="button" value="&rsaquo;">
        </form>

And this is my jQuery

<script type="text/javascript">
  $(document).ready(function(){
    $('#procurar').submit(function(e) {
      e.preventDefault();
      //edited
      window.open = ('http://www.psicotropicus.org/'+'/busca'+encodeURIComponent($('#procurar-submit').val()), '_blank');
      return false;
    });
  });
</script>

The ideai is that by clicking on submit, the javascript/jquery will get the #procurar-submit value and add it on the URL and redirect the user.

The _blank still not works

Thanks in advance.


Solution

  • Looks like you don't have an action specified on your form tag. Why not just change the second input element from type=submit to type=button. Then you can bind a click event on that button and have full control of what happens next. You don't have to worry about preventing a default submit action. You could do the following:

    $(document).ready(function(){
      $(document).on('click', '#procurar-submit', function() {
        window.location.href = 'http://www.psicotropicus.org/busca'+$('input[name="procurar"]').val();
      });
    });
    

    To open a new window like on a '_blank' you could change the code to be:

    $(document).ready(function(){
      $(document).on('click', '#procurar-submit', function() {
        window.open('http://www.psicotropicus.org/busca'+$(input[name="procurar"]).val(), '_blank');
      });
    });
    

    But be careful with pop-up blockers

    EDIT I changed the selector that gets the value of the text field. I would maybe add a class or id on that text field so it can be identified apart from others. See this fiddle