Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is form attr (' action ')?

The HTML form action attribute defines what should happen to data when a form is submitted on a web page. The value of the action attribute should be the URL of the web resource that will process the contents of the form.

What does action attribute take as value in a form?

The action attribute defines the action to be performed when the form is submitted. Usually, the form data is sent to a file on the server when the user clicks on the submit button.

How do I change the action of a form in HTML?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript. Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

Can a form have multiple actions?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.


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

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);
}); 

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>