0

I'm having trouble with returning the appropriate responses. It sort of works like, on validation parentAnswer is ran, strips the name to reveil the parent name Answer[12]. Now if the value of this is 'yes' then I want to return that this is required if something isn't already inputted.

Was hoping there is some already in built way for the plugin to check if it's already filled out, instead of having to write messy code to do it.

<select class="input-small" name="Answers[12]">
    <option value="no">No</option>
    <option value="yes">Yes</option>
</select>    
<textarea class="parentAnswer" rows="5" cols="107" name="Answers[12a]"></textarea>

Method

jQuery.validator.addMethod("parentAnswer", function(value, element) {
    var parentElement = element.name.replace(/(.*)\[(\d*).*\]/, "$1[$2]");
    var parentValue = $('select[name="'+parentElement+'"]').val();
    if(parentValue === 'yes'){
        return this.optional(element) || (parseFloat(value) > 0);
        //^ this is the line in question
    } else {
        return true;
    }
}, jQuery.format("Could you supply more details"));

1 Answer 1

1

Inspecting your parseFloat(value) with the console log, you will see that it always returns NaN unless your textarea contains some numbers. I don't think that's what you wanted.

Try this simpler logic instead:

jQuery.validator.addMethod("parentAnswer", function (value, element) {
    var parentElement = element.name.replace(/(.*)\[(\d*).*\]/, "$1[$2]");
    var parentValue = $('select[name="' + parentElement + '"]').val();
    return !(parentValue === 'yes' && $(element).val() === '');
}, jQuery.format("Could you supply more details"));

Working DEMO: http://jsfiddle.net/6LGFy/

BTW: jQuery Validate very much likes for you to have a name attribute on all input fields as well. Your textarea was missing this attribute.


EDIT:

Alternatively, you might be able to use the depends sub-option instead of a custom method. It's much simpler this way, but you may or may not need to tweak the selector below.

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            answer: {
                required: {
                    depends: function(element) {
                        return $("select[name^='Answers'] option[value='yes']").is(":selected");
                    }
                }
            }
        },
        messages: {
            answer: {
                required: "Could you supply more details"
            }
        }
    });

});

DEMO: http://jsfiddle.net/UyMZ3/

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

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.