Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ID by Class name JQuery

Hi this is a jquery question:

supposed i have this:

<input type="checkbox" class="select" id ="select-1">

<input type="checkbox" class="select" id ="select-2">

and i want to get the id, of the checkbox that has been selected when i click a submit button (note: you can only select 1) and i have this button click event here:

$("#submit").click(function(){

          if($(".select").is(':checked')){

              alert($(".select").attr('id'));
          }
});

It always alerts "select-1" even if i select the checkbox with the "select-2" id.. I'm guessing since they're both in the same class the first one with the ".select" class to be found is displayed in the alert.. how do i get the specific id that is checked by using their class names? Thank You!

like image 262
muffin Avatar asked Oct 25 '13 06:10

muffin


4 Answers

Are you only checking one checkbox at a time?

alert( $(".select:checked").attr('id') );

Or, if you have multiple checkboxes checked at once:

$(".select:checked").each(function(){
   alert($(this).attr('id'));
});

Demo: http://jsfiddle.net/UTux2/

like image 131
XCS Avatar answered Oct 19 '22 20:10

XCS


Get ID using this way

$(".select:checked").attr('id');

Also keep in mind that if only one can be selected, it's better to change it to radio.

like image 28
Elon Than Avatar answered Oct 19 '22 22:10

Elon Than


You aren't capturing the checked checkbox, you're only asking "is there one checked?".

$("#submit").click(function(){

    var elem = $(".select:checked");

    if(elem.length > 0){
        alert(elem.attr('id'));
    }
});
like image 2
MrCode Avatar answered Oct 19 '22 21:10

MrCode


There are multiple elements. You need to check for all checkbox having same class

$("#submit").click(function(){

          $(".select:checked").each(function(){
           alert($(this).attr('id'));
   });

});
like image 2
sudhAnsu63 Avatar answered Oct 19 '22 20:10

sudhAnsu63