Q:

Using javascript to update html css code on validation

I have a form in my html and below is one of its components or fields.
<div class="form-group">
    <div class="input-group">
        <span class="input-group-addon"><i class="zmdi zmdi-lock"></i></span>
        <div id="form_field" class="fg-line">
            <input name="pas" type="password" class="form-control" placeholder="Password">
        </div>
    </div>
</div>

I need to add has-error to class fg-line if the input field is blank.
I tried that using the code below apparently it only adds to the first form-field it encounters which its understandable but what I don't know is how to get it to only apply has-error to the  input field which is empty.
function validateForm() {
    var isValid = true;
    $('.form-control').each(function () {
        if ($(this).val() === '') {
            isValid = false;

            $("#form_field").removeClass("fg-line").addClass("fg-line has-error");
        }
    });
    return isValid;
}

A:

In your structure, does the input you're testing always come as a direct child as the div you're looking to modify? You can grab the current element in the loop's parent by doing $(this).parent() as seen here:
function validateForm() {
    var isValid = true;
    $('.form-control').each(function () {
        if ($(this).val() === '') {
            isValid = false;

            //Add has-error class to the parent div
            $(this).parent().addClass("has-error");
        }
    });
    return isValid;
}

Otherwise, you can use .closest() which will traverse upwards along the DOM tree and find the first matching occurrence of the specified selector.
function validateForm() {
    var isValid = true;
    $('.form-control').each(function () {
        if ($(this).val() === '') {
            isValid = false;

            //Add has-error class to the closest occurrence of class fg-line
            $(this).closest('.fg-line').addClass("has-error");
        }
    });
    return isValid;
}

