samedi 27 février 2016

getJSON if checkbox is checked then uncheck

I got a function getBrandUrl() which fires getProducts().

If a checkbox is checked and the function is fired (for the second time, on a checked checkbox) the checkbox needs to be unchecked. So I can build the GET request without the value of that checkbox to filter out products by brand.

<input type="checkbox" name="brand[]" value="35890" onclick="javascript:getBrandUrl('35890');">
<a href="javascript:getBrandUrl('35890');" title="blabla" alt="blabla">blabla</a>

Clicking the a[href] (blabla) for the first time? then the checkbox needs to be checked and the GET request can be formatted. So if another checkbox or a[href] is clicked it appends to the URL and when it's clicked for the second time it needs to be removed.

function getBrandUrl(value)
        {
            getProducts("<?=$filterUrl?>", value, 'brand[]');
        }

function getProducts(url, value, type)
        {

            if($('input[type="checkbox"][value="' + value + '"]').is(':checked')) {
                $(this).attr('checked', 'false');
            } else {
                $(this).attr('checked', 'true');
            }

            var checked = '';
            $('input[name="' + type + '"]:checked').each(function() {
                checked += '&' + type + '=' + this.value;
            });

            $.getJSON(url + checked + "&json=true", function(data) {
                $('#productList').html('');

                $.each( data, function( key, val ) {
                    var product = formatProductHTML(val.ID, val.PRICE, val.TITLE, val.LINK);

                    $(product).appendTo('#productList');
                });
            });
        }

The problem is that when I click for the first time it will be uncheck right away so it won't be in the formatted GET request.

Any idea's how to solve this problem or does anyone know what i'm doing wrong here?




Aucun commentaire:

Enregistrer un commentaire