简体   繁体   中英

jquery- check if fields on form are not empty

I have a couple of select elements and input fields....I can do a series of if statements to check, but I was curious if there was a master function that looks at the DOM and sees if there are values in data elements?

Thanks

<!DOCTYPE html>
<html>
<head>
  <style>

  td { text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <table border="1">
    <tr><td>TD #0</td><td></td></tr>
    <tr><td>TD #2</td><td></td></tr>

    <tr><td></td><td>TD#5</td></tr>
  </table>
<script>$("td:empty").text("empty!").css('background', 'rgb(255,220,200)');</script>

</body>
</html>

btw you can simply use required attributes of the form elements

example <input type="text" required="required">

You can add a class called required_check and iterate through them with jquery

// target the proper elements and loop through them
$('.required_check').each(function(){

    //check the value of currently targeted element
    if($(this).val() == ''){

        // run code if field is empty
        alert($(this).attr('name')+' cannot be empty!');
    }
});

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