Herp
Herp

Reputation: 53

HTML form with dynamic action (using JavaScript?)

I want to create a form like this:

  1. Type in your ID number into the form's input and submit.
  2. The form's action becomes something like /account/{id}/.

I was told JavaScript was the only way to achieve this (see here), but how?

Upvotes: 5

Views: 12609

Answers (3)

call0fcode
call0fcode

Reputation: 163

You can do something like this in JavaScript. Depending on the checked radio button (in this case,but it could be another form element) it will be chosen an action or the other:

<script type="text/javascript">
function OnSubmitForm()
{
  if(document.myform.operation[0].checked == true)
  {
    document.myform.action ="insert.html";
  }
  else
  if(document.myform.operation[1].checked == true)
  {
    document.myform.action ="update.html";
  }
  return true;
}
</script>

<form name="myform" onsubmit="return OnSubmitForm();">
   name: <input type="text" name="name"><br>
   email: <input type="text" name="email"><br>
   <input type="radio" name="operation" value="1" checked>insert
   <input type="radio" name="operation" value="2">update
   <p>
   <input type="submit" name="submit" value="save">
   </p>
</form>

Upvotes: 1

Demian Brecht
Demian Brecht

Reputation: 21378

<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(frm.txt).keyup(function(){
            $(frm).get(0).setAttribute('action', '/account/'+$(frm.txt).val());
        });
    });
    </script>
</head>
<body>
<form id="frm" action="foo">
    <input type="text" id="txt" />
    <input type="submit" id="sub" value="do eet" />
</form>

Upvotes: 3

David
David

Reputation: 219117

Using jQuery it might look something like this:

$('#inputAccount').change(function () {
    $('#myForm').attr('action', 'http://www.example.com/account/' + $('#inputAccount').val());
});

This should change the action of the form any time the text in the input element changes. You could also use .blur() instead of .change() to perform the action whenever focus leaves the input element, so it doesn't keep changing all the time, etc. Then, when the form is submitted, it should submit to whatever was last placed in its action attribute.

Upvotes: 11

Related Questions