Reputation: 3154
I have an HTML form containing a table presenting (among others) two columns with a checkbox and an input text field. The user first checks the checkbox, then modifies the value in the input text field. Before submitting this form I would like to validate the user inputs.
I implemented this validation function:
<script type="text/javascript" charset="utf-8">
var error = false;
$('#form-id').submit(function (event) {
var pattern = /^[0-9]+$/;
alert(pattern); // 1st
var error = false;
$('#form-id input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
if(sThisVal === 'on') {
var field = $(this).closest('td').siblings()
.find("input[type=text]")[0];
var value = field.value;
alert(value); // 2nd
var ok = pattern.test(value);
alert(ok); // 3rd
if( ! ok) {
error = true;
field.addClass('red-border');
} // if on ok
} // if checked
}); // foreach checkbox
return ! error;
});
Everything is ok till the 3rd alert. Then it fails on addClass
with this message:
TypeError: 'undefined' is not a function
(evaluating 'field.addClass('red-border')')
So field is undefined
but it was ok when I read its value.
I am not expert at all in Javascript or JQuery but after reading the docs I cannot understand why this happens.
Upvotes: 0
Views: 114
Reputation: 55210
Change these lines
var field = $(this).closest('td')
.siblings()
.find("input[type=text]");//jQuery object
var value = field[0].value; // field[0] is a native HTML element
The error was that you tried to addClass
, a jQuery method, to a native HTML element
See this fiddle for explanation: http://jsfiddle.net/codovations/tH5xc/
Upvotes: 2
Reputation: 146
It is not a jquery object try:
if(!ok) {
error = true;
field[0].addClass('red-border');
}
instead of:
if( ! ok) {
error = true;
field.addClass('red-border');
}
Upvotes: 0
Reputation: 85545
if( ! ok) {
should be if( !ok) {
without space!
And also,
return ! error;
should be return error = !error;
Upvotes: 2