Lloyd Dominic
Lloyd Dominic

Reputation: 808

Change form's action attribute dynamically

I have a form in HTML. Inside the form, there are only two input fields:

<input type="search">

<input type="submit">

Now, the problem is, how could I change the value of the action attribute to the value typed in the input type='search', when I submit the form.

Is this possible?

Upvotes: 0

Views: 1162

Answers (2)

Chuck Le Butt
Chuck Le Butt

Reputation: 48758

I cannot fathom why anyone would want this, but here's how you do it.

HTML code

<form id="searchForm">
  <input type="search" id="search">
  <input type="submit">
</form>

jQuery is

<script>
$("#searchForm").on('submit', function(){
  var $userEntered = $(this).children('#search').val();
  $(this).attr("action", $userEntered);
});
</script>

This will place whatever the user enters into the search field into the action attribute of the form.

JSFiddle: https://jsfiddle.net/JohnnyWalkerDesign/bwnvhz24/

(Note: You can see the JSFiddle work by entering something like https://www.google.com into the input field. It must begin with https:// because that's what JSFiddle uses.)

Upvotes: 1

Shubham
Shubham

Reputation: 1793

You can check it .

HTML code

<form action="http://www.google.com" id="checking">
  <button type="submit">click it</button>
</form>

script code is

<script>
$("#checking").submit(function(e){
  this.action = "http://www.w3schools.com";
});
</script>

Upvotes: 0

Related Questions