jq实现input全选,反选,所选的value实现购物车的功能

不废话直接上代码

html

<div class="box_content">
        <from>
            <input type="checkbox" name="ipty_0" class="ty_input" value="手机">
            <input type="checkbox" name="ipty_1" class="ty_input" value="电视">
            <input type="checkbox" name="ipty_2" class="ty_input" value="电脑">
            <input type="checkbox" name="ipty_3" class="ty_input" value="汽车">
            全选:<input type="checkbox" name="iptys" id="all" value="mrli">
            取消:<input type="checkbox" name="iptn" id="noAll">
            <input type="submit" value="提交订单" id="submit_order">
        </from>
</div>

js

<script>
var aa=[];//存储所选的value值
$(document).on('click','#all',function(){//全选事件
    if($('input[name = iptys]').is(':checked')){//全选按钮为true时执行
        $('input[name ^= ipty_]').prop("checked","true");//将所有input的name开头是ipty_的添加checked为true
        $('input[name = iptys]').prop("checked","true");
        $('input[name = iptn]').removeAttr("checked");
    }else{
        $(this).prop("checked","true");//此步用意(点击过全选后再点击无效)
    }
}).on('click','#noAll',function(){//反选事件
    if($('input[name = iptn]').is(':checked')){//反选按钮为true时执行
        $('input[name ^= ipty_]').removeAttr("checked");//将所有input的name开头是ipty_的去掉checked
        $('input[name = iptys]').removeAttr("checked");
    }else{
        $(this).prop("checked","true");//此步用意(点击过反选后再点击无效)
    }
}).on('click','.ty_input',function(){//单选事件
    if($('input[name = iptn]').is(':checked')){
        $('input[name = iptn]').removeAttr("checked");
    }
    if($(this).is(':checked')){
        if($('input[name ^= ipty_]:checked').length == $('.ty_input').length){//判断有ty_input类名的input个数和input的name以ipty_开头的且被选中的个数相等时
            $('#all').prop("checked","true");//设置全选按钮为true
        }
    }else{
        if($('input[name ^= ipty_]:checked').length !== $('.ty_input').length){//判断有ty_input类名的input个数和input的name以ipty_开头的且被选中的个数不相等时
            $('input[name = iptys]').removeAttr("checked");//设置全选按钮为false
        }
    }
}).on('click','#submit_order',function(){//提交事件
    if($('input[name ^= ipty_]:checked').length > 0){
        $('input[name ^= ipty_]').val()
        $("input[name ^= ipty_]:checkbox:checked").each(function(){
            aa.push($(this).val())
        })
        console.log(aa)
        aa = []; //提交完成置空数组(防止点击全选后提交完成点击反选在提交会有数据的问题)
        //当然项目中不会出现这问题,提交完成肯定是要跳转的
        //项目中aa数组的数据最好是存下缓存(Cookie 或 sessionStorage)
    }else{
        alert('请选择商品')
    }

})
</script>

效果展示

jq实现input全选,反选,所选的value实现购物车的功能

我的应用

jq实现input全选,反选,所选的value实现购物车的功能