Muhammad Hassan Muhammad Hassan - 7 months ago 10
Javascript Question

this.form Is Not Passing Form In A JavaScript Function

I have too many Form on my single web page with having different names of each and every form. Now I have a button in every form that is getting that form with a fixed parameter and passing it to a JavaScript function. But in my case its not working and giving me the error that

Uncaught TypeError: Cannot read property 'name' of undefined
or `Uncaught ReferenceError: updateContact is not defined. My script file is attached before these forms and also after these forms for checking purpose. You can see a live DEMO At JSFiddle having this error.

JavaScript:



<script type="text/JavaScript">
function updateContact(formName, id){
var currentFormName = formName.name;
alert(currentFormName + " - " + id);
}
</script>


HTML:



<form method="post" action="" name="updateAllContact0">
<a onClick="updateContact(this.form, 0)" >Update</a>
</form>
<form method="post" action="" name="updateAllContact1">
<a onClick="updateContact(this.form, 1)" >Update</a>
</form>
<form method="post" action="" name="updateAllContact2">
<a onClick="updateContact(this.form, 2)" >Update</a>
</form>
<form method="post" action="" name="updateAllContact3">
<a onClick="updateContact(this.form, 3)" >Update</a>
</form>
<form method="post" action="" name="updateAllContact4">
<a onClick="updateContact(this.form, 4)" >Update</a>
</form>
<form method="post" action="" name="updateAllContact5">
<a onClick="updateContact(this.form, 5)" >Update</a>
</form>
<!--
.
// Too Many Forms Of Unknown Length
.
<form method="post" action="" name="updateAllContactN">
<a onClick="updateContact(this.form, N)" >Update</a>
</form>
-->


NOw whats the problem I have in my code...???

Answer

Try substituting this.parentElement.form for this.form. <a> element does not have form child node. <form> is .parentElement of <a> element.