jquery this.id not working

試著忘記壹切 提交于 2020-05-25 08:12:20

问题


Hello people here is my code ...

    $ (".input_check").change (function (){

        if ($ (this).is (':checked')) {
            console.log(this.id + 'is checked')
        } else {
            console.log(this.id + 'is not checked')
        }


    });

the above code works fine for several check boxes ....But i want to perform check after the page load not after $ (".input_check").change.... I tried ...

 $ (function () {
if ($ (".input_check").is (':checked')) {
            console.log(this.id + 'is checked')
        }
)}

Iam trying to find the ID this.id but not wrking.. I also tried (this).id and this.attr("id") still not working... :( am getting undefined anyways to fix this??

UPDATE :: I have multiple checkboxes which are checked... I am trying to find multiple ids of those check boxes which are checked


回答1:


(this).id and this.attr("id") are not proper jQuery syntax for this situation. Should be

$(this).attr('id') 

Fiddle

Edit based on your comments

Ok, then what stops you from doing the same on document ready?

 $(function() {
     $( ".input_check" ).each(function( index ) {
        if ($ (this).is (':checked')) {
            console.log($(this).attr('id')  + 'is checked')
        } else {
            console.log($(this).attr('id')  + 'is not checked')
        }
     });
 });

Fiddle




回答2:


To get the ID of all :checked elements as an array:

var checked = $('.input_check:checked').map(function() {
    return this.id;
}).get();



回答3:


try:

$(this).attr('id')

and check if you have a ID attribute defined in the checkbox



来源:https://stackoverflow.com/questions/24301203/jquery-this-id-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!