1

I have gone through quite a few similar question but none of them fit to my problem.

I am calling a function after onclick event to my anchor tag and after clicking the anchor tag the function adds a row new row to another section within the webpage.

What I am trying to do is to revert the process back when a user clicks on the same anchor tag again. In other words the newly added row should be removed from the view if clicked again.

Here is my code where on click I am calling a function to add new rows

function drawSelections(betTypeId, tableId, selections) {
    var whiteLegendTrId = tableId + '_whiteLegendTr';

    $.each(selections, function(i, v){

        var selectionRowId = tableId + '_' + v.id;

        document.getElementById(tableId).appendChild(createTr(selectionRowId,null,"white"));

        $('#' + whiteLegendTrId).find('td').each(function() {
            var tdId = $(this).attr('id');
            if (tdId == "pic") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, "",null))}
            else if (tdId == "no") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.position,null))}
            else if (tdId == "horseName" || tdId == "jockey") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.name,null))}

            // Horse prices
            else {
                var priceNotFound = true;
                $.each(v.prices, function(index,value) {
                    if (value.betTypeId == betTypeId && (value.productId == tdId || value.betTypeId == tdId)) {
                        priceNotFound = false;

                        var td = createTd(null, null, null, "", null),
                            a = document.createElement('a');
                        a.innerHTML = value.value.toFixed(2);

                        // adding new rows after onclick to anchore tag
                        (function(i, index){
                            a.onclick=function() {
                                var betInfo = createMapForBet(selections[i],index);
                                $(this).toggleClass("highlight");
                                increaseBetSlipCount();
                                addToSingleBetSlip(betInfo);
                            }
                        })(i,index)

                        td.appendChild(a);
                        document.getElementById(selectionRowId).appendChild(td);
                    }
                });
                if (priceNotFound) document.getElementById(selectionRowId).appendChild(createTd(null, null, null, '-',null));
            };
        });
    });
}

Adding new rows

function addToSingleBetSlip(betInfo) {
    // Show bet slip
    $('.betslip_details.gray').show();
    // Make Single tab active
    selectSingleBetSlip();

    // Create div for the bet
    var div = createSingleBetDiv(betInfo);
    $("#bets").append(div);

    // Increase single bet counter
    updateBetSinglesCounter();

}

This is the JS code where I am generating the views for the dynamic rows added after clicking the anchor tag in my first function

function createSingleBetDiv(betInfo) {
    var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
        div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
        a =  createA(null, null, null, 'right orange'),
        leftDiv = createDiv(null, null, 'left'),
        closeDiv = createDiv(null, null, 'icon_shut_bet'),
        singleBetNumber = ++document.getElementsByName('singleBet').length;

    // Info abt the bet
    $(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>.&nbsp;' + betInfo['horseName'] + '</b></p>');
    var raceInfo = "";
    $("#raceInfo").contents().filter(function () {
        if (this.nodeType === 3) raceInfo = $(this).text() + ',&nbsp;' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
    });
    $(leftDiv).append('<p class="title">' + raceInfo + '</p>');

    // Closing btn
    (function(id) {
        a.onclick=function() {
            removeSingleBet(id + '_div');
        };
    })(id);
    $(a).append(closeDiv);

    // Creating input field
    $(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');

    // Creating WIN / PLACE checkbox selection
    $(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');

    // Append left part
    $(div).append(leftDiv);
    // Append right part
    $(div).append(a);
    // Appending div with data
    $.data(div, 'mapForBet', betInfo);

    return div;
}

Function to delete the individual rows

function removeSingleBet(id) {

    // Remove the div
    removeElement(id);

    // Decrease the betslip counter
    decreaseBetSlipCount();

    // Decrease bet singles counter
    updateBetSinglesCounter();
}

function removeElement(id) {
    var element = document.getElementById(id);
    element.parentNode.removeChild(element);
}
8
  • The way i read it, the function that adds the bets should be able to remove the bet also. Right now it adds another slip and that's wrong. You could add a data attribute to the bet and an attribute to the slip. Check for matching entities when clicking on the bet. If it exists loop through the slips and remove the offensive slip, if not add one. Am i on the right track? (pun intended) Commented Mar 11, 2014 at 8:51
  • yeah you are on the right track. Since I already have a function which removes the bet from the bet slip, but it is called in another function. I would like to call it in the same function where I am adding new bet slips after clicking on anchor tag which is function drawSelections(betTypeId, tableId, selections) Commented Mar 11, 2014 at 8:55
  • Ok, am I correct that it's the identification of an already existing element that's the problem? As in, if the slip has been created or not or actually exists? Commented Mar 11, 2014 at 9:05
  • yep. If the bet is already added in the betslip. Adding it again from the bet table should actually remove the bet instead of adding it one more time as my function is doing at the moment. I believe if you visit the website you will get more clear idea. Commented Mar 11, 2014 at 9:08
  • What you're trying to do here is to create a two way binding through a view and a data model. I understand that it's beside the scope, but another time it might be a good idea to use a framework like knockoutJS for this. You can use api.jquery.com/jQuery.data to save the associated ID/object directly on the button. Then check for its existence when deciding whether or not to create or remove. Ok so now that we have established the problem we can look for a solution. Adding a unique ID to the slip that matches the bet. It might even be possible to add the object itself to the bet. Commented Mar 11, 2014 at 9:14

1 Answer 1

1

It's not the most elegant solution, but it should get you started.

I tried keeping it in the same format as your code where applicable:

http://jsfiddle.net/L5wmz/

ul{
    min-height: 100px;
    width: 250px; 
    border: 1px solid lightGrey;
}

<ul id="bets">
    <li id="bet_one">one</li>
    <li id="bet_two">two</li>
</ul>
$(document).ready(function(){
    var bets   =    $("#bets li");
    var slips  =    $("#slips");

    bets.bind("click", function(){
        var that = $(this);

        try{
            that.data("slipData");
        }catch(err){
            that.data("slipData",null);
        }

        if(that.data("slipData") == null){
            var slip = createSlip({slipdata:"data"+that.attr("id")});
            slip.bind("click", function(){
                that.data("slipData",null);
                $(this).remove()
            });
            that.data("slipData",slip);
            slips.append(slip);
        }
        else{
            slips.find(that.data("slipData")).remove();
            that.data("slipData",null);
        }
        console.log(that.data("slipData"));
    });
});

function createSlip(data){
    var item = $(document.createElement("li")).append("slip: "+data.slipdata);
    return item;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. I will test it out and restructure my code based on your example.
Cool, remember to select as answer if it helps you moving on :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.