Get the ID by Class name JQuery

前端 未结 8 1887
臣服心动
臣服心动 2021-02-05 19:00

Hi this is a jquery question:

supposed i have this:





        
相关标签:
8条回答
  • 2021-02-05 19:32

    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.

    0 讨论(0)
  • 2021-02-05 19:36

    Because you have not iterated all the elements which has class 'select'. It always goes to the first element and prints the result. Put a loop to iterate all elements having class 'select'.

    0 讨论(0)
  • 2021-02-05 19:39

    you should be using radio buttons and not checkboxes to allow one choice out of many.

    <input type="radio" name="select" value="select-1">
    <input type="radio" name="select" value="select-2">
    

    then things will get really simple:

    $("#submit").click(function(){
    
        alert($('[name="select"]:checked').val());
    });
    
    0 讨论(0)
  • 2021-02-05 19:41

    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'));
        }
    });
    
    0 讨论(0)
  • 2021-02-05 19:42

    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'));
       });
    
    });
    
    0 讨论(0)
  • 2021-02-05 19:43
    $("#submit").click(function(){  
              if($(".select").is(':checked')){
                   var $this=$(".select").is(':checked');
                   alert($this.attr('id'));
              }
    });
    
    0 讨论(0)
提交回复
热议问题