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

258,740

Solution 1

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

Solution 2

If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.

$('#search-form').submit(function(){
  var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + formAction);
}); 

Solution 3

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>
Share:
258,740

Related videos on Youtube

n00b0101
Author by

n00b0101

Updated on April 28, 2021

Comments

  • n00b0101
    n00b0101 about 3 years

    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.

  • n00b0101
    n00b0101 over 14 years
    That is way better than what I was trying... Thank you
  • Ryan
    Ryan over 12 years
    Worked perfect. Thanks. I updated this code to change the action on submit instead of on form change.
  • SET001
    SET001 almost 12 years
    this.form.submit(); will have no sense since there are actually no forms an thus - nothing to submit
  • trante
    trante over 10 years
    If you design for mobile devices it would be better to change action "on submit" for performance issues. Check my answer below.
  • gsinha
    gsinha about 8 years
    Use prop instead of attr. Example = $("#search-form").prop ("action", "/search/" + action);
  • enorl76
    enorl76 about 5 years
    why would DOMElement setAttribute save any time over using jquery attr?