Checkbox checked according to string

Asked

Viewed 209 times

1

I have a string in the format ["0,1,0,1,0,1,0,0"]. Where 1 is checked and 0 is unchecked. I also have a grid where I still have a checkbox at the first Oluma. I need to mark the checkboxes according to my string. I tried at first using Javascript, but could not.

C# :

 protected void Page_Load(object sender, EventArgs e)
{
Session["Checados"] = Checados;
.
.
.
}

JS and Aspx:

 <div class="CentralizarGrid">
    <asp:GridView ID="_gvPontoParada" CssClass="table table-striped grid-table" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="None" OnDataBound="_gvPontoParada_DataBound" >
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"/>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Código" DataField="Codigo" />
            <asp:BoundField HeaderText="Descrição" DataField="Descricao" />
            <asp:BoundField HeaderText="Endereço" DataField="Endereco" />

        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>
</div>
 .
 .
 .

  <script type="text/javascript">
    var Checados='<%= (Session["Checados"].ToString())%>';
    var check= Checados.split(",");


    function verifica(chk) {
        for(var i = 0; i < check.length; i++)
        {
            if (check[i] == "0")
            {
                document.getElementById(chk).checked = false;
            } else if (check[i] == "1")
            {
                document.getElementById(chk).checked = true;
            }
         }
    }

Thanks for the help!!

1 answer

1


Since you are getElementById and you are not iterating over the various checkbox what happens is that the checkbox will always have the value equal to the last element of the Checkados vector of your example, your code would have to be in the following logic:

$(document).ready(function(){
    var i = 0;

    var Checados='<%= (Session["Checados"].ToString())%>';
    var check= Checados.split(","); 

    $('input[type=checkbox]').each(function () {
         $(this).prop('checked',check[i] == '1' ? true : false); 
         i+=1;
     });
 });

In this example Voce traverses all imputs of the checkbox type setting them to true if the position of the equivalent vector is equal to 1, otherwise false.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.