2

Hi i'm using jQuery in my asp.net mvc application, in this i have created some checkboxes like

$("#dvModules").append('<input type="checkbox" id=Module_' + jsModulesData[ctr].Code + ' name="' + jsModulesData[ctr].Name + '" value="' + jsModulesData[ctr].Code + '"> ' + jsModulesData[ctr].Name + '
');

i checked some of them and stored its values in database, when i enter it to this page again, i got the values from the database, but i could not check the corresponding checkboxes with their values my code is below:

var arrModuleIDs = SelectedModuleIDs.split(',');

$(document).ready(function () {
    SelectedModuleIDs = '@ViewBag.SelectedModuleIDs';
    var arrModuleIDs = SelectedModuleIDs.split(',');

    for (var i = 0; i < arrModuleIDs.length; i++) {
        $("#Module_" + arrModuleIDs[i] + "").attr('checked', true);
         //Here the arrmoduleIDs is the values from database.
    }

here the loop is performing well but the checkbox is not checked, can anyone help me to resolve this.

2
  • 1
    Does "#Module_" + arrModuleIDs[i] generate a valid selector, i.e. is it selecting an element? Do some basic debugging... since we don't have an example of the value of the selector or the HTML, you have to do this on your own. Also try to use .prop instead of .attr. Commented May 14, 2012 at 9:38
  • Hiya, what you are doing is correct see here : jsfiddle.net/azEXJ attr('checked',true) should be fine. Might be better context around this might help us to help you! Commented May 14, 2012 at 9:42

1 Answer 1

1
    $(document).ready(function () {
        //            $.each(('@ViewBag.SelectedModuleIDs').split(','), function (i, value) {
        //                $('#dvModules').find("#Module_" + value + "").attr('checked', true);
        //            });

        $.each(('4,3,6,7').split(','), function (i, value) {
            $('#dvModules').find("#Module_" + value).attr('checked', true);
        });
    });

<div id="dvModules">
    <input type="checkbox" id="Module_1" value="1" />1<br />
    <input type="checkbox" id="Module_2" value="2" />2<br />
    <input type="checkbox" id="Module_3" value="3" />3<br />
    <input type="checkbox" id="Module_4" value="4" />4<br />
    <input type="checkbox" id="Module_5" value="5" />5<br />
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

can u shoe me the code jsModulesData[ctr]? u r using jquery ajax?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.