zoukankan      html  css  js  c++  java
  • 【特效】复选框的值动态添加

    实际做项目时遇到的效果,以后也可能会遇到,先记下来。

    效果描述:一个文本框,后面的若干复选框选项,当选项补勾选,其值会加入到文本框中,不勾选,则其值会从文本框中删除。js代码用到了数组的相关知识,插入和删除数组。具体代码如下:

    html:

    <input type="text" value="" class="input1">

    <div class="checks">

             <input type="checkbox" id="check_1"><label for="check_1">省1</label> 

        <input type="checkbox" id="check_2"><label for="check_2">省2</label>

        <input type="checkbox" id="check_3"><label for="check_3">省3</label>

        <input type="checkbox" id="check_4"><label for="check_4">省4</label>

        <input type="checkbox" id="check_5"><label for="check_5">省5</label>

        <input type="checkbox" id="check_6"><label for="check_6">省6</label>

        <input type="checkbox" id="check_7"><label for="check_7">省7</label>

        <input type="checkbox" id="check_8"><label for="check_8">省8</label>

    </div> 

    js:

    <script>

    $(document).ready(function(){

             var input1=$(".input1");

             var input2=$(".checks input");                 

             var arrayObj=new Array();

            

             //删除数组中指定的值

             function removeByValue(arr,val){

                    for(var i=0;i<arr.length;i++){

                           if(arr[i]==val){

                        arr.splice(i,1);

                        break;

                           }

                    }

             }

            

             input2.each(function(){

                       $(this).click(function(){

                                var text1=$(this).next("label").html();                      

                                if($(this).prop("checked")==true){

                                         arrayObj.push(text1);     

                                         input1.prop("value",arrayObj);                                   

                                         }

                                if($(this).prop("checked")==false){

                                         removeByValue(arrayObj,text1);

                                         input1.prop("value",arrayObj);

                                         }                          

                                });    

                      

                       });

    });                                

    </script>

    当然了,里面每个复选框的id也可以用js来添加,另一篇博客中会写到这个知识点。

    效果预览:http://www.gbtags.com/gb/rtreplayerpreview-standalone/2916.htm

    源码下载:http://pan.baidu.com/s/1bpIACm7

  • 相关阅读:
    Caesar cipher
    遗传算法之背包问题
    Transport scheme NOT recognized: [stomp]
    error running git
    Canvas 旋转的图片
    canvas时钟
    火箭起飞
    让图标转起来
    Tomcat启动脚本
    Task中的异常处理
  • 原文地址:https://www.cnblogs.com/xiaoxianweb/p/5704174.html
Copyright © 2011-2022 走看看