Normally form.submit() will work,
but if there's an input named submit,
form.submit will be the very input and you can't submit the form with the above code.
So is there a way to submit the form in this case(if I don't change the input's name)?
You can invoke the submit method from another form and hack this with call or apply.
document.createElement('form').submit.call(myForm);
… but it won't work on IE6.
It is safer to rename the input to something other than submit.
submit() method doesn't try to recover from the input name / default method name conflict.submit, get form's own method, rename input back and call the method the same way. Or is there intrinsic limitation in IE6 on calling DOM element methods with call?I think the word "submit" is a reserved word and can't be used in any input element except the type=submit element.
But there is always a way to break the rules. By using AJAX to perform a POST request, you can use any name you want. And you don't even need a name for the input element, just an id. As a matter of fact, you don't even need a form, just an input element.
<html>
<head>
<script type="text/javascript">
function ajaxRequest()
{
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if(window.ActiveXObject)
{
for(var i=0; i<activexmodes.length; i++)
{
try{return new ActiveXObject(activexmodes[i])}
catch(e){}
}
}
else if(window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function myfunc()
{
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function()
{
if(mypostrequest.readyState==4)
{
if(mypostrequest.status==200 || window.location.href.indexOf("http")==-1)
{
document.getElementById("result").innerHTML=mypostrequest.responseText
}
}
}
var hiddenValue=encodeURIComponent(document.getElementById("submit").value)
var parameters="submit="+hiddenValue
mypostrequest.open("POST", "go2.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
window.onload = myfunc;
</script>
</head>
<body>
<div id="result"></div>
<input type='hidden' id='submit' value='1'>
</body>
</html>
You could just use the .click() function on the submit button. If there is no submit button you would have to insert one into the DOM first though.
Like this:
var submitbutton = document.createElement('input');
submitbutton.type = "submit";
document.getElementById("yourForm").appendChild(submitbutton);
submitbutton.click();
Or, if you have a submit button:
document.getElementById("yourButton").click()