Gwilym
Gwilym

Reputation: 11

Simple javascript form action direction

I am trying to use Jquery to re-form a target url for a form - see below. Any ideas where I am going wrong? many thanks ...

<!DOCTYPE html>
<html>
<head>
  <style>
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

  <script>
      // Needs to point at search page with eg: test.htm?s=SearchTerm&cat=3,7
      // but I keep getting - test.htm?s=hh&cat1=3&cat2=0
      $("#aSearch").click(function () { 
        $('form').attr('action', './test.htm?s=' + this.s + '&cat=' . this.cat1 + ',' + this.cat2);
      });
  </script>

  <form name="advancedSearch" action="" method="get">
    <input id="s" type="text" name="s" size="40" />
    <select name="cat1">
      <option value="0"> - - - </option>
      <option value="3">Chardonnay (6)</option>
      <option value="23">Gewurztraminer (1)</option>
      <option value="24">Pinot Gris (1)</option>
      <option value="4">Sauvignon Blanc (3)</option>              
    </select>
    <select name="cat2">
      <option value="0"> - - - </option>
      <option value="2">Burgandy (6)</option>
      <option value="7">Shiraz (1)</option>           
    </select>
    <div><input id="aSearch" type="submit" value="Search" /></div
  </form>

</body>
</html>

Upvotes: 1

Views: 219

Answers (1)

Jon Gauthier
Jon Gauthier

Reputation: 25582

In your original code, you were trying to access properties of this. The this keyword in the callback referred to the aSearch DOM object, and so it wasn't providing the right values.

$('form').attr('action', './test.htm?s=' + this.s + '&cat=' . this.cat1 + ',' + this.cat2);

You'll need to select each element with jQuery and fetch its value with .val() instead:

<script>
    $(document).ready(function() {
        var s = $('#s');
        var cat1 = $('#cat1');
        var cat2 = $('#cat2');

        $("#aSearch").click(function () { 
            $('form').attr('action', './test.htm?s=' + s.val() + '&cat=' . cat1.val() + ',' + cat2.val());
        });
    });
</script>

Upvotes: 1

Related Questions