0

Trying to debug something that basically .trim()'s, .val()'s and .length's a textarea input as HTML below (truncated):

<form id="Kontaktanfrage" method="post" action="tests/testform/">
...
<textarea cols="50" rows="8" id="el_12" name="FORM[Kontaktanfrage][el_12]" title="Ihre Nachricht: *" class="textarea required"></textarea>
...
</form>

JavaScript:

function validateField(formId, fieldId) {
if (fieldId) {
    var element = "form#"+formId+" input#"+fieldId;
    var fieldValue = jQuery.trim(jQuery(element).val());
    var fieldLength = fieldValue.length;
    var fieldError = "";
    if ($(element).is('.textarea.required') && fieldLength == 0) {
        fieldError = "error message";
    }
}

}

The above if check is never true.

Using JQuery: 1.4.1.

Having seen other examples online, I can't see what the difference should be. Feel free to test it in FireBug at (http://www.initiat.de/tests/testform/). Any help appreciated, can't see what I'm doing wrong.

3 Answers 3

1

You're creating your selector assuming that all of your fields are Input elements. TextArea is a different element and your selector should reflect that. I don't think that performance will take a big hit if you change this line

var element = "form#"+formId+" input#"+fieldId;

to this

var element = "form#"+formId+" #"+fieldId;

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ben, I forgot all about textarea not technically being of type 'input', it's one of my biggest annoyances in HTML. Thanks for spotting it :)
1

Why not use

.hasClass()

2 Comments

I need to check 2 classes, hasClass() only checks 2 if it in a literal order, not in any order. I need the flexibility
You could always go element.hasClass(class1) && element.hasClass(class2)
0

Try with

if ($(element).hasClass('textarea') && $(element).hasClass('required') && fieldLength == 0) {
        fieldError = "error message";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.