开发者

HTML form with dynamic action (using JavaScript?)

I want to create a form like this:

  1. Type in your ID number into the fo开发者_C百科rm'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?


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.


<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>


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜