简体   繁体   English

如何计算所选元素的数量?

[英]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. .val()方法返回集合中第一个元素的.value属性。 You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection: 您可以使用.filter()方法过滤空输入,并读取已过滤集合的.length属性:

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类并使用.removeClass.addClass方法:

CSS: CSS:

.red_border {
   border: 1px solid red;
}

JavaScript: 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. 您可以更好地查看HTML5 Contraint API,而不是执行您当前正在执行的操作,这是一种更加手动且耗时的方式。

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. 而不是给每个字段一个“必然”的类(旁注:你需要的词是'必要',而不是'必然',或者更好,'必需')使用required属性。 So: 所以:

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

Then in your jQuery you can target empty fields with: 然后在您的jQuery中,您可以使用以下命令来定位空字段

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

If all you're doing is highlighting bad fields, you don't even need JavaScript for this. 如果您所做的只是突出显示坏字段,那么您甚至不需要JavaScript You can do the same thing via CSS: 你可以通过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,当提交表单时, 才把激活方式:

JS: JS:

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

CSS: CSS:

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

You need to: 你需要:

  1. query all elements by className 按className查询所有元素
  2. filter the jQuery Collection in order to keep only the elements that have no value 过滤jQuery Collection,以便只保留没有值的元素
  3. doSomethingElse 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. 尝试使用目标元素上的each循环。

 $(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. 您可以使用filter()例如以下示例。

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

empty_inputs.length will return 3 in my example. empty_inputs.length将在我的示例中返回3。

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. 在同一个循环中,您还可以计算空的.necessarily输入数。

This example will output the result to the .result span. 此示例将结果输出到.result范围。

 $("#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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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