根据某些业务逻辑动态添加和删除复选框事件? [英] Add and remove checkbox events dynamically depending on some business logic?

查看:75
本文介绍了根据某些业务逻辑动态添加和删除复选框事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

我有一个带有复选框的结果表,选中该复选框后,该行的内容(实际上只有2列连接在一起,被复制到具有作业代码和作业名称的新div中).这工作得很好,并且我已经避免了重复. 但是,在新的结果div中,我将创建一个锚标记以删除div本身. 除去div后,我应该能够再次使用复选框添加所选的作业. 请注意,结果表中有很多作业,因此将标志再次设置为false将不起作用.

I have a results table with a checkbox, when the checkbox is checked, the content of the row(actually 2 columns concateneted only, are copied to a new div, with the job code and job name). This works pretty well, and I am avoiding duplicated already. However, in the new results div, I am creating an anchor tag to remove the div itself. After the div has been removed, I should be able to add the selected job again with the checkbox. Please note that there are many jobs in the results table, so putting the flag to false again will not work.

此外,如果您对此问题有更好的标题,请告诉我

Also if you find a better title for this question, please let me know

    //On every checkbow that is clicked
    var flag = false;
    $("#ctl00_PlaceHolderMain_myGrid input").change(function () {
        if (this.checked && flag === false) {
            flag = true;
            var jobCode = $(this).parent().parent().parent().find("td:eq(2)").text()
            var jobName = $(this).parent().parent().parent().find("td:eq(1)").text()
            var displayvalue = jobCode.toUpperCase() + " - " + jobName.toUpperCase();                      
            AddSelectedJob(jobCode, displayvalue);
            //$(this).unbind('change'); //Unbind the change event so that it doesnt fire again
            FillSelectedJobs();            
        }
    });



//Add selected job in the results div
function AddSelectedJob(id, display) {
    //create a div for every selected job
    $("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + '<a href="javascript:;" onclick="removeSelectedJob(this)">Remove selected job</a></div>');
}

//Removes the selected job from the resutls div
function removeSelectedJob(el) {
    $(el).parent().remove();
}

生成的html是这样的:

The generated html is like this:

<div>
            <div style="height: 300px; overflow: auto; float: left">
                <div>
        <table cellspacing="0" cellpadding="4" id="ctl00_PlaceHolderMain_myGrid" style="color:#333333;width:100%;border-collapse:collapse;">
            <tr style="color:White;background-color:#5D7B9D;font-weight:bold;">
                <th scope="col">&nbsp;</th><th scope="col">JobCode</th><th scope="col">JobName</th><th scope="col">JobPartner</th><th scope="col">JobManager</th><th scope="col">ClientName</th>
            </tr><tr style="color:#333333;background-color:#F7F6F3;">
                <td>
                                <input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1" type="checkbox" name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1" />
                            </td><td>jobcode01</td><td>jobname</td><td>xx</td><td>xx</td><td>xx</td>
            </tr>
        </table>
    </div>
            </div>
            <div style="margin-top: 0px; margin-left: 10px; float: left">
                <span>Selected :</span>
                <div id="ResultsDiv" style="margin-top: 0px">
                </div>
            </div>

推荐答案

首先,我建议对HTML进行一些更改.从您的DOM中分离出样式,并将其放置在类中.

Firstly I suggest some changes to your HTML. Separate out the styles from your DOM and place them in classes.

这确保了关注点分离

HTML

<div>
    <div class="divMain">
        <div>
            <table cellspacing="0" cellpadding="4" 
                     id="ctl00_PlaceHolderMain_myGrid" class="table">
                <tr class="rowHead">
                    <th scope="col">&nbsp;</th>
                    <th scope="col">JobCode</th>
                    <th scope="col">JobName</th>
                    <th scope="col">JobPartner</th>
                    <th scope="col">JobManager</th>
                    <th scope="col">ClientName</th>
                </tr>
                <tr class="row">
                    <td>
                        <input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1" 
                           type="checkbox" 
                          name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1"
                          data-flag="false" />
                    </td>
                    <td>column1</td>
                    <td>column2</td>
                    <td>column3</td>
                    <td>column4</td>
                    <td>column5</td>
                </tr>
            </table>
        </div>
    </div>
    <div class="m0 selected"> 
        <span>Selected :</span>
        <div id="ResultsDiv" class="m0"></div>
    </div>

CSS

.divMain{
    height: 300px;
    overflow: auto;
    float: left
}

.table{
    color:#333333;
    width:100%;
    border-collapse:collapse;
}

.rowHead{    
    color:White;
    background-color:#5D7B9D;
    font-weight:bold;
}

.row{
 color:#333333;
 background-color:#F7F6F3;   
}

.m0{
     margin-top: 0px;   
}

.selected{
    margin-left: 10px;
    float: left
}

JavaScript

$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
    // Next cache your selector
    // so that you need not crawl the DOM multiple times
    var $this = $(this),
        $row = $this.closest('.row'),
        currFlag = Boolean($this.data('flag'));

    // As there might be multiple jobs , a single flag variable  
    // will not work. So you can set a data-flag attribute on the 
    // input that stores the current value
    if (currFlag === false && this.checked) {
        // Set the corresponding flag to true
        $this.data('flag', true);
        var jobCode = $row.find("td:eq(2)").text(),
            jobName = $row.find("td:eq(1)").text(),
            displayvalue = jobCode.toUpperCase() + " - " 
                         + jobName.toUpperCase(),
            inputId =  $this.attr('id')
        // Pass the input name too as you need to set the value of
        // the corresponding flag value again as you can add it multiple times         
        AddSelectedJob(jobCode, displayvalue, inputId);
        FillSelectedJobs();
    }
});

//Add selected job in the results div
function AddSelectedJob(id, display, inputId) {
    //create a div for every selected job
    // Use the inputId to save it as a data-id attribute  
    // on anchor so that you can set the value of the flag after 
    // removing it
    var html = '<div class="selectedjobs" id=' + id + '>' + display ;
    html += '<a href="javascript" data-id="'+ inputId 
                                 +'">Remove selected job</a></div>';                   
    $('[id$=ResultsDiv]').append(html);
}

// Remove the inline click event for the anchor and delgate it to the 
// static parent container
$('[id$=ResultsDiv]').on('click', 'a', function(e) {
    var $this = $(this),
        $currentCheckbox = $this.data('id');
    // Set the flag value of the input back to false

    $('#'+ $currentCheckbox).data('flag', false);
    e.preventDefault(); // prevent the default action of the anchor
    $this.closest('.selectedjobs').remove();
});


function FillSelectedJobs() {
    //save values into the hidden field
    var selectedJobs = $("[id$=ResultsDiv]").find("[class$='selectedjobs']");
    var returnvalue = "";
    for (var i = 0; i < selectedJobs.length; i++)
        returnvalue += selectedJobs[i].id + ";";
    $("[id$=HiddenClientCode]").val(returnvalue);
}

检查小提琴

Check Fiddle

这篇关于根据某些业务逻辑动态添加和删除复选框事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆