简体   繁体   English

javascript保存复选框状态

[英]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. 这是部分起作用的jQuery代码。

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. 当用户单击复选框时,该特定城市将存储在userCityList数组中。 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 HTML代码

<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... 这是AJAX代码...

    $("#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. 如果您使用的一个现代版jQuery我会建议使用.off.on和使用.off如果你真的不得不这样做。

lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. 同样, .pop()数组方法删除了最后一个元素,但是刚刚单击的元素可能并不总是最后添加的元素。 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. 并且由于复选框是动态添加的,因此可以在DOM ready的一开始就进行以下绑定,而不必在任何事件处理程序中进行。 Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes . 不要给您的复选框提供相同的ID以导致无效的HTML,而应使用类选择器.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. 由于您-根据下面的评论-每次选择一个新州都将替换所选城市,因此您将必须有第二个div来容纳所有所选城市。 Un-checking any of the cities in this final div would move it back; 取消选中最后一个div中的任何城市都会将其移回; 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 ] : 使用多维数组存储州和城市ID,例如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: 现在,在您的ajax代码中,当加载一组新的复选框时,您必须检查该复选框先前是否已被选中:

  $("#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. 请记住,userCityList变量必须是全局变量才能存储这些值,并且,如果刷新页面,当然会丢失复选框的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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