whiterook6
whiterook6

Reputation: 3534

How can I fill the action parameter of a form with values from the form's input?

I know I can pass query parameters from a form and expect them in the query string:

<form method="GET">
  <input type="text" name="param" value="value" />
  <input type="submit" value="submit" />
</form>

This results in

http://blah-blah-blah/blah?param=value

However, in my webapp, I'm using path parameters. To access a single book, #459, in the library, you'd visit

/books/459

and to check one out, POST to

/books/459/checkout

where 459 is a path parameter. When I try

<form action="/books/{book_id}">...</form>

it takes me to

/books/%7Bbook_id%7D

rather than

/books/459

Do I need javascript or something to build the URI?

Upvotes: 2

Views: 6315

Answers (3)

vijayan007
vijayan007

Reputation: 386

  • Thanks to RobG

  • I have used the same thing in calling WhatsApp from mobile application

  • It works beautifully

    <form action="https://wa.me/" 
    onsubmit="this.action = this.action + this.mobile.value; this.submit();">
      <input type="tel" name="mobile" size="10" value="91xxxxxxxxxx"/>
      <input type="text" name="text" value="Thanks Vijayan!" />
      <input type="submit" value="WhatsApp" />
    </form>
    

Upvotes: 1

RobG
RobG

Reputation: 147363

You may need something like:

<form onsubmit="this.action = this.action + this.book_id.value;" ...>

However, making the action dependent on scripting is poor design. It is much more robust for your server to deal with the URI ...?book_id=value, which does not require any client script at all.

Upvotes: 1

Fallexe
Fallexe

Reputation: 596

If you are generating your HTML with PHP, the code below should work (untested).

$book_id = 459;
<form action="/books/{$book_id}">...</form>

Alternatively, you could dynamically modify the html using JavaScript. It is better not to do it this way because some users may disable JavaScript. (untested)

$('form').attr('action','/books/' + book_id);

Upvotes: 0

Related Questions