jQuery iCheck 回调函数

4

我正在使用Jquery iCheck样式化输入字段,但我到了一个无法处理iCheck回调的地步。我想要检索的是,所有在给定类名的容器内被选中的输入值。

http://jsfiddle.net/lgtsfiddler/E4bKg/1/ 这里是我一直在尝试的代码,但是点击的元素在流程中不会被推入数组,只有在第二次点击时才会。

  <ul class="brands">
        <li>
            <input class ="marken" type="checkbox" name="brand" value="brand1">
            <label>brand1</label>
        </li>
        <li>
             <input class ="marken" type="checkbox" name="brand" value="brand1">
            <label>brand2</label>
        </li>
        <li>
             <input class ="marken" type="checkbox" name="brand" value="brand1">
            <label>brand3</label>
        </li>
        <li>
             <input class ="marken" type="checkbox" name="brand" value="brand1">
            <label>brand4</label>
        </li>
    </ul>

代码:

 $(document).ready(function () {
     //here I style with iCheck
     $('ul.brands input').each(function () {
         var self = $(this),
             label = self.next(),
             label_text = label.text();

         label.remove();
         self.iCheck({
             checkboxClass: 'icheckbox_line-blue',
             radioClass: 'iradio_line',
             insert: '<div class="icheck_line-icon"></div>' + label_text
         });
     });

     //Register click event
     $('ul.brands input').on('ifClicked', function (event) {
         brands();
     });
 });
 //here I try to retrieve all checked values
 function brands() {
     var brands = [];
     $('ul.brands li div.icheckbox_line-blue').each(function (index, value) {
         var attr_class = $(value).attr('class');
         console.log(attr_class);
         //check if icheckbox_line-blue class contains checked  
         if (attr_class.indexOf("checked") !== -1) {
             brands.push($(value).find('input').val());
         }
     });
     console.log(brands);
 }

那么如何在选择后检查这个类呢?
1个回答

7

你可以检查原始的复选框而不是类,然后从父级获取按钮描述。

顺便说一下,我使用ifToggled事件,这样它将为已选和未选元素触发。

代码:

$('ul.brands input').each(function () {
    var self = $(this),
        label = self.next(),
        label_text = label.text();

    label.remove();
    self.iCheck({
        checkboxClass: 'icheckbox_line-blue',
        radioClass: 'iradio_line',
        insert: '<div class="icheck_line-icon"></div>' + label_text
    });
});

$('ul.brands input').on('ifToggled', function (event) {
    brands();
});

function brands() {
    var brands = [];
    $('ul.brands input').each(function (index, value) {
        if ($(this).is(':checked')) {
            brands.push($(this).parent().text());
        }
    });
    console.log(brands);
}

演示: http://jsfiddle.net/IrvinDominin/S2NdY/


@fefe 很高兴能帮助你! - Irvin Dominin
你知道你在这个问题上帮了我很多。 - fefe
Irvin,你尝试过设置输入框的checked属性吗?似乎不是这个问题。is(:checked)返回true,但当表单提交时,复选框并没有被发送为已选中。 - Alexander Suraphel
如果我的ul的类是动态的呢?@Irvin Dominin - Mir Gulam Sarwar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接