Dynamically changing form action URL has no effect
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 na开发者_如何学JAVAme="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.
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();
}
精彩评论