0

I have an array like

var favorite = {};
    $.each($(".list input[type='checkbox']:checked"), function(){ 
        if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
            favorite[$(this).attr("name")] = [];
        }           
        favorite[$(this).attr("name")].push($(this).val());
    });

With one dimensional array I can do:

$('#list [value="'+favorite.join('"],[value="')+'"]').prop('checked',true);

Which produces a selector like:

$('#list [value="1"],[value="3"],[value="4"],[value="5"]')

But how can I produce a selector from two dimensional array like:

$('#list [Name="Name[]",value="1"],[Name="Name[]",value="3"],[Name="Name[]",value="4"],[Name="Model[]",value="5"]')

I need to select all checkboxes which is in favorite array. Because after ajax Post I lose all checked checkboxes something like that:

$(function() {
    $('.list input').change(function(e){
            //e.preventDefault();
            var favorite = {};
                $.each($(".list input[type='checkbox']:checked"), function(){ 
                    if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                        favorite[$(this).attr("name")] = [];
                    }           
                    favorite[$(this).attr("name")].push($(this).val());
                });


        var str;
        str = $.param(favorite);
        
        $.ajax({
            url:'/Search.asp',
            type:'POST',
            data:str,
            dataType:'text',
            success: function(data)
            {
                $("#ExSearchForm").html(data);
                $("#ExSearchForm").find('[value=' + favorite.join('], [value=') + ']').prop("checked", true);
            }
        });
        

    });
});

The Html markup

                <div class="list">
                    <div class="nomination">Make</div>
                    <div class="name">
                    <label class='selected-car'><input type='checkbox' name='Make[]' value='*FAKE*' /><span>*FAKE*<i>0</i></span></label>
<label class='selected-car'><input type='checkbox' name='Make[]' value='AIXAM' /><span>AIXAM<i>2</i></span></label>
<label class='selected-car'><input type='checkbox' name='Make[]' value='ALFA ROMEO' /><span>ALFA ROMEO<i>106</i></span></label>
<label class='selected-car'><input type='checkbox' name='Make[]' value='ALPINA' /><span>ALPINA<i>1</i></span></label>
<label class='selected-car'><input type='checkbox' name='Make[]' value='AUDI' /><span>AUDI<i>686</i></span></label>
<label class='selected-car'><input type='checkbox' name='Make[]' value='BMW' /><span>BMW<i>557</i></span></label>
....
4
  • I dont think the last selector is valid. It wont work Commented Jun 10, 2015 at 12:09
  • 2
    I'm pretty sure this is a lot more complicated than it needs to be. Can you describe what you are trying to achieve so we can show you a more efficient way. Commented Jun 10, 2015 at 12:09
  • $(".list input[type='checkbox']:checked") already return your checked input as jquery object, saving this into a var and use it later $("#ExSearchForm").find(myvar).prop("checked", true); should do the trick Commented Jun 10, 2015 at 12:33
  • $("#ExSearchForm").find(myvar) will not work beause of DOM will be completely updated after POST success. So, references to the elements will be cleared too. Commented Jun 10, 2015 at 12:42

2 Answers 2

2

You should create array of values based on favorite object:

$('.list input[type=checkbox]').on('change', function () {
    var favorite = {};

    $('.list input[type=checkbox]:checked').each(function () {
        var $el = $(this);
        var name = $el.attr('name');
        if (typeof (favorite[name]) === 'undefined') {
            favorite[name] = [];
        }
        favorite[name].push($el.val());
    });

    $.ajax({
        url: '/Search.asp',
        type: 'POST',
        data: $.param(favorite),
        dataType: 'text',
        success: function (data) {
            $("#ExSearchForm").html(data)
                .find('input[type=checkbox]').each(function () {
                    var $el = $(this);
                    var name = $el.attr('name');
                    var value = $el.attr('value')
                    if (favorite[name] && favorite[name].indexOf(value) !== -1) {
                        $el.prop('checked', true);
                    }
                });
        }
    });
});

Notice: But such kind of selectors are very complicated and could be extremely slow.

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

13 Comments

This selector is similar to your (it can be slow in case if there are thousands of checkboxes).
But the snippet will be little faster in gerenal than your. Because it caches references to checkbox elements inside each loop and form reference inside success callback.
This example should be pretty fast. Just try it.
It was a typo mistake. Just replace a by favorite
|
0

I would suggest using an array of objects instead then you can easily iterate over that array which would also be significantly faster.

Something like this

$(function() {
    $('.list input').change(function(e){
            //e.preventDefault();
            var favorite = {};
                $.each($(".list input[type='checkbox']:checked"), function(){ 
                    if(typeof(favorite[$(this).attr("name")]) == 'undefined'){
                        var item = {
                          value: 1, 
                          name : favorite[$(this).attr("name")
                        }
                    } else {
                        var item = {
                          value: 0, 
                          name : favorite[$(this).attr("name")
                        }
                    }
                                          
                    favorite[$(this).attr("name")].push(item);
                               
                    
                });

    });
});

2 Comments

You can not use array of objects because favorite should be serialized later using $.param and passed as param to the $.ajax
Objects can be serialized too?

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.