Reputation: 671
I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!
Upvotes: 0
Views: 104
Reputation: 360592
A name
attribute on an HTML element is NOT the same as an id
. You have no id on your input field, so there's no way for getElementById
to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this
Upvotes: 2
Reputation: 114347
document.getElementById
looks for elements by ID. Your field doesn't have an ID, it has a NAME.
Upvotes: 4
Reputation: 348972
document.getElementById
selects an element by id
, not by name
.
Some ways to solve the problem:
id="requestorfirstname"
to the input element.document.getElementsByName('requestorfirstname')[0]
. getElementsByName
returns a list, hence [0]
.document.querySelector('[name="requestorfirstname"]')
method.Get a reference to the form, and access the element using the .elements
collection.
For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']
Upvotes: 2