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

Viewed 259032

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.

6 Answers
$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

Simple and easy in javascipt

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

If you want to change from Pure javascript means use follow methods. Same as Ankush Kumar's code with Extra methods

function fn_one(){
  document.formname.action="https://google.com/search?q=form+submit+using+name";
}
function fn_two(){
  document.getElementsByName("formname")[0].action="https://google.com/search?q=form+submit+using+name+method+2";
}
function fn_three(){
  document.getElementById("formid").action="https://google.com/search?q=form+submit+using+ID";
}
<form name="formname" id="formid" action="google.com/search?q=" target="_blank">
  <div>
    <button type="button" onclick="fn_one()">Change By Name {1}</button>
    <button type="button" onclick="fn_two()">Change By Name {2}</button>
    <button type="button" onclick="fn_three()">Change By ID</button>
  </div>
   <div>
    <button type="submit">Go To Google</button>
  </div>
</form>
    

Related