How to only validate fields that are visible?

Asked

Viewed 624 times

2

I have a form with several fields(inputs, selects), but some are like display: block and others as display:none; as I put the validation at all when I submit the form wanted it to check only those that are visible on the screen and not all.

  • 2

    You can use the :visible jQuery but it would be interesting to question (and answer) if you put the code you have for the answer to be more complete.

1 answer

1


Option 1 - Pure Javascript

I created the following function, which takes into account display: none and visibility: hidden:

function estaVisivel(elm){
    var estaVisivel = (elm.offsetWidth > 0 && elm.offsetHeight > 0) && // display: none
    window.getComputedStyle(elm,null).getPropertyValue("visibility") != "hidden"; 

    return estaVisivel;    
}

Some Tests:

var form = document.getElementById("form");
for (var i = 0; i < form.elements.length; i++) {
    var elm = form.elements[i];
    var visible = estaVisivel(elm);
    log("<br />Elemento: " + elm.id + " visible = " + visible);
}

 function estaVisivel(elm){
        var estaVisivel = (elm.offsetWidth > 0 && elm.offsetHeight > 0) && // display: none
        window.getComputedStyle(elm,null).getPropertyValue("visibility") != "hidden"; 
 
        return estaVisivel;    
    }

function log(text){
    document.getElementById("resultado").innerHTML += text;
}
.hidden {
    visibility: hidden;
}

.display-none {
    display: none;
}
<form id="form">      
    <input id="b" type="text" class="hidden" /><br />
    <select id="c" class="hidden"><option>1</option></select><br />
    <textarea id="d" class="hidden"></textarea><br />
       
    <input id="b1" type="text" class="display-none" /><br />
    <select id="c1" class="display-none"><option>1</option></select><br />
    <textarea id="d1" class="display-none"></textarea><br />
        
    <input id="b2" type="text" /><br />
    <select id="c2"><option>1</option></select><br />
    <textarea id="d2"></textarea><br />
</form>

<div id="resultado"></div>

Option 2 - jQuery

Simply use the pseudo selector :visible:

if($("#elemento").is(":visible"))
    // validação

Browser other questions tagged

You are not signed in. Login or sign up in order to post.