简体   繁体   中英

How to count the number of selected elements?

I have a lot of elements which are used identical class-name. Now I need to calculate the number of selected items.

For eg something like this: (however this example doesn't work correctly)

 $("#btn").click(function(){ if($(".necessarily").val() == ''){ $(".necessarily").css('border','1px solid red'); } // also I want the number of input.necessarily which are empty }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <form name="frm" action="#"> <input name="first-name" class="necessarily" type="text" /><br><br> <input name="last-name" class="necessarily" type="text" /><br><br> <input name="email" class="necessarily" type="email" /><br><br> <input name="password" class="necessarily" type="password" /><br><br> <input name="address" class="anything" type="text" /><br><br> <input name="btn" id="btn" type="submit" value="Register" /> </form> 

Now I want the number of those inputs which are empty ..., How can I calculate that?

.val() method returns .value property of the first element in the collection. You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection:

var $empty = $(".necessarily").filter(function() {
   // you can use the `$.trim` method for trimming whitespaces
   // return $.trim(this.value).length === 0; 
   return this.value.length === 0;
});

if ( $empty.length > 0 ) {

}

If you want to add a border to the empty fields you can declare a CSS class and use the .removeClass and .addClass methods:

CSS:

.red_border {
   border: 1px solid red;
}

JavaScript:

var $empty = $(".necessarily").removeClass('red_border').filter(function() {
   return this.value.length === 0;
}).addClass('red_border');

You'd do better looking at the HTML5 Contraint API rather than doing what you're currently doing, which is a more manual and time-consuming way.

Instead of giving each field a class 'necessarily' (sidenote: the word you need is 'necessary', not 'necessarily', or, better still, 'required') use the required attribute. So:

<input name="last-name" required type="text" />

Then in your jQuery you can target empty fields with:

$('input:invalid').css('border', 'solid 1px red');

If all you're doing is highlighting bad fields, you don't even need JavaScript for this. You can do the same thing via CSS:

input:invalid { border: solid 1px red; }

The only problem with that is the styling will be showed even before the user has filled out the form, which is almost never desirable. You could get round this by logging, via JS, when the form is submitted, and only then activating the styles:

JS:

$('form').on('submit', function() { $(this).addClass('show-errors'); });

CSS:

.show-errors input:invalid { border: solid 1px red; }

You need to:

  1. query all elements by className
  2. filter the jQuery Collection in order to keep only the elements that have no value
  3. doSomethingElse

so, this maybe could help you:

 function CheckEmptyCtrl($) { 'use strict'; var self = this; self.target = $('.necessarily'); self.empty = self.target.filter(function(index, item) { return !($(item).val().trim()); }); $('#result').append(self.empty.length + ' elements have no values.'); console.log(self.empty.length, self.empty); } jQuery(document).ready(CheckEmptyCtrl); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <div id="result"></div> <form name="frm" action="#"> <input name="first-name" class="necessarily" type="text" value="notEmpty" /><br><br> <input name="last-name" class="necessarily" type="text" /><br><br> <input name="email" class="necessarily" type="email" /><br><br> <input name="password" class="necessarily" type="password" /><br><br> <input name="address" class="anything" type="text" /><br><br> <input name="btn" id="btn" type="submit" value="Register" /> </form> 

Try this code:

$("#btn").click(function(){
     var selectedcount = $(".necessarily").length; //no. of elements with necessarily class name
     var emptyInputCount=0;
      $(".necessarily").each(function(){
      if($(this).val() == ''){
        emptyInputCount++;
      }

    });

Try with each loop on the target elements.

 $(function() { $("#btn").click(function() { var i = 0; $(".necessarily").each(function() { if ($(this).val() == "") { $(this).css('border', '1px solid red'); i++; } }); alert(i); //Number of input element with no value }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <form name="frm" action="#"> <input name="first-name" class="necessarily" type="text" /> <br> <br> <input name="last-name" class="necessarily" type="text" /> <br> <br> <input name="email" class="necessarily" type="email" /> <br> <br> <input name="password" class="necessarily" type="password" /> <br> <br> <input name="address" class="anything" type="text" /> <br> <br> <input name="btn" id="btn" type="submit" value="Register" /> </form> 

Hope this helps!

You can use filter() like following example bellow.

var empty_inputs = $('.necessarily').filter(function(){
    return $(this).val()=='';
});

empty_inputs.length will return 3 in my example.

Hope this helps.


 var empty_inputs = $('.necessarily').filter(function(){ return $(this).val()==''; }); console.log(empty_inputs.length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="first-name" class="necessarily" type="text" /><br><br> <input name="last-name" class="necessarily" type="text" /><br><br> <input name="email" class="necessarily" type="email" value="Register"/><br><br> <input name="password" class="necessarily" type="password" /><br><br> <input name="address" class="anything" type="text" value="Register"/><br><br> <input name="btn" id="btn" type="submit" value="Register" /> 

Hope this helps.

You need to loop over the all of the inputs and count how many are empty. In the same loop you can also count the number of .necessarily inputs which are empty.

This example will output the result to the .result span.

 $("#btn").click(function() { var inputs = $("form input"); var emptyNecessarilyCount = 0; var totalEmpty = 0 inputs.each(function() { if ($(this).val() == "") { totalEmpty++; if ($(this).hasClass('necessarily')) { emptyNecessarilyCount++; } } }); $('.result').append("Total: " + totalEmpty); $('.result2').append("Necessarily: " + emptyNecessarilyCount); }); 
 span { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="frm" action="#"> <input name="first-name" class="necessarily" type="text" /> <br> <input name="last-name" class="necessarily" type="text" /> <br> <input name="email" class="necessarily" type="email" /> <br> <input name="password" class="necessarily" type="password" /> <br> <input name="address" class="anything" type="text" /> <br> <input name="btn" id="btn" type="submit" value="Register" /> <span class="result"></span> <span class="result2"></span> </form> 

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