Domanda

I have a simple search field:

  <form id="searchForm" action="">
    <input type="text" name="searchField" id="searchField" value="">
  </form>

I've tried several variations of this (related link):

<script>
  $('#searchField').keypress(function (e) {
    if (e.which == 13) {    // hit enter
      $('#searchForm').submit(function(){
          var val = $('#searchField').val();
          this.action = "index.php?g="+genre+"&s="+val; 
          return false;
      });
    }
  });
</script>

and this:

<script>
  $('#searchField').keypress(function (e) {
    if (e.which == 13) {    // hit enter
      var val = $('#searchField').val();
      $('#searchForm').attr("action","index.php?g="+genre+"&s="+val);
      $('#searchForm').submit();
      return false;
    }
  });
</script>

But am unable to get the page (action) to direct to the desired page. Even if I try and set the action externally (eg: Google.com), it will not send me there. What am I missing? The genre var is declared previously btw.

Also, I know it needs validation - just trying to get it working first.

Thanks

È stato utile?

Soluzione

<form id="searchForm" action="" method="post" >
    <input type="text" name="search" id="searchField" value="">
</form>
<script>
$(function(){
    $('#searchField').keypress(function (e) {
    if (e.which == 13) {   
        var genre = 'test';
        var val = $('#searchField').val();
        $('#searchForm').attr("action","index.php?g="+genre+"&s="+val);
        $('#searchForm').submit();
          return false;
    }
  });
});
</script>

Try Now... I have changed the form method to post now its working fine.

Altri suggerimenti

You should go with the second approach. But you have to provide your script inside Jquery's document.ready function.

<script>    

$(document).ready(function(e) {

    $('#searchField').keypress(function (e) {
        if (e.which == 13) {    // hit enter
        var genre = 'abcd';
            var val = $('#searchField').val();
            $('#searchForm').attr("action","index.php?g="+genre+"&s="+val);
            $('#searchForm').submit();
            return false;
        }
    });

});

</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top