728x90


I am trying to find the number of rows that match a specific pattern. In this example, all that START with "123":

This is working:

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);

The problem is the LIKE will vary, so I'm trying to define it in the script, then execute the query, but this is NOT working:

$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);

How can I get this query to work properly in the second example?

EDIT: I've also tried it without the period (also not working):

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");
shareimprove this question
   
John, something that I have found helps me when using variables in strings, is to use the curly braces. $var1 = "foo"; $var2 = "{$var1} bar"; echo $bar2; Will output: foo bar and you don't have to worry about concatenation, etc etc. Doesn't work as you may think with single quotes for strings, however. – Blake Apr 13 '12 at 0:10 

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

shareimprove this answer
   
Fantastic. Thank you so much! – JROB Apr 12 '12 at 23:56
2 
There is a danger of injection if you are using any user-inputted data. There is zero danger for: $var = "rawr"; ... query("SELECT * FROM table WHERE col='{$var}'"; You are controlling your own data on-server. – Blake Apr 13 '12 at 0:06 
   
@Blake: Obviously, but I feel obliged to say it anyway. Code has a way of being adapted to contexts other than the one it was meant for. – Jon Apr 13 '12 at 0:14
   
@Jon, Surely. However, you have to specify that queries can be vulnerable to injections... with user-inputted data. There's a difference between saying "Look at that house" and "Look at that house on fire." :) – Blake Apr 13 '12 at 1:38
   
ertertg ertferf – user609306 Mar 8 '14 at 17:58 


'WEB' 카테고리의 다른 글

How to set clearfix and define  (0) 2018.01.24
[PHP] swtich  (0) 2018.01.23
explode  (0) 2018.01.22
[PHP] mysqli::num_rows  (0) 2018.01.14
[PHP] filter_var function vs number_format  (0) 2018.01.14
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


+ Recent posts