最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTML form with dynamic action (using JavaScript?) - Stack Overflow

programmeradmin7浏览0评论

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 bees something like /account/{id}/.

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

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 bees something like /account/{id}/.

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

Share Improve this question edited May 23, 2017 at 11:44 CommunityBot 11 silver badge asked Feb 8, 2011 at 21:05 HerpHerp 531 gold badge1 silver badge4 bronze badges 3
  • i think you are looking to do a GET request like account.php?id=33 ? – KJYe.Name Commented Feb 8, 2011 at 21:08
  • No, I'm looking to do a POST request like account/33 – Herp Commented Feb 8, 2011 at 21:09
  • 4 just because you mentioned w3schools: w3fools. – Hamish Commented Feb 8, 2011 at 21:09
Add a ment  | 

3 Answers 3

Reset to default 11

Using jQuery it might look something like this:

$('#inputAccount').change(function () {
    $('#myForm').attr('action', 'http://www.example./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./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)

  1. 暂无评论