I'm trying to create a form and submit it immediately with javascript and I cannot figure out what I'm doing wrong. here is my code:
function autoLogIn(un, pw) { var form = document.createElement("form"); document.body.appendChild(form); form.method = "POST"; form.action = "login.php"; var element1 = document.createElement("<INPUT NAME='un' TYPE='hidden' VALUE='"+un+"'>"); form.appendChild(element1); var element2 = document.createElement("<INPUT NAME='pw' TYPE='hidden' VALUE='"+pw+"'>"); form.appendChild(element2); form.submit(); }
The JavaScript form submission can be used for object creation and various attributes can also be used. The attributes can be class, id, tag, etc. Calling by attributes is quite simple, we just need to place the symbols properly.
Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.
When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method. Example: Create a form and submit it using the above approach.
The problem is that createElement does not accept HTML. It accepts a tagname and returns a DOM element. You can then set the value attribute on this element to what you require.
function autoLogIn(un, pw) { var form = document.createElement("form"); var element1 = document.createElement("input"); var element2 = document.createElement("input"); form.method = "POST"; form.action = "login.php"; element1.value=un; element1.name="un"; form.appendChild(element1); element2.value=pw; element2.name="pw"; form.appendChild(element2); document.body.appendChild(form); form.submit(); }
Modified code: jsfiddle.
function autoLogIn(un, pw) { var form = document.createElement("form"); document.body.appendChild(form); form.method = "POST"; form.action = "login.php"; var element1 = document.createElement("INPUT"); element1.name="un" element1.value = un; element1.type = 'hidden' form.appendChild(element1); var element2 = document.createElement("INPUT"); element2.name="pw" element2.value = pw; element2.type = 'hidden' form.appendChild(element2); form.submit(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With