admin管理员组

文章数量:1323723

When a form action URL was changed dynamically, when the form submit, it will still use the default action URL, anybody know why? Please see a simple example below:

<form action="test.php" method="get" id="test">
  <select name="id" onChange="formSubmit(this)">
    <option value="abc">abc</option>
    <option value="xyz">xyz</option>
  </select>
</form>

<script type="text/javascript">
function formSubmit(element){
  var url = $("#test").attr("action", url);
  var newParam = "&new=123";

  url += "?" + element.name + "=" + element.value + newParam;
  //e.g. formurl now = 'test.php?id=xyz&new=123';

  $("#test").attr("action", url);
  $("#test").submit();//the form will submit to test.php?id=xyz instead of the new URL
}
</script>

Thx.

When a form action URL was changed dynamically, when the form submit, it will still use the default action URL, anybody know why? Please see a simple example below:

<form action="test.php" method="get" id="test">
  <select name="id" onChange="formSubmit(this)">
    <option value="abc">abc</option>
    <option value="xyz">xyz</option>
  </select>
</form>

<script type="text/javascript">
function formSubmit(element){
  var url = $("#test").attr("action", url);
  var newParam = "&new=123";

  url += "?" + element.name + "=" + element.value + newParam;
  //e.g. formurl now = 'test.php?id=xyz&new=123';

  $("#test").attr("action", url);
  $("#test").submit();//the form will submit to test.php?id=xyz instead of the new URL
}
</script>

Thx.

Share Improve this question asked Sep 11, 2010 at 6:04 franfranfranfran 3,1752 gold badges20 silver badges11 bronze badges 1
  • 1 Any reason why you'd want to do that instead of inserting values into hidden fields? – NullUserException Commented Sep 11, 2010 at 6:09
Add a ment  | 

1 Answer 1

Reset to default 6

You are assigning empty value to url variable initially on the first line:

var url = $("#test").attr("action", url);

It should be:

var url = $("#test").attr("action");

You also need to get form element with get or [0] shorthand:

$("#test")[0].submit();

This is how your function should look:

function formSubmit(element){
  var url = $("#test").attr("action");
  var newParam = "&new=123";
  url += "?" + element.name + "=" + element.value + newParam;
  $("#test").attr("action", url);
  $("#test")[0].submit();
}

本文标签: javascriptDynamically changing form action URL has no effectStack Overflow