Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery increment number using .each()

how do i increment id using .each() function.

$("input:checked").each(function(){
var counter = $(this).length();
var id_bookslot = data; //<-- increment id +1
var treatment_type = $(this).closest("div").attr("id");
var id_treatment = $(this).attr("class");
$.post("include/get_booking.php?insert", {id_bookslot: id_bookslot,id_treatment:id_treatment,treatment_type:treatment_type});
});

let say, there are 3 checkboxes are checked! so the id will be incrementing until 3(1,2,3).

i forgot to mention var id_bookslot = data. data which is an id that i retreive from database. let say it starts with 1234. and everytime .each() generate, it will increment by 1. 1234, 1235, 1236

like image 324
tonoslfx Avatar asked Feb 27 '26 04:02

tonoslfx


2 Answers

The each() method allows you to use the index of the element. That's likely the best way to accomplish this.

$("input:checked").each(function( index ){
    var id_bookslot = index + 1; //<-- increment id +1
    var treatment_type = $(this).closest("div").attr("id");
    var id_treatment = $(this).attr("class");
    $.post("include/get_booking.php?insert", {id_bookslot: id_bookslot,id_treatment:id_treatment,treatment_type:treatment_type});
});

I added +1 since the index is a 0 index and you seem to want it to start at 1.

like image 157
MacAnthony Avatar answered Mar 01 '26 20:03

MacAnthony


If your goal is to do a post for each checkbox, and to give an index or smoething, each gives you an index you can use (also, avoid writing $(this) repeatedly, it's wasteful):

$("input:checked").each(function(index) {
  var $this = $(this);
  var id_bookslot = data + index + 1;          // <== Using the index here
  var treatment_type = $this.closest("div").attr("id");
  var id_treatment = $this.attr("class");
  $.post("include/get_booking.php?insert", {
      id_bookslot:    id_bookslot,
      id_treatment:   id_treatment,
      treatment_type: treatment_type
    }
  );
});

Also note that $(this).length will always be 1, but you weren't using your counter variable anyway, so I just removed it. If you use it but just didn't quote the code that is, do this:

var checked = $("input:checked");
checked.each(function(index) {
  var $this = $(this);
  var id_bookslot = data + index + 1;          // <== Using the index here
  var treatment_type = $this.closest("div").attr("id");
  var id_treatment = $this.attr("class");
  $.post("include/get_booking.php?insert", {
      id_bookslot:    index,
      id_treatment:   id_treatment,
      treatment_type: treatment_type
    }
  );
});

...and use checked.length for your counter variable.

like image 34
T.J. Crowder Avatar answered Mar 01 '26 19:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!