0

How to set action value in form depending on the value of select?

<form action="/my-url/{{design.id}}" method="get">
    <select name="producttype">
       <option value="lite">Select one of option</option>
       <option value="a">Option a</option>
       <option value="b">Option b</option>
       <option value="c">Option c</option>
    </select>
</form>

How to create something like this:

If select option have value a my form action will be: <form action="/my-url/{{design.id}}/a" method="get">

If select option have value b my form action will be: <form action="/my-url/{{design.id}}/b" method="get">

Antony
  • 14,900
  • 10
  • 46
  • 74
user2307683
  • 2,009
  • 2
  • 16
  • 13
  • 1
    Why don't you simply pass in the value of `producctype` as an URL parameter? – Jon Jun 17 '13 at 09:08
  • Possible duplicate of http://stackoverflow.com/questions/1925614/jquery-change-form-action-based-on-selection – billyonecan Jun 17 '13 at 09:09
  • 1
    Instead of JavaScript you should consider rewriting your server-side script so that it accepts the url `/my-url/{{design.id}}?producttype=a` instead, possibly redirecting to `/my-url/{{design.id}}/a` – RoToRa Jun 17 '13 at 09:48

3 Answers3

1

this should work:

$("select[name='producttype']").change(function(){
    var form = $("form");
    var action = "/my-url/{{design.id}}/" + $(this).val();
    form.attr("action", action);
});

Couple of things to note:

  1. If you have multiple forms on the page, then you need a more accurate way of selecting the correct form - perhaps an id attribute

  2. What is {{design.id}}? Is this meant to be generated dynamically?


A solution to Note 2 could be to include the base URL as a data-* attribute, something like this:

<form action="/my-url/{{design.id}}" data-baseurl="/my-url/{{design.id}}/" method="get">

and then change the above javascript to be like this:

var action = form.data("baseurl") + $(this).val();

Here is a working example

musefan
  • 47,875
  • 21
  • 135
  • 185
0

Try

$('select[name="producttype"]').change(function(){
    var $this = $(this);
    $this.closest('form').attr('action', '/my-url/' + $this.val())
})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can try:

var producttype = document.getElementsByName("producttype")[0];
producttype.onchange = function() {
    var form = document.getElementsByTagName("form")[0];
    form.action = "/my-url/{{design.id}}/" + this.value;
}  
Xiaodan Mao
  • 1,648
  • 2
  • 17
  • 30