Erwin van Ekeren
Erwin van Ekeren

Reputation: 730

show div when all input fields have content

I have a form with a few input fields, I only want to show a div when all the input fields got content, when one of the input fields has no content the div should disappear again.

I made it work with one input field, but how do I get it to work when all the input fields are filled in (don't know if its a good clean way?):

$(function () {    
$('input').change(function() {
$('.next').toggle($(this).val().length !== 0);
}); });

Fiddle:
http://jsfiddle.net/uQyH9/19/

Upvotes: 2

Views: 1561

Answers (3)

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use a filter function to check that all the input are filled.

Code:

    $(function () {
        $('input').change(function () {
            $('.next').toggle($("input").filter(function () {
                return this.value === "";
            }).length === 0)
        });
    });

Demo: http://jsfiddle.net/IrvinDominin/DwF2P/

UPDATE

You can check the value of the elements by type by cheking type attribute.

Code:

$(function () {
    $('input').change(function () {
        $('.next').toggle($("input").filter(function () {
            var myType=$(this).attr("type");
            if (myType === "checkbox") return !$(this).is(":checked");
            if (myType==="radio"){
                var myName = $(this).attr("name");
                if (myName==="") return !$(this).is(":checked");
                return $('input[name='+ myName +']:checked').length===0
            }
            return this.value === "";
        }).length === 0)
    });
});

Demo: http://jsfiddle.net/IrvinDominin/pqJhg/

Upvotes: 1

Barmar
Barmar

Reputation: 782785

Loop over the inputs. If you find one that isn't filled in, then hide the DIV. If you don't, show the DIV.

$('input').change(function() {
    var allFilled = true;
    $('input').each(function() {
        if (this.value === '') {
            allFilled = false;
            return false; // Terminate the loop
        }
    }
    $('.next').toggle(allFilled);
});

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148744

Try this : http://jsfiddle.net/uQyH9/21/

$(function () {   
    var _cached=$('input');

    _cached.change(function() {
        if (_cached.filter(function (){return $(this).val().length }).length==_cached.length)
        $('.next').show();
         else
        $('.next').hide();

    });
});

Upvotes: 2

Related Questions