Reputation: 3361
I have following code to submit a form
<form class="sh-form" onsubmit="validateCmntForm(this);">
and when I try to get field value from submitted form with following code it return f.getElementById not a function
error
validateCmntForm(f){
let nameField = f.getElementById('sh-cmnt-fullname');
console.log(nameField)
}
What am I doing wrong here ? can someone help me with this ?
Update : reason for passing the form with this in function is that I have multiple same type of forms on page so can not use id with this and have to get field values from submitted form
Upvotes: 3
Views: 50
Reputation: 4480
You could either reference the submit event directly (target
will be an array of the attached children), or you could reference the input by ID if you would prefer. I've included a snippet below demonstrating both.
function validateCmntForm(event) {
event.preventDefault();
console.log(event.target[0].value);
console.log(document.getElementById('sh-cmnt-fullname').value);
}
<form class="sh-form" onsubmit="validateCmntForm(event)">
<input id="sh-cmnt-fullname" type="text" />
<button type="submit">Submit</button>
</form>
Upvotes: 2
Reputation: 1
Use return validatecmntform
function validateCmntForm(oForm){
console.log(oForm.elements["name"].value) // this is how you can get form data
return false;
}
<form class="sh-form" onsubmit="return validateCmntForm(this);">
<input type="text" name="name" id="myname">
<input type="submit" value="submit">
</form>
Upvotes: 1
Reputation: 465
try this
<form onsubmit='return validateCmntForm()' method='post' name='myForm'>
<input type="text" name="eName">
</form>
in script
<script type="text/javascript">
validateCmntForm = function(){
var eName = document.forms['myForm']['eName'].value;
console.log(eName)
}
</script>
Upvotes: 1