Get input fields with a value inside a div using .closest

时间:2018-09-18 19:52:53

标签: jquery

I'm using JQuery to get the closest div with a specific class and creating a variable:

var box = $(this).closest('.box');

How can i then get all inputs with a class of required inside this variable div?

I've tried this:

    var errors = false;
    $(box + " input .required").each(function() {
        console.log($(this).val());
        if($(this).val() === "") {
            errors = true;

            $(this).parent().find('label').css("color", "#f36f25");
            $(this).parent().find('label').css("font-weight", "bold");
        }
    });

but get an error in the console saying Uncaught Error: Syntax error, unrecognized expression: [object Object] input .required

1 个答案:

答案 0 :(得分:3)

Given the code

var box = $(this).closest('.box'); 

and

$(box + " input .required").each(function() {

then that means the line $(box + " input .required").each(function() { actually reads like

$($(this).closest('.box')+ " input .required").each(function() {

which is syntactically invalid. You are trying to append a jquery selection object with a string, all within another jquery selector. That just doesn't work.

You want to do box.find("input.required").each(....

Resulting code looks like this:

var box = $(this).closest('.box');

var errors = false;
box.find("input.required").each(function() {
    console.log($(this).val());
    if($(this).val() === "") {
        errors = true;

        $(this).parent().find('label').css("color", "#f36f25");
        $(this).parent().find('label').css("font-weight", "bold");
    }
});
相关问题