I've found a similar question here: javascript - change form action based on selection?
But my problem is slightly different. I have two selects:
<form id="CarSearch" action="" method="post">
<select name="style" id="Style">
<option value="" selected>Any Style</option>
<option value="style/sports-1">Sports</option>
<option value="style/wagon-3">Wagon</option>
<option value="style/suv-6">SUV</option>
</select>
<select name="make" id="Make">
<option value="" selected>Any Make</option>
<option value="make/porsche-3">Porsche</option>
<option value="make/ford-6">Ford</option>
<option value="make/volvo-7">Volvo</option>
</select>
<input type="submit" value="submit"/>
</form>
I want to build the form action attribute based on the values in both selects. So here are the situations:
- If both the Style and Make are set to "Any" and hence have no values; the form action should be blank.
- If a Style is specified, but Make isn't; the form action should be just the value from Style e.g.
action="style/sports-1"
- If a Make is specified, but Style isn't; the form action should be just the value from Make e.g.
action="make/volvo-7"
- If both a Style and Make are specified; the form action should be a concatenation of the values from Style and Make e.g.
action="/style/sports-1/make/volvo-7"
The defaults for both selects is always "Any". I could try to create two variables in jQuery for each select and set their values whenever either select changes. But its the concatenation part that's confusing me.
I have created a JSFiddle here to get me started http://jsfiddle.net/L91rb9f9/3/
I'm ending with two slashes when a Style isn't specified.