728x90


I have tons of checkboxes that are either checked (checked="checked") or unchecked.

I would like to get the number of all checkboxes, unchecked and checked checkboxes.

With check-box I mean <input type="checkbox" />.

How to do it with jQuery? Thanks in advance!

shareimprove this question
up vote114down voteaccepted

You could do:

var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;

EDIT

Or even simple

var numberNotChecked = $('input:checkbox:not(":checked")').length;
shareimprove this answer

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;
shareimprove this answer

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);
shareimprove this answer

Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.

You can do that by giving a class to the first checkbox

For example class='mycxk' and you can count that using the filter, like this

$('.mycxk').filter(':checked').length


728x90


I have several checkboxes with a name array and I want the output of the checked boxes to be a variable with a comma separated list.

<input type="checkbox" name="example[]" value="288" />
<input type="checkbox" name="example[]" value="289" />
<input type="checkbox" name="example[]" value="290" />

For example if the first and last box are selected the output will be:

var output = "288,290";

How can I do this with jQuery?

shareimprove this question

You can use :checkbox and name attribute selector (:checkbox[name=example\\[\\]]) to get the list of checkbox with name="example[]" and then you can use :checked filter to get only the selected checkbox.

Then you can use .map function to create an array out of the selected checkbox.

DEMO

var output = $.map($(':checkbox[name=example\\[\\]]:checked'), function(n, i){
      return n.value;
}).join(',');
shareimprove this answer
   
Hmmm, this seems to return a list of all (checked) checkboxes even with those without the name of example[]. e.g. jsfiddle.net/6LCvN . Any idea why? – Hugh Apr 10 '13 at 3:40 
   
@Hugh Missed it somehow, but you need double slashes to escape the [ and ] jsfiddle.net/6LCvN/22 or wrap in quotes jsfiddle.net/hmtdtwbr – Selvakumar Arumugam Nov 25 '14 at 20:47 

Currently un-tested, but I believe the following should work:

var valuesArray = $('input:checkbox:checked').map( function () {
    return $(this).val();
}).get().join();

Edited, after a small break, to use native DOM, rather than $(this).val() (which is needlessly expensive, in context):

var valuesArray = $('input:checkbox:checked').map( function() {
    return this.value;
}).get().join(",");
shareimprove this answer
var valuesArray = $('input[name="valuehere"]:checked').map(function () {  
        return this.value;
        }).get().join(",");

works for me always

shareimprove this answer


728x90


I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible?

I would like something like the following pseudocode:

$(function() {
  $('#contentDiv').isvisible(function() {
    alert("do something");
  });
});

The alert("do something") code should not fire until the contentDiv is actually made visible.

Thanks.

shareimprove this question
up vote167down voteaccepted

You could always add to the original .show() method so you don't have to trigger events every time you show something or if you need it to work with legacy code:

Jquery extension:

jQuery(function($) {

  var _oldShow = $.fn.show;

  $.fn.show = function(speed, oldCallback) {
    return $(this).each(function() {
      var obj         = $(this),
          newCallback = function() {
            if ($.isFunction(oldCallback)) {
              oldCallback.apply(obj);
            }
            obj.trigger('afterShow');
          };

      // you can trigger a before show if you want
      obj.trigger('beforeShow');

      // now use the old function to show the element passing the new callback
      _oldShow.apply(obj, [speed, newCallback]);
    });
  }
});

Usage example:

jQuery(function($) {
  $('#test')
    .bind('beforeShow', function() {
      alert('beforeShow');
    }) 
    .bind('afterShow', function() {
      alert('afterShow');
    })
    .show(1000, function() {
      alert('in show callback');
    })
    .show();
});

This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.

You could also create another method so you don't have to override the original .show() method.

shareimprove this answer
5 
EDIT: There is only one downside with this method: You will have to repeat the same "extension" for all methods that reveal the element: show(), slideDown() etc. Something more universal is required to solve this problem for once and all, since its impossible to have "ready" event for delegate() or live(). – Shahriyar Imanov Feb 24 '11 at 17:59
   
Good, the only problem is that fadeTo function does not work properly after implementing this function – Omid Nov 11 '11 at 10:56
8 
Your code does not appear to work with the latest jQuery (1.7.1 at the date of this comment). I have reworked this solution slightly to work with the latest jQuery: stackoverflow.com/a/9422207/135968 – mkmurray Feb 23 '12 at 22:15
2 
Thanks mkmurray. It at least worked for a few years! – Tres Aug 15 '13 at 1:37
   
Can't get that code to work with div visibility triggered by an ajax response. – JackTheKnife Oct 7 '16 at 14:39


728x90

숫자형식의 값을 화면에 보여줄때에는 화폐단위처럼 숫자 3자리마다 콤마(comma)를 추가해주면 가독성이 좋아진다.

프로그래밍 언어별로 이러한것을 처리하기 위해 숫자를 특정 형식대로 포맷팅 해줄수가 있는데, 자바스크립트는 그러한 기능이 없다. 물론 우리들이 흔하게 사용하년 jQuery에도 그러한 기능은 없다. (jQuery는 숫자형식을 컨트롤 하는 플러그인이 있다)

그렇기 때문에 숫자를 화페단위처럼 3자리마다 콤마를 넣어주긴 위해선 해당 기능을 하는 함수를 만들어서 사용해야 한다.

일반적으로 인터넷에서 검색했을때 제일 많이 나오는 함수는 아래와 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function comma(num){
    var len, point, str; 
       
    num = num + ""
    point = num.length % 3 ;
    len = num.length; 
   
    str = num.substring(0, point); 
    while (point < len) { 
        if (str != "") str += ","
        str += num.substring(point, point + 3); 
        point += 3; 
    
     
    return str;
 
}



위의 함수의 경우 나와 같이 일을 하는 막내직원이 어디선가 긁어와서 사용중인 함수인데, 위와 같이 while문을 통해
자릿수마다 콤마를 추가하고 있다. 

위 방법보다는 공백제거 함수처럼 정규식을 사용할수 있지 않을까 해서 검색해보니 stackoverflow에 떡하니 있다 !!

1
2
3
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}



심플하다 !!

참고 : http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript



출처: http://fruitdev.tistory.com/160 [과일가게 개발자]

'WEB > jQuery' 카테고리의 다른 글

jQuery checkbox values to comma separated list  (0) 2018.01.22
jQuery event to trigger action when a div is made visible  (0) 2018.01.22
jQuery Change Image src with Fade Effect  (0) 2018.01.14
jQuery change() Method  (0) 2018.01.14
PHP array_push  (0) 2018.01.14

+ Recent posts