简体   繁体   中英

Check if all children input fields have a value

I want to check if all input-fields of the same row have a value after changing a input:

HTML

<tr>
    <td><input type="text"></td>
    <td><input type="text"></td>
    <td><input type="text"></td>
</tr>

JS

$(this).find('input').each (function() {

});

So if all input fields have a value I want to send true, otherwise false.

Something like this maybe?

var valid = true;
$(this).find('input').each (function() {
  if ($(this).value().length == 0) {
    valid = false;
  }
});

Will that work?

EDIT

Heres a fiddle with my code and how it works; https://jsfiddle.net/3748str4/ - note that the event is on 'change' which means you need to click OUT of the field to fire the event.

You can do that like so:

var nInputs = $('input', this).length,
    nVals   = $('input', this).filter(function() {
        return !!this.value.trim();
    }).length;
if( nVals === nInputs ) {
    //all inputs have values;
}

 $(function() { $('#check').on('click', function() { $('tr').each(function(i,v) { console.log( 'Row ' + i ); var inputs = $('input', this), nVals = inputs.filter(function() { return !!this.value.trim(); }).length; if( nVals === inputs.length ) { console.log( 'All inputs have values' ); } else { console.log( nVals + '/' + inputs.length + ' have values' ); } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> <tr> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> <tr> <td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td> </tr> </table> <button id="check">Check</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM