JavaScript: how to change form action attribute value based on selection?

n00b0101 picture n00b0101 · Dec 18, 2009 · Viewed 255.4k times · Source

I'm trying to change the form action based on the selected value from a dropdown menu.

Basically, the HTML looks like this:

<form class="search-form" id="search-form" method="post" accept-charset="UTF-8" action="/search/user">
<select id="selectsearch" class="form-select" name="selectsearch">
<option value="people">Search people</option>
<option value="node">Search content</option>
</select>

<label>Enter your keywords: </label>
 <input type="text" class="form-text" value="" size="40" id="edit-keys" name="keys" maxlength="255" />

<input type="submit" class="form-submit" value="Search" id="edit-submit" name="search"/>
</form>

If "people" is selected, (which it is by default), the action should be "/search/user", and if content is selected, the action should be "/search/content"

I'm still searching around, but haven't been able to find out how to do this.

Answer

cletus picture cletus · Dec 18, 2009
$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});