0

I have a problem with my code. I am creating a form that has multiple textbox and what my process is. If the user checked the checkbox, there is a function for setting the product ID in the array. If the user unchecked, the product ID in the array must removed. I am using the checkbox onclick trigger effect.

Here's my sample code:

function setProduct(product_id) {

    var arr_product = [];

    //if existed, removed in the array
    if($.inArray(product_id), arr_product) {

        arr = jQuery.grep(arr_product, function(value) {
            return value != product_id;
        }); 

    } else {

        arr_product.push(product_id);      

    }

    return arr_product;

}

function viewSetItems(product_id, product_name, image) {

    var url_link = 'index.php?route=product/product/getSetProducts&product_id=' + product_id;

    $.ajax({
        url: url_link,
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
            $("#display-set-item").fadeIn();
        },
        success: function(data) {

           if(image == '') {
                image = "<?php DIR_IMG_DATA ?>image/cache/data/no_image-200x200.jpg";    
           }

           $("#p-img").prepend("<img src='"+image+"' height='150' width='150' class='img-responsive'/>");
           $("#p-img").attr("rowspan",data.length + 1);         

           var prod_array = [];   

           data.forEach(function(i){

                var p_array = i.product_id + "_" + i.price;

                prod_array.push(p_array);

                name = product_name.replace("||", " "); // value = 9:61
                $("#p-name").text(name);

                $h_table = '';

                $nname = i.name;
                $p_name = $nname.replace("||", " ");

                $link = 'index.php?route=product/product&product_id=' + i.product_id;

                $h_table+="<tr class='p-detail'>";
                    $h_table+="<td class='text-center'><input type='checkbox' name='p_price[]' id='pp-"+i.product_id+"' value="+i.price+" onClick='setProduct("+i.product_id+")' /></td>";
                    $h_table+="<td><a href='"+$link+"' class='modal-link'>" +$p_name+ "</a></td>";
                    $h_table+="<td class='text-right'>" +i.price+ "</td>";    
                $h_table+="</tr>";

                $("#table-product-set").append($h_table);

            });

            prod_array.forEach(function(d) {

                var x = d.split("_");
                setProduct(x[0]);

            });

            alert(setProduct());

            $('#table-product-set tr:last').after("<tr class='p-action'><td colspan='4'><span class='btn-blue pull-right' id='close-btn' style='cursor: pointer;' onclick='closeMe()'>CLOSE</span><input type='button' class='btn-blue pull-right' value='ADD TO REGISTRY' style=' margin-right: 5px' /></td></tr>");

        },
        error: function() {
            $("#display-set-item").text('Error');
        }
    });

}

Sorry I have a little knowledge in jquery/javascript. I hope you can help me. Ok that's all guys, Thanks.

6
  • So what is your problem exactly? what is missing? Commented Aug 12, 2014 at 7:07
  • Can you explain your HTML structure a little more? Do you have a series of checkboxes on a page (for example, one for each product, 10 products on a page) and are trying to keep track of exactly which ones are ticked? Commented Aug 12, 2014 at 7:07
  • I have an error in the setProduct() function. Maybe my code is wrong but I don't know where it is. In every product there is a checkbox. Commented Aug 12, 2014 at 7:12
  • shouldnt that be $.inArray(product_id, arr_product) ..? Commented Aug 12, 2014 at 7:15
  • So I can't use the $.inArray() in if statement? Commented Aug 12, 2014 at 7:20

1 Answer 1

1

I'm assuming you meant you have a checkbox per item/product/etc., you have multiple items on a page, and you want to keep track of which items are ticked.

First of all, you're redeclaring your arr_product array on each call of setProduct(), so that's never going to work.

I can see you're dynamically adding the HTML for each checkbox, which is good: it means you already have a loop running through all of them. I would recommend adding a data attribute to each checkbox indicating its index in the array you're going to keep.

Add a variable var index = 0; to your code above the foreach() loop. At the bottom of your foreach() add index++;. You now have an index which keeps track of how many checkboxes you have added, which is also each checkbox its position in the array.

In each iteration of the loop, add this to the checkbox code: data-index="+ index +", making the total:

<input type='checkbox' name='p_price[]' id='pp-"+i.product_id+"' value="+i.price+" onClick='setProduct("+i.product_id+")' data-index=" + index + " />

Also in each iteration, add this event listener:

$("#" + "pp-" + i.product_id).on("change", function(e)
{
    arr_product[$(this).getAttribute("data-index")] = $(this).prop("checked");
}

You now have an event listener attached to each checkbox which sets the corresponding value in an array to true or false, based on whether its checked or unchecked.

Edit: of course the above assumes you place the arr_product somewhere where it isn't re-initialised continuously. Also, if you want to still use your function that's also possible. Change your function signature to be setProduct(product_index, value), and then call it by replacing the line arr_product[.......("checked"); above with setProduct($(this).getAttribute("data-index"), $(this).prop("checked"));

P.S. I'd recommend using an index attached to the actual checkbox in this case because the handling is much easier overall than a ID-string. However, if you really want to use the ID you can replace the index with an ID.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks for the wonderful solution. And the very clear answer. I implemented that in my code and so far no errors. Thanks again. :)
@Jerielle I aim to please. ;)

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.