简体   繁体   中英

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.

var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
    var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
    var cityID = $(event.target)[0].id;//stores city id
    var cityVal = $(event.target)[0].value;//stores city value

    if ($('#' + cityID).is(':checked')) {
        if (userCityList.length < 5) {
            userCityList.push(cityID);
        }
        else {
            $('#' + cityID).prop('checked', false);
            alert("5 cities have been selected");
            return;
        }
    }//end if

    if (!($("#" + cityID).is(':checked'))) {
        userCityList.pop();
    }
    //console.log(userCityList);

});

LOGIC

When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.

Any suggestions?

HTML code

<div class="panel-body">
    <p>Select upto 5 state/city combinations</p>
    <div class="col-xs-3 no-pad-left less-width">
        @*<p>Select upto 5 state/city combinations</p>*@
        <select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
    </div>
    <div class="col-xs-3" id="checkboxes">

    </div>
</div>

UPDATE Here's the image that goes with this issue.

在此处输入图片说明

So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.

UPDATE

Here's the AJAX code...

    $("#ResidentialLocationStateList").change(function () {
    url = "/ResidentialBuilding/getCityList?state=";
    state = $("#ResidentialLocationStateList").val();
    url = url + state;
    //console.log(url);
    $("#checkboxes").empty();
    $.getJSON(url, function (data) {
        //console.log(data);
        $.each(data, function (index, value) {
            //console.log(value.city);
            id = value.city;
            id = id.replace(/\s+/g, '');
            valCity = value.city;
            valCity = valCity.replace(/\s+/g, '');
            $("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" +  'id=' + id + '>' + value.city + '</input><br>');
        });
    });
});

If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.

lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes .

Therefore, I would suggest the following code

var userCityList = [];
$(document).on("change", ".checkboxes", function() {
    var stateVal = $('#ResidentialLocationStateList').val();
    var cityID = this.id;//stores city id
    var cityVal = this.value;//stores city value
    var finalDiv = $('#final');
    var tempDiv  = $('#othertempdiv');

    if( this.checked ) {
        if( userCityList.length < 5 ) {
            userCityList.push( cityID );
            finalDiv.append( this );
        } else {
            $(this).prop('checked', false);
            alert('5 cities have been selected');
        }
    } else {
        var index = $.inArray( cityID, userCityList );
        if( index > -1 ) {
            userCityList.splice( index, 1 );
            tempDiv.append( this );
        }
    }
});

Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.

<div id="final"></div>

Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ] :

var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
    var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
    var cityID = $(event.target)[0].id;//stores city id
    var cityVal = $(event.target)[0].value;//stores city value

    if ($('#' + cityID).is(':checked')) {
        if (userCityList.length < 5) {    
            if(!userCityList[stateVal])userCityList[stateVal] = [];            
            userCityList[stateVal].push(cityID);
        }
        else {
            $('#' + cityID).prop('checked', false);
            alert("5 cities have been selected");
            return;
        }
    }//end if

    if (!($("#" + cityID).is(':checked'))) {
        if(userCityList[stateVal]){
        //Edited, now it can remove the city by its position (index)
          var position = $.inArray(cityID, userCityList[stateVal]);   
            userCityList[stateVal].slice(position, 1);
        }

    }
});

So when you need to retrieve the checked cities for an state you can do just:

for(var i =0; i < userCityList[stateVal].length; i++){
   console.log(userCityList[stateVal][i]);
}

UPDATE

The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:

  $("#ResidentialLocationStateList").change(function () {
    url = "/ResidentialBuilding/getCityList?state=";
    state = $("#ResidentialLocationStateList").val();
    url = url + state;
    //console.log(url);
    $("#checkboxes").empty();
    $.getJSON(url, function (data) {
        //console.log(data);
        $.each(data, function (index, value) {
            //console.log(value.city);
            id = value.city;
            id = id.replace(/\s+/g, '');
            valCity = value.city;
            valCity = valCity.replace(/\s+/g, '');
            $("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" +  'id=' + id + '>' + value.city + '</input><br>');
            //Let's check if this checkbox was previously checked
            if($.inArray(id, userCityList[state])){
                    //if yes, let's check it again
                    $('#'+id).prop('checked', true);                
            }
        });
    });
});

Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM