1

I have a table with a checkbox, when the user clicks on the checkbox, something is copied into a div, so the user knows what he has selected.

However, if I uncheck and check again, then its copied again to the div.

           //On every checkbow that is clicked
    var flag = false;
    $("#ctl00_PlaceHolderMain_myGrid input").change(function () {
        if (this.checked && flag === false) {
            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();
            //var removeDiv = $("#" + clientCode);

            //removeDiv.remove();         

            AddSelectedJob(jobCode, displayvalue);
            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();
}

    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);

    }

This is the generated html

<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>column1</td><td>column2</td><td>column3</td><td>column4</td><td>column5</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>

Update 1: A more clear explanation:

I have a table with checkboxes, when a row is selected the job code and job name is copied to a div called results. In that div, I created an anchor tag to remove the div itselft. When the remove selected job link is clicked, I should be able to add it again from the table when click the checkbox again. However if the selected job is already on the div results, I should not be able to add it again. Please see question here also: Remove div on the click of a link that was created dynamically

Community
  • 1
  • 1
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506
  • So within the _if checked_ block unbind the change handler. Unless I've completely misinterpreted what you're trying to do, which wouldn't surprise me given that you didn't actually ask a question. Please explain the desired behaviour more clearly. – nnnnnn Jun 03 '13 at 06:58
  • and how can I do that? – Luis Valencia Jun 03 '13 at 06:59
  • _$(this).off("change")_ would unbind the handler on the current checkbox, so that would prevent the associated data being copied to the div more than once. – nnnnnn Jun 03 '13 at 07:11

3 Answers3

1

Why not just use the checked attribute instead of unbinding the event

var flag = false;
$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
    if(this.checked && flag === false) {
         flag = true;  // set it to true so that it does 
                       // fire this block again
         // do something
    }
    else {
        // do something else
    }
});

OR

For a cleaner approach, if you want the event to fire only once for the life time of the page load , then just unbind the event

$(this).off('change')   // If using .on

EDIT

If the above code does not help this should work

if (this.checked) {
   $(this).unbind('change');   // or //   $(this).off('change');
   AddSelectedJob(clientCode, displayvalue);
   FillSelectedJobs();
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • _this.checked_ is definitely better than _$(this).prop("checked") == true_ but ultimately they both do the same thing so how would this change the behaviour of the OP's code? – nnnnnn Jun 03 '13 at 07:05
  • "if I uncheck and check again, then its copied again to the div.". Would your code suffice for the said requirement? – Khadim Ali Jun 03 '13 at 07:06
  • @nnnnnn .. Thanks for pointing it out.. Think I missed it.. I have edited the code.. Added a extra flag variable that exists outside the scope of the event. This is solve your issue – Sushanth -- Jun 03 '13 at 07:09
  • @nnnnnn.. Also if the OP wants the event to exist for only a single life time of page load, then unbinding the event makes more sense – Sushanth -- Jun 03 '13 at 07:10
  • @Sushanth-- when I click the checkbox 3 times, one to select, another time to unselect, and then to select again, then it adds the selected job again creating duplicated on the div. plese help – Luis Valencia Jun 03 '13 at 07:24
  • @LuisValencia.. Did you try adding the flag variable or unbinding the event – Sushanth -- Jun 03 '13 at 07:26
  • I tried the flag approach but it didnt work, I didnt try unbinding the event because, on the other div there is a Remove Selected Job Link, so if it is removed then the checkbox has to work again, please see my other question here: http://stackoverflow.com/questions/16891656/remove-div-on-the-click-of-a-link-that-was-created-dynamically – Luis Valencia Jun 03 '13 at 07:28
  • Copy the code that you have tried into your question.. Do not replace the current one – Sushanth -- Jun 03 '13 at 07:29
  • @Sushanth-- I will, in the meantime please read the update at the bottom of the question – Luis Valencia Jun 03 '13 at 07:31
  • you are not updating the value of `flag = true` when checked for the first time . So it is always false and will always pass the condition – Sushanth -- Jun 03 '13 at 07:36
  • @Sushanth-- It works now, now the 2nd part is, after I click on the remove selecteed job, I should be able to add again that row to the results div. If you want I can create another question for that? – Luis Valencia Jun 03 '13 at 07:43
  • @Sushanth-- please see question here http://stackoverflow.com/questions/16892229/add-and-remove-checkbox-events-dinamically-depending-on-some-business-logic – Luis Valencia Jun 03 '13 at 07:52
0

Before AddSelectedJob you can check the if content of particular div is empty.

Madurika Welivita
  • 890
  • 1
  • 10
  • 19
0

Do not do in this way. What I would do. On every checkbox click, I will get the list of checked checkbox again and display it in a result div.

In your case you are appending DIV on every click. Which will cause duplication if I checked multiple times.

Still if you want to stick to this pattern then you have to remove entry from the ResultDiv when you unchecked the checked checkbox.

Please let me know if you have any query or confusion.

alok_dida
  • 1,723
  • 2
  • 17
  • 36