mercredi 30 septembre 2015

Disabling checkbox in mvc does not submit values to database

Is it that if a checkbox is disabled, the value does not get submitted to the database? I have disabled a checkbox so that even if the user does not enter any values in the rest of the form, atleast one value will be submitted. But when I click on the submit button there is no entry in the database. Please Help

<table class="table-bordered">
<tr>
    <td colspan="2">
        @Html.CheckBoxFor(m => m.isUsed, new { @disabled="disabled"})
    </td>
</tr>
<tr>
    <td>
        @Html.TextBoxFor(m => m.FirstName, @Model.isUsed ? (object)new { @class = "form-control" } : new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.FirstName)
    </td>
</tr>




Is it possible to include check box "true" attribute within hyperlink?

We are using integrated authentication; however one of our websites requires the user to check a box to enable/acknowledge Integrated Authentication, then click a "login" button.

I'd like to streamline our users experience by providing them with a direct link which would already include the IntegratedAuthentication checkbox as being checked.

Is this possible?

The data field input name and id is "IntegratedAuthentication" The primary page link is "https://website/account/LogIn" I've tried adding variances of the following to the primary page link with no success:

https://website/account/LogIn?_eventid=&IntegratedAuthentication=1
https://website/account/LogIn?_eventid=IntegratedAuthentication=true




Gridview that is bound to sqldatasource in edit mode is not updating a checkbox column in rowupdating event

I am using c# and VS 2008. My GridView has several cells but only one cell ("Active", boolean) with a checkbox TemplateField is not updating in Edit mode when Update button is clicked. I have specified 2 primary keys as DataKeyNames in GridView1 properties. I am using rowupdating event to pass the desired checkbox (bit)value to sqldatasource. Is there another event I am missing in order to make the update happen? Again, all other cells update just fine.

I did a lot of research before posting here and I still couldn't see where my mistake is. I only included pertinent parts of the code (gridview properties, the one field in question

ASPX

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
                    AutoGenerateColumns="False" 
                    AutoGenerateEditButton="True" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" 
                    DataSourceID="sqldatasource1" 
                    onrowcancelingedit="GridView1_RowCancelingEdit" 
                    onrowediting="GridView1_RowEditing" 
                    onrowupdating="GridView1_RowUpdating" 
        DataKeyNames="ID,CertID" ondatabound="GridView1_DataBound" 
        onrowcreated="GridView1_RowCreated" 
        onrowdatabound="GridView1_RowDataBound">
    <Columns>

 <asp:TemplateField HeaderText="Active" SortExpression="Active">
            <EditItemTemplate>
                <asp:CheckBox ID="cbActiveEdit" runat="server" 
                    Text='<%# Convert.ToBoolean(Eval("Active").ToString().Equals("Yes")) %>'
                    Checked='<%# Convert.ToBoolean(Eval("Active").ToString().Equals("Yes")) %>'
                    Enabled="True" 
                    AutoPostBack="false"></asp:CheckBox> 

                </EditItemTemplate>
            <ItemTemplate>
                <asp:Label  ID="lblActive" runat="server" Text='<%# Convert.ToBoolean(Eval("Active").ToString().Equals("Yes")) %>' Enabled="false"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

  <asp:SqlDataSource ID="sqldatasource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:SomeConnectionString %>" 
        SelectCommand="SelectRecords" 
        SelectCommandType="StoredProcedure" 
        UpdateCommand="UpdateRecords" 
        UpdateCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="ddlvwRecords" Name="ID" 
                PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="ID" Type="Int32" />
            <asp:Parameter Name="CertID" Type="Int32" />
            <asp:Parameter Name="CertNumber" Type="String" />
            <asp:Parameter Name="DueBy" Type="DateTime" />
            <asp:Parameter Name="Completed" Type="DateTime" />
            <asp:Parameter Name="Expires" Type="DateTime" />
            <asp:Parameter Name="Renewed" Type="DateTime" />
            <asp:Parameter Name="Comments" Type="String" />
            <asp:Parameter Name="PeriodEffective" Type="String" />
            <asp:Parameter Name="CeuEarned" Type="String" />
            <asp:Parameter Name="Active" Type="Boolean" />
        </UpdateParameters>
    </asp:SqlDataSource>

C#

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   try
    {

    //Get the new values to Update
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

    CheckBox cb = (CheckBox)GridView1.Rows[e.RowIndex].FindControl("cbActiveEdit");

    string strActiveStatus;

    if (cb != null && cb.Checked == true)  
        {   
            strActiveStatus = "1";
        }
        else
        { 
            strActiveStatus = "0";
        } 
    sqldatasource1.UpdateParameters["Active"].DefaultValue = GetStatus(strActiveStatus).ToString();//GetStatus is returning “true” or “false”
    sqldatasource1.Update();

    //Reset the edit index.
    GridView1.EditIndex = -1;

    //Bind data to the GridView control.
    GridView1.DataBind(); 

    }//end try

    catch (SqlException ex)
    {
        //handle error here 
    }  

}

 protected bool GetStatus(string str)
{
    if (str == "1")
    {
        return true;
    }
    else
    {
        return false;
    }
}




How can I check checkboxes (or not) based on the value of a field in a Document (Meteor)?

I need to read values from a MongoDB Collection and then check (or not) the checkboxes in a Meteor Template based on a field in the Document which matches the value of a checkbox.

To take a step back first, I populate the Template with the checkboxes like so:

<div id="seljoblocs" name="seljoblocs">
  {{#each jobLocs}}
    <input type="checkbox" value={{jl_jobloc}}><label>{{jl_jobloc}}</label>
  {{/each}}
</div>

...populating the value and the label from the Template's "jobLocs" Helper:

jobLocs: function() {
  return JobLocations.find({}, {
    sort: {
      jl_jobloc: 1
    },
    fields: {
      jl_jobloc: 1
    }
  });
}

When a selection is made from a "worker" input select element, I can note which worker was selected like so:

Template.matchWorkersWithJobLocs.events({
    'change #selworker': function(event, template) {
        var workerid = template.find('#selworker').value;
        // TODO: Add code to query Collection and then check the appropriate checkboxes
    },

...so that I can check the checkboxes where matches are found (a "match" means that the worker is qualified to be assigned to the job/location). IOW, with the returned Document field value (jobloc), I want to check the appropriate checkboxes.

My question is, how I can do that?

Is it the case (hopefully!) that, within the following SpaceBars loop:

{{#each jobLocs}}
  <input type="checkbox" value={{jl_jobloc}}><label>{{jl_jobloc}}</label>
{{/each}}

...I can have an "isChecked" helper like this:

{{#each jobLocs}}
  <input type="checkbox" value={{jl_jobloc}} {{isChecked}}><label>{{jl_jobloc}}</label>
{{/each}}

...that either returns an empty string or the string "checked" based on whether this Meteor method returns true:

Template.matchWorkersWithJobLocs.helpers({
    isChecked: function () {
    var workerid = $('#selworker').val;
    if (null == WorkersJobLocsLookup.findOne( {wjllu_workerid: workerid, wjllu_jobloc: jobLocs.jl_jobloc})) {
        return '';
    } else {
        return 'checked';
    }
}

That way, the checkbox will be checked (because the function returns "checked", which checks the checkbox) or not, because the function returns an empty string.

IOW, to get to the nitty gritty, is the "jobLocs.jl_jobloc" field from the Spacebars loop available/accessible within the helper, so that I can see if it has a corresponding Document in the WorkersJobLocsLookup Collection?




Checkboxes on a Materialize table implemented in Meteor JS

My question is in 2 parts.

I would like to add a checkbox to a table. What's the best way to do that?

Secondly, I would like to have all checkboxes selected when the top most checkbox is selected, and to have all the checkboxes de-selected when the top most checkbox is clicked again. However, the user should also be able to select a few items on the checkbox; if they choose to do so.




image checkbox label button needs to work

I need the menu to slide down when the .logo (bird) image button is clicked

PS: the menu slides down when the .toggle (3 line button) is clicked BUT I need the menu to slide down when the .logo (bird) image is clicked

/* ------------------------------------------ */
/* BASIC SETUP */
/* ------------------------------------------ */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.page-wrap {
    width: 1216px;
    margin: 0 auto;
}

.row-basic {
    max-width: 1216px;
}

html,
body {
    text-align:justify
    color: #fff;
    font-size: 19px;
    text-rendering: optimizeLegibility;
    background: #333;
    background-position: center;
    height: 100vh;
    background-attachment: fixed;
}

/* ------------------------------------------ */
/* HEADER */
/* ------------------------------------------ */

header {
    background-color: rgba(246, 149, 149, 0.06);
    height: 81px;
    width: auto;
    padding-top: 24px;
    margin-top: 26px;
    margin-bottom: 0px;
    display:flex;
    justify-content: space-between;
}

/* ----- NAVIGATION -----*/

nav {
    display:flex;
    align-items: center;
}

nav ul {
    display:flex;
}

.user-tools {
    display:flex;
    align-items: center;
}

.user-tools :focus {
    outline:none;
}

/* ----- LOGO -----*/

.logo {
    cursor: pointer;
    height: 68px;
    width: auto;
    margin-right: 21px;
    margin-left: 31px;
}

/* ----- MENU BUTTON -----*/

.mobile-nav-toggle {
    height: 50px;
    width: 35px;
    margin-right: 31px;
    display: flex;
    align-items: center;
    cursor: pointer;
}

.mobile-nav-toggle span,
.mobile-nav-toggle span::before,
.mobile-nav-toggle span::after {
    border-radius: 2px;
    content: "";
    display: block;
    height: 6px;
    width: 100%;
    background: #fff;
    position: relative;
}

.mobile-nav-toggle span::before {
    top: 11px;
}

.mobile-nav-toggle span::after {
    bottom: 17px;
}

/* ------------------------------------------ */
/* PAGE CONTENT TOP BAR */
/* ------------------------------------------ */
    
.box1 {
    height: 26px;
    width: 300px;
    background: #8242b1;
}    
    
.box2 {
    height: 26px;
    width: 300px;
    background: #b14242;
}     
    
.box3 {
    height: 26px;
    width: 300px;
    background: #424bb1;
}      

.page-content {
    display:flex;
    justify-content: center;
    transition: all 0.3s ease-in-out 0s;
    position:relative;
    margin-top: -260px;
    z-index: 0; }
    
.toggle {
    transition: all 0.3s ease-in-out 0s;
    text-decoration: none;
    font-size: 30px;
    color: #eaeaea;
    position:relative;
    top: -225px;
    left: 20px;
    z-index: 1; }
    .toggle:hover  {
        color:#cccccc; }

.topbar {
    display:flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease-in-out 0s;
    position: relative;
    top: -220px;
    bottom: 0px;
    left: 0px;
    height: 220px;
    width: auto;
    padding: 30px;
    background: #333;
    z-index: 1; }
    .topbar li {
        display:flex;
        justify-content: center;
        list-style: none;
        color: rgba(255, 255, 255,0.8);
        font-size: 16px;
        margin-bottom: 16px;
        cursor: pointer; }
        .topbar li:hover {
            color: rgba(255, 255, 255,1); }

#topbartoggler {
  display: none; }
  #topbartoggler:checked + .page-wrap .topbar {
    top: -4px; }
  #topbartoggler:checked + .page-wrap .toggle {
    top: -5px; }
  #topbartoggler:checked + .page-wrap .page-content {
    padding-top: 220px; }
<body>


<input type="checkbox" id="topbartoggler" name="" value="">    
    
<div class="page-wrap"> 
    
    <div class="topbar">
        <ul>
            <li>Home</li>
            <li>Projects</li>
            <li>Clients</li>
            <li>Blog</li>
            <li>Contact</li>
        </ul>
    </div>
    
    <label for="topbartoggler" class="toggle" class="mobile-nav-toggle">☰</label>
    
    <div class="page-content">
        <div class="box1"></div>            
        <div class="box2"></div>            
        <div class="box3"></div>            
    </div>
    
    <header class="row-basic">
        <nav>
            <img src="http://ift.tt/1gUqgD4" alt="logo" class="logo">
        </nav>
        <div class="user-tools">
            <div class="toggle"></div>
            <div class="mobile-nav-toggle">
                <span></span>
            </div>
        </div>
    </header>
  
</div>
    
</body>



Uncheck checkboxes on a subform

I am a beginner with access database. I am building a database for supplies. I have a form with a subform query. The query has checkboxes on it. When the user selects the checkbox they are choosing what supplies they need. They will press a request command button which will open a confirmation window that displays the items they chose (another query). I would like for when they press the request button that the checkboxes clear on the subform query. I have tried several different ways of coding this with no luck. I don't know SQL very well and have been trying to do everything with VBA in the event codes. Can anyone help me out and point me in the right direction.




How to compare two products using checkbox and button?

Code below add checkboxes and buttons to all products listed from database.

How can I compare two products when two checkboxes must be checked and then button should be clickable(button is disabled when none product is checked) and redirect to another page and show these two products with their specifications?

This must be probably done with some query on usporedi.php page, but the problem are checkboxes and button. When button isn't disabled it redirects to usporedi.php.

I've tried with some scripts, but they didn't work.

I appreciate any help.

<?php
                    
                    $per_page = 10;
                   
                    if (!isset($_GET['page'])) {
                        $page = 1;
                    } else {
                        $page = $_GET['page'];
                    }

                    
                    if ($page <= 1) {
                        $start = 0;
                    } else {
                        $start = $page * $per_page - $per_page;
                    }

                   
                    $query = "SELECT *, FORMAT(cijena,2,'de_DE') FROM artikli WHERE kategorija='laptop'";

                   
                    $num_rows = mysqli_num_rows(mysqli_query($con, $query));

                   
                    $num_pages = ceil($num_rows / $per_page);

                   
                    $query .= " LIMIT $start, $per_page";

                  
                    $result = mysqli_query($con, $query);
                    while ($row = mysqli_fetch_array($result)) {

                        $id = $row ['id'];

                        print
                                "<div id='proizvod'></br><a style='text-decoration:none; color:black;' class='two' href='proizvod.php?id=$id' >" . $row["naziv"] . "" .
                                "<p><img src=" . $row["slika"] . " width='200px' height='200px' style='border-radius: 15px;'></p>" .
                                "<p> Cijena za gotovinu: " . $row["FORMAT(cijena,2,'de_DE')"] . " KN </p>" .
                                "<pre id='pre1'>" . $row["opis"] . "</pre>" .
                                "</a>

**<input type='checkbox' name='Usporedi'>
<button onclick='usporedi()' name='Usporedi' disabled>Usporedi</button>

                    <script>
                    function usporedi(){
                       window.location='usporedi.php';
                    }
                    
                    </script>**
</div>";
                    }
                    ?>



Primefaces - How to call method on ticking the SelectAll checkbox in dataTable through ajx

I need your help in calling a method from a backing bean once I ticked the SelectAll checkbox at the top of a dataTable. I am able to call the method ShowTotal once I ticked or unticked the checkbox of each individual item, however when I tick the SelectAll checkbox from the top, no listener is called. Here is my code:

<p:dataTable id="PendingRequests" var="hr" selection="#{hrdirector.selectedRequests}"
             value="#{hrdirector.listPendingRequests}" rowKey="#{hr.requestNo}"
             filteredValue="#{hrdirector.filteredRequests}" widgetVar="dataTableWidgetVar">
  <p:ajax event="rowSelectCheckbox" listener="#{hrdirector.ShowTotal}" process="@this" 
          update=":form:PendingRequests:sum"/>

  <p:ajax event="rowUnselectCheckbox" listener="#{hrdirector.ShowTotal}" process="@this"
          update=":form:PendingRequests:sum"/>

        <p:column selectionMode="multiple" style="width:16px;text-align:center"></p:column>
        <p:column headerText="Request No.">
            <h:outputText value="#{hr.requestNo}"/>
        </p:column>
        <p:column headerText="Request Amount">
            <h:outputText value="#{hr.requestAmount}"/>
        </p:column>
    </p:dataTable>

    <h:outputText id="Sum" value="#{hr.Sum}"/>

I tried to add the below code in the column which it has the selection, but it gave me an error:

<p:column selectionMode="multiple" style="width:16px;text-align:center">
<p:ajax listener="#{hrdirector.ShowTotal}" />
</p:column>




How to check if a checkbox is checked or not

I have 2 checkboxes and in my controller i want to be able to know if those checkboxes are checked or not. My code :

in .h :

@property (weak, nonatomic) IBOutlet Checkbox *option1Button;
@property (weak, nonatomic) IBOutlet Checkbox *option2Button;

in controller.m:

- (IBAction)optionButton1Pressed:(id)sender {
   NSLog(@"first : %lu second : %lu", (unsigned long)[_option1Button state], (unsigned long)[_option2Button state]);
}

- (IBAction)optionButton2Pressed:(id)sender {
   NSLog(@"first : %lu second : %lu", (unsigned long)[_option1Button state], (unsigned long)[_option2Button state]);
}

The action mapped is "touch up inside". And what i can see in the logs is that state is always 1 if i check or uncheck the checkboxes. Everytime that i click, it's a 1

I've tried with "editing changed" but it's never called

Any idea?




Qt Designer custom checkbox relative path

I am trying to make a Checkbox in Qt Designer that uses custom png images instead of the checkbox.

I do this by using a custom stylesheet with following content:

QCheckBox::indicator {
 width: 30px;
 height: 30px;
 }

QCheckBox::indicator:checked
{
 image: url(radio_selected.png);
}
QCheckBox::indicator:unchecked
{
  image: url(C:\\MYPROJECT\\subdirectory\\radio_unselected.png);
}

QCheckBox::indicator:checked:hover
{
  image: url(C:\\MYPROJECT\\subdirectory\\radio_selected.png);
}
QCheckBox::indicator:unchecked:hover
{
  image: url(C:\\MYPROJECT\\subdirectory\\radio_unselected.png);
}

The absolute paths using dual backslashes deliver the desired result. The relative path entry doesn't work. Neither does

QCheckBox::indicator:checked
{
 image: url(./radio_selected.png);
}

nor

QCheckBox::indicator:checked
{
 image: url(.\radio_selected.png);
}

nor

QCheckBox::indicator:checked
{
 image: url("radio_selected.png");
}

nor

QCheckBox::indicator:checked
{
 image: url(file:///radio_selected.png);
}

or anything else that i've tried... what am I missing here?




How to check if a checkbox is checked or unchecked using JavaScript? What is wrong in my code?

I am pretty new in JavaScript and I have the following problem. Into a JSP page I have something like this:

<tbody>
    <c:forEach items="${listaProgetti.lista}" var="progetto" varStatus="itemProgetto">
        <tr id='<c:out value="${progetto.prgPro}" />'>
            <td><input type="checkbox" class="checkbox" onchange="changeCheckbox(this, <c:out value="${progetto.prgPro}" />)"></td>
            .....................................................
            .....................................................
            .....................................................
        </tr>
    </c:forEach>
</tbody>

So, as you can see, clicking on the checkbox it is call this changeCheckbox() that have to discover if the clicked checkbox is checked or unchecked after the click event.

So I am trying to do something like this:

function changeCheckbox(elem, idRow) {
    alert("INTO changeCheckbox()");

    var checkedRowList = new Array();

    alert(idRow);   // Rappresenta il progetto attualmente selezionato
    //alert(elem);

    if(this.checked) {
        alert("CHECKED");
    } else {
        alert("UNCHECKED");
    }
}

So as you can see the first parameter passed to the changeCheckbox() function is the this object that should repreent the clicked input tag that represent a checkbox (correct me if it is a wrong assertion).

So into the script I try to check if the checkbox is checked or unchecked by if(this.checked) but it can't work

The problem is that when I check a checkbox don't enter in the body of the previous if but enter every time in the body od the else.

Why? What is wrong? What am I missing? How can I solve this issue?

Tnx




How to use javascript to filter table rows based on multiple sections of checkboxes

I have the following checkboxes in a form that allows me to show/hide rows in a table. Each section of checkboxes works fine, but how do I make one section check the status of the other section of checkboxes, so the logic filters based on all selections?

I hope you can see what I am trying to do based on my snippet of sample data:

$(document).ready(function() {
  $("#type :checkbox").click(function() {
    $("td").parent().hide();
    $("#type :checkbox:checked").each(function() {
      $("." + $(this).val()).parent().show();
    });
  });
  $("#fee :checkbox").click(function() {
    $("td").parent().hide();
    $("#fee :checkbox:checked").each(function() {
      $("." + $(this).val()).parent().show();
    });
  });
});
<script src="http://ift.tt/1qRgvOJ"></script>

<form name="repaymentcalc" id="myForm" action="">


  <section id="type">

    <p id="Mortgage Type">Mortgage Type</p>
    <input type="checkbox" name="type" value="t2" id="t2" checked/>2yr Fixed
    <br>
    <input type="checkbox" name="type" value="t3" id="t3" checked/>3yr Fixed
    <br>
    <input type="checkbox" name="type" value="t5" id="t5" checked/>5yr Fixed
    <br>

  </section>

  <section id="fee">

    <p id="Fee">Fee</p>
    <input type="checkbox" name="fee" value="fee" id="fee" checked/>Fee
    <br>
    <input type="checkbox" name="fee" value="nofee" id="nofee" checked/>No Fee
    <br>

  </section>

</form>

<table id="mortgagetable">

  <tbody>

    <tr class="product">
      <td class="t2">2yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="fee">999</td>
    </tr>
    <tr class="product">
      <td class="t3">3yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="fee">999</td>
    </tr>
    <tr class="product">
      <td class="t5">5yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="fee">999</td>
    </tr>
    <tr class="product">
      <td class="t2">2yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="nofee">no fee</td>
    </tr>
    <tr class="product">
      <td class="t3">3yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="nofee">no fee</td>
    </tr>
    <tr class="product">
      <td class="t5">5yr Fixed</td>
      <td class="initialrate">1.29</td>
      <td class="nofee">no fee</td>
    </tr>

  </tbody>

</table>



Two dimensial array. Multiple selection dropdown

I have a php form that has a known number of columns (4) and unknown number of rows. In that form I use single selection dropdown, free input text, radio and multiple selection dropdown.

            <table>
            <tr>
                <td><b>Single selection dropdown</b></td>  
                <td><select  name="row[0][column_1]" >
                    <option></option>
                    <option>Selection 1</option>
                    <option>Selection 2</option>
                    <br />
                </select> </td>

                <td><b>Free text</b> 
                    <input type="text" name="row[0][column_2]" placeholder="Free text">  </td>   
                <td><b>Radio</b> 
                    <input type="radio" value="ja" name="row[0][column_3]">Ja
                    <input type="radio" value="nein" name="row[0][column_3]">Nein
                </td>   

                <td>
                    <select multiple="multiple"  name="row[0][column_4[]]">
                        <option value="k80">K80</option>
                        <option value="k50">K50</option>
                        <option value="hitch">Hitch</option>
                        <option value="zugpendel">Zugpendel</option>
                        <option value="Piton-Fix">Piton-Fix</option>

                    </select>
                </td>
            </tr>
        </table>

At the moment everything work as expected but I cannot get data from multiple selection dropdown.

$row = $_POST['row'];
 echo '<table>';
 foreach ( $_POST['row'] as $val)
 {
    echo '<tr>';
    echo '  <td>', $val['column_1'], '</td>';
    echo '  <td>', $val['column_2'], '</td>';
    echo '  <td>', $val['column_3'], '</td>';


     if (!empty($val['column_4'])){
        foreach((array) $val['column_4'] as $key){
            echo '  <td>', $key , '</td>';
        }
     }
    echo '</tr>';
}
echo '</table>';

I guess at some point $val['column_4'] is empty or not an array at all.




c# HeaderCheckbox in datagridview strange behaviour

I have got a header checkbox for SelectAll in my checkboxColumn of my datagridview

    private void AddSelectAllCheckBox(DataGridView theDataGridView)
    {
        CheckBox cbx = new CheckBox();
        cbx.Name = "SelectAll";
        //The box size
        cbx.Size = new Size(14, 14);

        Rectangle rect = default(Rectangle);
        rect = theDataGridView.GetCellDisplayRectangle(0, -1, true);
        //Put CheckBox in the middle-center of the column header.
        cbx.Location = new System.Drawing.Point(rect.Location.X + ((rect.Width - cbx.Width) / 2), rect.Location.Y + ((rect.Height - cbx.Height) / 2));
        cbx.BackColor = Color.White;
        theDataGridView.Controls.Add(cbx);

        //Handle header CheckBox check/uncheck function
        cbx.Click += HeaderCheckBox_Click;
        //When any CheckBox value in the DataGridViewRows changed,
        //check/uncheck the header CheckBox accordingly.
        //theDataGridView.CellValueChanged += DataGridView_CellChecked;
        //This event handler is necessary to commit new CheckBox cell value right after
        //user clicks the CheckBox.
        //Without it, CellValueChanged event occurs until the CheckBox cell lose focus
        //which means the header CheckBox won't display corresponding checked state instantly when user
        //clicks any one of the CheckBoxes.
        theDataGridView.CurrentCellDirtyStateChanged += DataGridView_CurrentCellDirtyStateChanged;
    }

    private void HeaderCheckBox_Click(object sender, EventArgs e)
    {
        this._IsSelectAllChecked = true;

        CheckBox cbx = default(CheckBox);
        cbx = (CheckBox)sender;

        foreach (DataGridViewRow row in metroGrid1.Rows)
        {

            row.Cells[0].Value = cbx.Checked;

        }

        metroGrid1.EndEdit();

        this._IsSelectAllChecked = false;
    }



    //The CurrentCellDirtyStateChanged event happens after user change the cell value,
    //before the cell lose focus and CellValueChanged event.
    private void DataGridView_CurrentCellDirtyStateChanged(System.Object sender, System.EventArgs e)
    {
        DataGridView dataGridView = (DataGridView)sender;
        if (dataGridView.CurrentCell is DataGridViewCheckBoxCell)
        {
            //When the value changed cell is DataGridViewCheckBoxCell, commit the change
            //to invoke the CellValueChanged event.
            dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }

This is working fine.

If I check or uncheck the Checkbox in its row this event is fired and works:

        private void metroGrid1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex > -1)
        {
            //listBox1.Items.Add(" -> ");
            DataGridView dgv = sender as DataGridView;
            if (dgv == null)
                return;
            //if (dgv.CurrentRow)
            //{
                if (Convert.ToBoolean(dgv.CurrentRow.Cells[Sel.Name].Value) == true)
                {
                    int selCount = Int32.Parse(metroLabel5.Text);
                    int addCount = selCount + Int32.Parse(dgv.CurrentRow.Cells[Jobs.Name].Value.ToString());
                    metroLabel5.Text = addCount.ToString();
                    //listBox1.Items.Add(dgv.CurrentRow.Index.ToString() + " -> " + dgv.CurrentRow.Cells[Jobs.Name].Value.ToString());

                }
                if (Convert.ToBoolean(dgv.CurrentRow.Cells[Sel.Name].Value) == false)
                {
                    int selCount = Int32.Parse(metroLabel5.Text);
                    int minCount = selCount - Int32.Parse(dgv.CurrentRow.Cells[Jobs.Name].Value.ToString());
                    metroLabel5.Text = minCount.ToString();
                   // listBox1.Items.Add(dgv.CurrentRow.Index.ToString() + " -> " + dgv.CurrentRow.Cells[Jobs.Name].Value.ToString());
                }
            //}
        }
    }

    private void metroGrid1_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex > -1)
        {
            metroGrid1.EndEdit();
        }
    }

My problem: If I check or uncheck the headerCheckbox the CellValueChanged Event is fired for each row which is ok, but it always uses the first row for the event.

For Example: I have 8 rows with jobs 1,2,3,4,5,6,7,8 so the metrolabel1.text should be 36 if all are selected, but with the selectAll checkbox it goes to 8 (8 time row 0 with 1 jobs)




Make checkbox selected on the basis of some field parameter in grid Magento

Hi i have created a custom grid using a silksoftware.which works fine. Now i need to make the check-box selected on the basis of some condition.Like say if i have a collection of 10 entries and i have selected 5 out of them and change there values with mass action. Now i need to show those 5 as selected in check-box. Can you please suggest me how can i do this.

My grid file is as below

class Iclp_Cusgrid_Block_Adminhtml_Cusgrid_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

        public function __construct()
        {
                parent::__construct();
                $this->setId("cusgridGrid");
                $this->setDefaultSort("cusgrid_id");
                $this->setDefaultDir("DESC");
                $this->setSaveParametersInSession(true);
        }

        protected function _prepareCollection()
        {
                $collection = Mage::getModel("cusgrid/cusgrid")->getCollection();
                $this->setCollection($collection);
                return parent::_prepareCollection();
        }
        protected function _prepareColumns()
        {
                $this->addColumn("cusgrid_id", array(
                "header" => Mage::helper("cusgrid")->__("ID"),
                "align" =>"right",
                "width" => "50px",
                "type" => "number",
                "index" => "cusgrid_id",
                ));

                $this->addColumn("region", array(
                "header" => Mage::helper("cusgrid")->__("region"),
                "index" => "region",
                ));
                $this->addColumn("regioncode", array(
                "header" => Mage::helper("cusgrid")->__("regioncode"),
                "index" => "regioncode",
                ));
            $this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV')); 
            $this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel'));

                return parent::_prepareColumns();
        }

        public function getRowUrl($row)
        {
               return $this->getUrl("*/*/edit", array("id" => $row->getId()));
        }



        protected function _prepareMassaction()
        {
            $this->setMassactionIdField('cusgrid_id');
            $this->getMassactionBlock()->setFormFieldName('cusgrid_ids');
            $this->getMassactionBlock()->setUseSelectAll(true);
            $this->getMassactionBlock()->addItem('remove_cusgrid', array(
                     'label'=> Mage::helper('cusgrid')->__('Remove Cusgrid'),
                     'url'  => $this->getUrl('*/adminhtml_cusgrid/massRemove'),
                     'confirm' => Mage::helper('cusgrid')->__('Are you sure?')
                ));
            return $this;
        }


}




mardi 29 septembre 2015

Checkbox checks even if 'false' provided from DTO

Having form like:

//defaults
$this->defaults = [
    'label' => false,
    'attr'  => [
        'autocomplete' => 'off',
    ],
];

//part of BuildForm()
->add('send_reminders', new CheckboxType, $this->defaults + [
    'required' => false,
    'data' => false,
])

DTO like:

(other fields)

/** @var bool */
pivate $sendReminders = true;

(getters and setters)

and custom form view like:

<div class="form-group">
    <label class="accept-terms">
        <input type="checkbox" id="{{ form.send_reminders.vars.id }}" name="{{ form.send_reminders.vars.full_name }}" {{ form.send_reminders.vars.value == 1 ? 'checked' : '' }}/>
        &nbsp;{{ 'visit_booked_phone_confirmation'|trans }}
    </label>
</div>

I use above for Foo entity creation and edition, by hydrating DTO.

I have following problem: While in entity creation, checkbox works just fine - it is checked by default, if user unchecks it, false is provided to DTO. If there are form errors from other fields and form is reloaded, checkbox remains unchecked.

While in entity edition, even if there's false in DTO, checkbox comes checked. I thought that I have problem with my custom form rendering twig, but I checked checkbox value:

{{ dump(form.send_reminders.vars.value) }} //returns "1"

I tried setting various attributes to form field, like required, data, empty_data and so on, nothing works. What am I doing wrong?




keeping check box checked after submiting the form

i have problem guys to keep the checkbox checked after submiting the form , i tried this code but its not working can you please some body hep me and tell me whats exactly wrong with it ,plus i do believe there must be an array created but not really sure howand where to set the array in my file.

<P>
         <label for ='product'>product</label>
            milk<input type='checkbox' name='optional[]' value='milk' id='milk'/>
            <?php
            if(isset($_POST['optional']) && in_array('milk',$_POST['optional'])) echo "checked='checked'";
            ?> 
            butter<input type='checkbox' name='optional[]' value='butter' id='butter'/> 
            <?php
            if(isset($_POST['optional']) && in_array('butter',$_POST['optional'])) echo "checked='checked'";
            ?> 
            cheese<input type='checkbox' name='optional[]' value='cheese' id='cheese'/>
            <?php
            if(isset($_POST['optional']) && in_array('cheese',$_POST['optional'])) echo "checked='checked'";
            ?> 



Persist checkbox in gridview while custom paging

I have a created a gridview and added a checkbox in item template. This grid has few columns along with DataKey (primary key). Due to performance gain, this grid will fetch the next set of recrods on each page change based on the page number click. So that is done.

Now when user selects a checkbox in page one and then go to page 2 and coming back to page one, then user will not see the checkbox checked as the user did earlier.

So is there a good way to persist the checkbox when user move page to page?

This checkbox be used as a flag to select the rows that can be deleted later by a button outside the grid.




Display message upon Switch button toggle

I am using Bootstrap Switch to turn my check-box in toggle switches.

Now I want to display different messages based on whether the switch is ON or OFF. Sounds simple enough...but I can't seem to make it work :(

My HTML:

<div class="approve-delivery">
  <label for="config-email" class="control-label col-xs-5">
    Do you want to send out email?
  </label>
  <input type="checkbox" id="config-email" onclick="ToggleSwitchMessage('config-email', 'enable-msg', 'disable-msg')" checked/>
</div>

<div class="email-config-msg">
  <p id="enable-msg">
      All emails will be sent.
  </p>
  <p id="disable-msg">
      No email will be sent.<br/>
      Please remember, you must turn email ON again if you want emails to
      be sent during this login session.
  </p>
</div>

And my jQuery:

function ToggleSwitchMessage(checkId, firstCommentId, secondCommentId) {
  var check_box = document.getElementById(checkId)
  var first_alert = document.getElementById(firstCommentId);
  var second_alert = document.getElementById(secondCommentId);

  if (check_box.checked == true) {
    first_alert.style.visibility = "visible";
    first_alert.style.display = "inline-block";
    second_alert.style.visibility = "hidden";
    second_alert.style.display = "none";
  } else {
    first_alert.style.visibility = "hidden";
    first_alert.style.display = "none";
    second_alert.style.visibility = "visible";
    second_alert.style.display = "inline-block";
  }
}

Here is my working JSFiddle

Again, this is what I'm trying to do:

  • based on the check-box checked/unchecked, the proper message should be displaying on the page when it loads
  • then if the check-box's option is changed, it should display appropriate message

I hope I am making sense (English is not my first language)! Also I'm sorry if it's duplicate question, in that case please provide the URL of the Q/A(s).

Thank you in advance for your time and help!!




Display an image in place of a check mark with codeigniter

I found this code on here. Does anyone know if this would work with codeigniter. I want the ability for some to click on a image and perform the same function as a check box. After you click the image it would display a new image overlay that would be a check mark on top of the image.

Code I found.

input[type=checkbox] {
    display: block;
    width: 30px;
    height: 30px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-appearance: none;
    outline: 0;
}
input[type=checkbox]:checked {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://ift.tt/nvqhV5" xmlns:xlink="http://ift.tt/PGV9lw" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path id="checkbox-3-icon" fill="#000" d="M81,81v350h350V81H81z M227.383,345.013l-81.476-81.498l34.69-34.697l46.783,46.794l108.007-108.005 l34.706,34.684L227.383,345.013z"/></svg>');
}
input[type=checkbox]:not(:checked) {
    background-image: url('data:image/svg+xml;utf8,<svg version="1.1" xmlns="http://ift.tt/nvqhV5" xmlns:xlink="http://ift.tt/PGV9lw" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"> <path id="checkbox-9-icon" d="M391,121v270H121V121H391z M431,81H81v350h350V81z"></path> </svg>');
}
<input type="checkbox" id="check" />
<div></div>



How to set checkbox always checked when user redirect to another page?

How do I implement my checkbox to stay check as it is even if user redirects to another page? Example, in my code behind when I check the checkbox the system updates the database and it says "Validated" , but when I press GoBackTeacher_Click event it will redirect to another page. In that another page there is a button function there that will redirect to this current page where my code behind function is implemented and checkbox is checked.

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace SoftwareAnalysisAndDesign.SAD
{
    public partial class ValidateSubjectTeacher : System.Web.UI.Page
    {
        CheckBox check = new CheckBox();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ValidateSubject"] == null)
            {
                Response.Redirect("TeacherPage.aspx", true);
            }

            if (!IsPostBack)
            {
                ValidateSubject.DataSource = Session["ValidateSubject"];
                ValidateSubject.DataBind();
            }
            //Add a checkbox in the last row of GridView Progmatically
            foreach (GridViewRow row in ValidateSubject.Rows)
            {
                check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
                check.Enabled = true;
                check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
                check.AutoPostBack = true; //Set the AutoPostBack property to true
            }
        }
        protected void ValidateSubject_Click(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row

            string validated = "Validated";
            string notyetvalidated = "Not yet validated";
            string studid = grvRow.Cells[0].Text;
            string coursenum = grvRow.Cells[1].Text;

            if (chk.Checked)
            {
                grvRow.Cells[10].Text = validated;
                //Open Connection
                using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
                {
                    //Open Connection to database
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }

                    using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = @Validated where StudentID = @studentID and CourseNo = @Coursenumber" ,conn))
                    {
                        cmd.Parameters.AddWithValue("@Validated", validated);
                        cmd.Parameters.AddWithValue("@studentID", studid);
                        cmd.Parameters.AddWithValue("@Coursenumber", coursenum);
                        cmd.ExecuteNonQuery();
                    }

                    //Close Connection to database
                    try
                    {
                        conn.Close();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }
                }
            }
            else
            {
                grvRow.Cells[10].Text = notyetvalidated;
                //Open Connection
                using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
                {
                    //Open Connection to database
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }
                    //query database to update the Status
                    using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = @Validated where StudentID = @studentID and CourseNo = @Coursenumber", conn))
                    {
                        cmd.Parameters.AddWithValue("@Validated", notyetvalidated);
                        cmd.Parameters.AddWithValue("@studentID", studid);
                        cmd.Parameters.AddWithValue("@Coursenumber", coursenum);
                        cmd.ExecuteNonQuery();
                    }

                    //Close Connection to database
                    try
                    {
                        conn.Close();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }
                }
            }
        }
        protected void GoBackTeacher_Click(object sender, EventArgs e)
        {
            Response.Redirect("TeacherPage.aspx");
        }
    }
}

To further understand my question, here is an image to further explain it.

This is when I check the checkbox without pressing the go back button

enter image description here

And this where I go pressed the go back button and in the another page there is a proceed button to redirect to this current page where my gridview is located.

enter image description here

There the checkbox is unchecked, and the status says it is validated. How do I implement my code that checkbox stay checked?

Is it something to do with postback? Please help.




Why don't active contextual action bar when check the checkbox on the listview?

I want to show custom action bar when checkbox checked in listview. I wrote the one xml file type of menu like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://ift.tt/nIICcg" >

    <item
        android:id="@+id/delete"
        android:title="actionbar"
        android:icon="@drawable/recycle"/>

</menu>

I use for custom listview this codes:

private class Adapter_collection extends ArrayAdapter<String> {

public Adapter_collection(Context context, int resource, int textViewResourceId,
        String[] name_collection_tbl_collection) {
    super(context, resource, textViewResourceId, name_collection_tbl_collection);
}

@Override
public View getView(int position, View convertView,  ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.listview_items, parent, false);
    TextView txt_item_list_collection = (TextView)row.findViewById(R.id.textView_Item_Listview);
    CheckBox checkBox=(CheckBox)row.findViewById(R.id.checkBox_Item_Listview);

    checkBox.setTag(position);
    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {         
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked ) {   
            if (mActionmode!=null) {
                MyActionModeCallBack callBack = new MyActionModeCallBack();
                mActionmode = startActionMode(callBack);
            }

                //Toast.makeText(getApplicationContext(), buttonView.getTag().toString() , Toast.LENGTH_SHORT).show();      
        }
    });
    txt_item_list_collection.setText(name_collection_tbl_collection[position]);
    return row;
}

}

I add this class for use contextual action bar :

    private class MyActionModeCallBack implements ActionMode.Callback {

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.getMenuInflater().inflate(R.menu.actionbar_menu, menu);
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mActionmode = null;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // TODO Auto-generated method stub
        return false;
    }
}

Now When I check the checkboxes in listview , action bar don't changed . Please advice.




Using select all script for filtered table

I am using this (file here) script and i am using check all script in first row for my checkboxes. But first when I filtered for a column, this script selected checkboxes at hidden rows, too.

$(document).ready(function(){
$('#select_all').on('click',function(){
    if(this.checked){
        $('.checkbox').each(function(){
            this.checked = true;
        });
    }else{
         $('.checkbox').each(function(){
            this.checked = false;
        });
    }
});

$('.checkbox').on('click',function(){
    if($('.checkbox:checked').length == $('.checkbox').length){
        $('#select_all').prop('checked',true);
    }else{
        $('#select_all').prop('checked',false);
    }
});
});

Thanks for your helps.




Check / uncheck all Checkbox components in Inno Setup

I have long list of components which in turn calls a sub setup file to installs the selected components. All the components comes with check box which user can select and deselect. I need a check box at the top clicking which will Check/Uncheck all in the component list.

Can this be done ?

Thanks for reading




android checkbox is checked always true

I define a checkbox and assign no value to it. every time I clicked on it and print the value of checkbox, It shows true all The time. I put the result in preferences and then retrieve it. why is it always true?

public class CallAndSms extends Activity{
static SQLiteDatabase myDB= null;
static     Context context ;
static ListView lv;
static CallAndSmsAdaptor adapter;
static ArrayList<String> AllData= new ArrayList<String>();
CheckBox save;
static SharedPreferences preferences;
SharedPreferences.Editor editor=null;
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);





    setContentView(R.layout.sms_call);
     preferences = getSharedPreferences("modes",Context.MODE_PRIVATE);
     editor = preferences.edit();



    save= (CheckBox) findViewById(R.id.save);


    save.setChecked(preferences.getBoolean("save", true));



    context=this;


     save.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

            if ( save.isChecked()){
                Log.i("save save", save.isChecked()+"");

                  editor.putBoolean("save", true);

            }

            else 

                  {editor.putBoolean("save", false);}

            Log.i("pref", preferences.getBoolean("save", true)+"");


        }
    });


 }
 }




Can a checkbox be checked by default in the stylesheet, rather than in an inline css?

Like the title says: can a checkbox be checked by default in the stylesheet, rather than in an inline css?

Example from w3schools.com, the "car" box is checked:

<form action="demo_form.asp">
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
<input type="submit" value="Submit">
</form>

I'm making an "I agree to the Terms and Conditions" checkbox, and due to the clunky website I'm making this on, I can't create inline CSS. Instead, I can assign this field a css class, and edit the class in the larger stylesheet.

If it makes it easier, this will be the only checkbox on the page.




Update database when Button Event is click?

I can't update my database when my checkbox is checked and click the Validate Button. Note:(I use Session to my pass my Data page by page)

In this another code behind page, I add a column checkbox to my gridview.

   //Add a colum check row
    SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));

    Session["ValidateSubject"] = SubjectlistTable;

    Response.Redirect("ValidateSubjectTeacher.aspx");

In the ValidateSubjectTeacherPage:

This is the program Aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ValidateSubjectTeacher.aspx.cs" Inherits="SoftwareAnalysisAndDesign.SAD.ValidateSubjectTeacher" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title>Student Assessment Form</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="Bootstrap/css/bootstrap-theme.css" />
    <link rel="stylesheet" href="Bootstrap/css/bootstrap.min.css"/> 
    <link rel="stylesheet" type="text/css" href="Stylesheets/ValidateSubjectTeacherStyle.css"/>

    <!--Side bar link-->
    <link rel="stylesheet" href="SidebarBootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="SidebarBootstrap/css/simple-sidebar.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="headerwrapper">
            <div id="headercontent" class="jumbotron">
                <img id="img1" src="usjrlogo.png" />
                <h1 id="title">Online AppSess System</h1>
            </div>
        </div>

        <div class="container" style="text-align: center; margin: 0 auto;">
            <br />
            <h1>Validation of Subjects</h1>
            <br />
            <asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
        </div>

        <div style="float: right; padding-right: 75px;">
            <button type="button" runat="server" class="btn btn-primary" onserverclick="ValidateSubject_Click">Validate</button>
            <button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
        </div>
    </form>

    <script src="jquery/jquery.min.js"></script>
    <script src="Bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

Aspx Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace SoftwareAnalysisAndDesign.SAD
{
    public partial class ValidateSubjectTeacher : System.Web.UI.Page
    {
        CheckBox check = new CheckBox();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ValidateSubject"] == null)
            {
                Response.Redirect("TeacherPage.aspx", true);
            }

            if (!IsPostBack)
            {
                ValidateSubject.DataSource = Session["ValidateSubject"];
                ValidateSubject.DataBind();
            }
            //Add a checkbox in the last row of GridView Progmatically
            foreach (GridViewRow row in ValidateSubject.Rows)
            {
                check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
                check.Enabled = true;
                check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
                check.AutoPostBack = true; //Set the AutoPostBack property to true
            }
        }
        protected void ValidateSubject_Click(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row


            string validated = "Validated";
            string notyetvalidated = "Not yet validated";
            string studid = grvRow.Cells[0].Text;
            string coursenum = grvRow.Cells[1].Text;

            if (chk.Checked)
            {
                grvRow.Cells[10].Text = validated;
                //Open Connection
                using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
                {
                    //Open Connection to database
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }

                    using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = @Validated where StudentID = @studentID and CourseNo = @Coursenumber" ,conn))
                    {
                        cmd.Parameters.AddWithValue("@Validated", validated);
                        cmd.Parameters.AddWithValue("@studentID", studid);
                        cmd.Parameters.AddWithValue("@Coursenumber", coursenum);
                        cmd.ExecuteNonQuery();
                    }

                    //Close Connection to database
                    try
                    {
                        conn.Close();
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine(E.ToString());
                    }
                }

            }
            else
            {
                grvRow.Cells[10].Text = notyetvalidated;
            }
        }
        protected void GoBackTeacher_Click(object sender, EventArgs e)
        {
            Response.Redirect("TeacherPage.aspx");
        }
    }
}

The code is working but when I click the submit button, the system prompts me with an error and I can't update my database:

Error message:

An exception of type 'System.InvalidCastException' occurred in SoftwareAnalysisAndDesign.dll but was not handled in user code Additional information: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlButton' to type 'System.Web.UI.WebControls.CheckBox'.

There's something wrong with my checkbox event here:

CheckBox chk = (CheckBox)sender;

It seems that checkbox event and button event can't be simultaneously handled. Please help, this is the only problem I want to fix so that my System is fully working.

Related link Get specific data and update database




WPF Check box command to List or From List

I am new to WPF and not sure whether, whatever i am trying to do is possible or not.

I have checkbox as below :-

<CheckBox Name="cbAccess" Checked="cbAccess_CheckedChanged" Unchecked="cbAccess_CheckedChanged">Access To Save</CheckBox>

List as below :-

List<int> accessList = new List<int>();

if checkbox is checked then it should fire command 10 (int) and i will add the 10 in some list. and then unchecked then remove from list.

When first time window get loaded then checkbox will be checked or unchecked on the basis of commnad 10 exist in list or not.




Inserting a checkbox via jQuery stops the form to submit on webkit

I have a basic form with button and a checkbox inside it. The checkbox is loaded via jQuery like this:

jQuery('.markitfixed').prepend('<input type="checkbox" /> ');

When you click on the checkbox within the submit button (with class markitfixed), nothing happens on webkit browsers (Chrome, Safari...)

It works fine on Firefox.

To demonstrate this, open jFiddle demo and click on the checkbox.

What can I do to make it work on webkit browsers?




jQuery Isotope Checkbox Function Issue

I'm having trouble getting the checkbox function to work properly. When a child filter item is selected (i.e. classic-panel-doors), it should uncheck the filter parent (door-style-all). I've attached the HTML & JS. A 'working' example on CodePen is below.

HTML

<div class="container">
  <div class="row">

    <div class="col-xs-12 col-md-4">

      <h1>Categories</h1>

      <div id="options">

        <div class="option-set" data-group="door-style">
          <div class="checkbox">
            <label for="door-style-all"><input type="checkbox" value="" id="door-style-all" class="all" checked />door-style-all</label>
          </div>
          <div class="checkbox">
            <label for="classic-panel-doors"><input type="checkbox" value=".classic-panel-doors" id="classic-panel-doors" />classic-panel-doors</label>
          </div>
          <div class="checkbox">
            <label for="carriage-panel"><input type="checkbox" value=".carriage-panel" id="carriage-panel" />carriage-panel</label>
          </div>
          <div class="checkbox">
            <label for="overlay-carriage-house"><input type="checkbox" value=".overlay-carriage-house" id="overlay-carriage-house" />overlay-carriage-house</label>
          </div>
          <div class="checkbox">
            <label for="faux-wood-overlay"><input type="checkbox" value=".faux-wood-overlay" id="faux-wood-overlay" />faux-wood-overlay</label>
          </div>
          <div class="checkbox">
            <label for="wood-doors"><input type="checkbox" value=".wood-doors" id="wood-doors" />wood-doors</label>
          </div>
          <div class="checkbox">
            <label for="full-view-aluminum"><input type="checkbox" value=".full-view-aluminum" id="full-view-aluminum" />full-view-aluminum</label>
          </div>
        </div>

        <div class="option-set" data-group="material">
          <div class="checkbox">
            <label for="material-all"><input type="checkbox" value="" id="material-all" class="all" checked />material-all</label>
          </div>
          <div class="checkbox">
            <label for="aluminum"><input type="checkbox" value=".aluminum" id="aluminum" />aluminum</label>
          </div>
          <div class="checkbox">
            <label for="fiberglass"><input type="checkbox" value=".fiberglass" id="fiberglass" />fiberglass</label>
          </div>
          <div class="checkbox">
            <label for="steel"><input type="checkbox" value=".steel" id="steel" />steel</label>
          </div>
          <div class="checkbox">
            <label for="wood"><input type="checkbox" value=".wood" id="wood" />wood</label>
          </div>
        </div>

        <div class="option-set" data-group="insulation-type">
          <div class="checkbox">
            <label for="insulation-type-all"><input type="checkbox" value="" id="insulation-type-all" class="all" checked />insulation-type-all</label>
          </div>
          <div class="checkbox">
            <label for="non-insulated"><input type="checkbox" value=".non-insulated" id="non-insulated" />non-insulated</label>
          </div>
          <div class="checkbox">
            <label for="polystyrene"><input type="checkbox" value=".polystyrene" id="polystyrene" />polystyrene</label>
          </div>
          <div class="checkbox">
            <label for="polyurethane"><input type="checkbox" value=".polyurethane" id="polyurethane" />polyurethane</label>
          </div>
        </div>

        <div class="option-set" data-group="colors">
          <div class="checkbox">
            <label for="colors-all"><input type="checkbox" value="" id="colors-all" class="all" checked />colors-all</label>
          </div>
          <div class="checkbox">
            <label for="almond"><input type="checkbox" value=".almond" id="almond" />almond</label>
          </div>
          <div class="checkbox">
            <label for="bronze"><input type="checkbox" value=".bronze" id="bronze" />bronze</label>
          </div>
          <div class="checkbox">
            <label for="brown"><input type="checkbox" value=".brown" id="brown" />brown</label>
          </div>
          <div class="checkbox">
            <label for="cedar-unfinished"><input type="checkbox" value=".cedar-unfinished" id="cedar-unfinished" />cedar-unfinished</label>
          </div>
          <div class="checkbox">
            <label for="desert-tan"><input type="checkbox" value=".desert-tan" id="desert-tan" />desert-tan</label>
          </div>
          <div class="checkbox">
            <label for="evergreen"><input type="checkbox" value=".evergreen" id="evergreen" />evergreen</label>
          </div>
          <div class="checkbox">
            <label for="gray"><input type="checkbox" value=".gray" id="gray" />gray</label>
          </div>
          <div class="checkbox">
            <label for="mahogany-unfinished"><input type="checkbox" value=".mahogany-unfinished" id="mahogany-unfinished" />mahogany-unfinished</label>
          </div>
          <div class="checkbox">
            <label for="oak"><input type="checkbox" value=".oak" id="oak" />oak</label>
          </div>
          <div class="checkbox">
            <label for="walnut"><input type="checkbox" value=".walnut" id="walnut" />walnut</label>
          </div>
          <div class="checkbox">
            <label for="white"><input type="checkbox" value=".white" id="white" />white</label>
          </div>
          <div class="checkbox">
            <label for="woodtone-mahogany"><input type="checkbox" value=".woodtone-mahogany" id="woodtone-mahogany" />woodtone-mahogany</label>
          </div>
          <div class="checkbox">
            <label for="woodtone-oak"><input type="checkbox" value=".woodtone-oak" id="woodtone-oak" />woodtone-oak</label>
          </div>
          <div class="checkbox">
            <label for="woodtone-walnut"><input type="checkbox" value=".woodtone-walnut" id="woodtone-walnut" />woodtone-walnut</label>
          </div>
        </div>

      </div>

    </div>

    <div class="col-xs-12 col-md-8">

      <div id="container" class="isotope">

        <div class="grid-sizer"></div>

        <div class="grid-item classic-panel-doors wood non-insulated isotope-item">
          <p>classic-panel-doors</p>
          <p>wood</p>
          <p>non-insulated</p>
        </div>

        <div class="grid-item carriage-panel fiberglass polystyrene isotope-item">
          <p>carriage-panel</p>
          <p>fiberglass</p>
          <p>polystyrene</p>
        </div>

        <div class="grid-item overlay-carriage-house steel polystyrene isotope-item">
          <p>overlay-carriage-house</p>
          <p>steel</p>
          <p>polystyrene</p>
        </div>

        <div class="grid-item faux-wood-overlay fiberglass non-insulated isotope-item">
          <p>faux-wood-overlay</p>
          <p>fiberglass</p>
          <p>non-insulated</p>
        </div>

        <div class="grid-item wood-doors wood non-insulated isotope-item">
          <p>wood-doors</p>
          <p>wood</p>
          <p>non-insulated</p>
        </div>

        <div class="grid-item full-view-aluminum aluminum polyurethane isotope-item">
          <p>full-view-aluminum</p>
          <p>aluminum</p>
          <p>polyurethane</p>
        </div>

      </div>

    </div>

  </div>
</div>

JS

var $container;
var filters = {};

$(function(){

  $container = $('#container');

  $container.isotope();
  // do stuff when checkbox change
  $('#options').on( 'change', function( jQEvent ) {
    var $checkbox = $( jQEvent.target );
    manageCheckbox( $checkbox );

    var comboFilter = getComboFilter( filters );

    $container.isotope({ 
      filter: comboFilter,
      transitionDuration: '.5s',
      itemSelector: '.grid-item',
      percentPosition: true,
      masonry: {
        // use element for option
        columnWidth: '.grid-sizer'
      }
    });

  });

});

function getComboFilter( filters ) {
  var i = 0;
  var comboFilters = [];
  var message = [];

  for ( var prop in filters ) {
    message.push( filters[ prop ].join(' ') );
    var filterGroup = filters[ prop ];
    // skip to next filter group if it doesn't have any values
    if ( !filterGroup.length ) {
      continue;
    }
    if ( i === 0 ) {
      // copy to new array
      comboFilters = filterGroup.slice(0);
    } else {
      var filterSelectors = [];
      // copy to fresh array
      var groupCombo = comboFilters.slice(0); // [ A, B ]
      // merge filter Groups
      for (var k=0, len3 = filterGroup.length; k < len3; k++) {
        for (var j=0, len2 = groupCombo.length; j < len2; j++) {
          filterSelectors.push( groupCombo[j] + filterGroup[k] ); // [ 1, 2 ]
        }

      }
      // apply filter selectors to combo filters for next group
      comboFilters = filterSelectors;
    }
    i++;
  }

  var comboFilter = comboFilters.join(', ');
  return comboFilter;
}

function manageCheckbox( $checkbox ) {
  var checkbox = $checkbox[0];

  var group = $checkbox.parents('.option-set').attr('data-group');
  // create array for filter group, if not there yet
  var filterGroup = filters[ group ];
  if ( !filterGroup ) {
    filterGroup = filters[ group ] = [];
  }

  var isAll = $checkbox.hasClass('all');
  // reset filter group if the all box was checked
  if ( isAll ) {
    delete filters[ group ];
    if ( !checkbox.checked ) {
      checkbox.checked = 'checked';
    }
  }
  // index of
  var index = $.inArray( checkbox.value, filterGroup );

  if ( checkbox.checked ) {
    var selector = isAll ? 'input' : 'input.all';
    $checkbox.siblings( selector ).removeAttr('checked');


    if ( !isAll && index === -1 ) {
      // add filter to group
      filters[ group ].push( checkbox.value );
    }

  } else if ( !isAll ) {
    // remove filter from group
    filters[ group ].splice( index, 1 );
    // if unchecked the last box, check the all
    if ( !$checkbox.siblings('[checked]').length ) {
      $checkbox.siblings('input.all').attr('checked', 'checked');
    }
  }

}

Here is a link to the pen - http://ift.tt/1FFlvy4

And here is an example of how it SHOULD work - http://ift.tt/18EQ4PE




How to show custom actionbar when check checkbox on the listview?

I have one listview that contain a text view and a checkbox in lines. I want to show custom actionbar when checkbox checked in listview. I wrote the one xml file type of menu like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://ift.tt/nIICcg" >

    <item
        android:id="@+id/delete"
        android:title="actionbar"
        android:icon="@drawable/recycle"/>

</menu>

So I use for custom listview this codes:

private class Adapter_collection extends ArrayAdapter<String> {

    public Adapter_collection(Context context, int resource, int textViewResourceId,
            String[] name_collection_tbl_collection) {
        super(context, resource, textViewResourceId, name_collection_tbl_collection);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.listview_items, parent, false);
        TextView txt_item_list_collection = (TextView)row.findViewById(R.id.textView_Item_Listview);
        CheckBox checkBox=(CheckBox)row.findViewById(R.id.checkBox_Item_Listview);

        checkBox.setTag(position);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {         
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked ) {   
                //list_collections.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

                    Toast.makeText(getApplicationContext(), buttonView.getTag().toString() , Toast.LENGTH_SHORT).show();        
            }
        });
        txt_item_list_collection.setText(name_collection_tbl_collection[position]);
        return row;
    }

}

I don't change the onCreateOptionsMenu()




Visual Basic - Checkbox states

Okay so what I want to do is whilst one Checkbox is checked and in this instance 'Addition' will be checked > whilst it is checked how would I make a pop-up saying "You cannot select more than two values at once" or something so they can't check two boxes and crash the program. Here is my code:

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

    Dim Addition As String
    Dim Subtraction As String
    Dim Multiplication As String

    Multiplication = CheckBox3.CheckState
    Subtraction = CheckBox2.CheckState
    Addition = CheckBox1.CheckState

    If Addition = CheckState.Checked Then
        'label icon of the current calculation sign 
        neum.Text = "+"
        'label icon of the current calculation sign
        Me.CheckBox2.CheckState = CheckState.Unchecked
        Me.CheckBox3.CheckState = CheckState.Unchecked
    End If

    If Addition = CheckState.Unchecked Then
        neum.Text = " "
    End If
End Sub




Android checkbox selection in listivew

In my android application I am storing all the details of contact list in mobile to a listview and a checkbox is added to it for selecting a particular contact.. but there is some problem in selecting checkbox, app is crashing while selecting I am giving the code below.. if anyone can help please help

 btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int count = listView.getCount();



                for(int i=0;i<count;i++) {
                    ViewGroup item = (ViewGroup) listView.getChildAt(i);
                    checkBox = ((CheckBox) item.findViewById(R.id.selected));

                    if(checkBox.isChecked()) {

                        Toast.makeText(SendMessagesActivity.this, "How are u", Toast.LENGTH_LONG)
                                .show();
                    }
                }


            }
        });

ContactsAdapter

public class ContactsAdapter extends BaseAdapter
{
    private Context context;
    private ArrayList<Contact> contacts;
    SparseBooleanArray sba=new SparseBooleanArray();

    public ContactsAdapter(Context context, ArrayList<Contact> contacts)
    {
        this.context = context;
        this.contacts = contacts;

    }




    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        final ViewHolder mHolder;

        if (convertView == null)
        {


            // gridView = new View(context);
            // get layout from mobile.xml
            //gridView = inflater.inflate(R.layout.contact, null);
            convertView = inflater.inflate(R.layout.contact, null);
            mHolder = new ViewHolder();

            mHolder.textName     =(TextView) convertView.findViewById(R.id.name);
            mHolder.textMobile   =(TextView) convertView.findViewById(R.id.mobile);
            mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);



            convertView.setTag(mHolder);



               /* TextView textName = (TextView) gridView.findViewById(R.id.name);
                textName.setSelected(true);
                textName.setText(contacts.get(position).getName());*/
               // cname = String.valueOf(contacts.get(position).getName());


               /* TextView textMobile = (TextView) gridView.findViewById(R.id.mobile);
                textMobile.setText(contacts.get(position).getMobile());*/
               // cmob = String.valueOf(contacts.get(position).getMobile());
            }



        else
        {
            //gridView = convertView;

            mHolder = (ViewHolder) convertView.getTag();

        }

        mHolder.textMobile.setText(contacts.get(position).getMobile());
        mHolder.textName.setText(contacts.get(position).getName());
        mHolder.textName.setSelected(true);
        mHolder.textSelector.setChecked(sba.get(position));

        mHolder.textSelector.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {

                 if(mHolder.textSelector.isChecked())
                 {
                     sba.put(position, true);
                 }

                else
                {
                    sba.put(position, false);
                }

            }
        });


        // return gridView;

        return convertView;
    }




    private class ViewHolder
    {
        private TextView textMobile,textName;
        private CheckBox textSelector;
    }

    @Override
    public int getCount()
    {
        return contacts.size();
    }

    @Override
    public Object getItem(int position)
    {
        return null;
    }

    @Override
    public long getItemId(int position)
    {
        return 0;
    }

}




How to replace product to #product?

I have this code, but when I run the program remain blocked. With this code I want to check/uncheck all items, and when this are checked in text file installer.ini to write #product=name of checkbox => product=name of checkbox and if this are unchecked in text file where I have product=name of checkboxto replace with #product=name of checkbox.

private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
{
    string installerfilename = path + "installer.ini";
    string installertext = File.ReadAllText(installerfilename);
    var lin =File.ReadLines(path + "installer.ini").ToArray();

    CheckBox cb = sender as CheckBox;
    if (cb.Checked)
    {
        for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
        {
            this.checkedListBox2.SetItemChecked(i, true);
            foreach (var txt in lin)
            {
                if (txt.Contains("#product="))
                {
                    var name = txt.Split('=')[1];
                    installertext = installertext.Replace("#product=", "product=" + name);

                }
                File.WriteAllText(installerfilename, installertext);
            }
        }
    }
    else if (!cb.Checked)
    {
        for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
        {
            this.checkedListBox2.SetItemChecked(i, false);
            foreach (var txt in lin)
            {
                if (txt.Contains("product="))
                {
                    var name1 = txt.Split('=')[1];
                    installertext = installertext.Replace("product=", "#product=" + name1);

                }
                File.WriteAllText(installerfilename, installertext);
            }

        }
    }
}




Selecting checkbox which is on shockwave flash and does not have any id in html code

I am working on website where it is a graph of traffic and it has shockwave flash which has some checkboxes after selecting them it performs some operations for example selecting 'subscribed bandwidth' shows bandwidth line on that traffic graph. Problem is there is no element in html code to interact with it.I am using selenium webdriver with python.Below is html code for that

<div id="chartContainer">
 <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="LineChart" height="830" width="100%">
     <param name="flashVars" value="use_1024=false&amp;dataMultFactor=1000">
     <param name="movie" value="swf/AryakaCharts.swf?version=26128">
     <param name="wmode" value="transparent">
     <param name="quality" value="high">
     <param name="bgcolor" value="#869ca7">
     <param name="allowScriptAccess" value="sameDomain">
     <embed src="swf/companyCharts.swf?version=26128"  quality="high" bgcolor="#869ca7" 
     name="LineChart" id="LineChart" align="middle" play="true" height="830"  width="100%"   wmode="transparent" flashvars="use_1024=false&amp;dataMultFactor=1000"   loop="false"allowscriptaccess="sameDomain"  type="application/x-shockwave-flash">
 </object>
</div>




lundi 28 septembre 2015

Checkbox items getting unchecked while scrolling listview

I can store the values of checkboxes using shared preferences but once I scroll the list view, the checked boxes getting unchecked again. I am not able to understand what is causing this. Would love to hear your suggestions.

Here is my code:

ListViewAdapter.java

package com.example.logintest;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewAdapter extends BaseAdapter{

    private Context _context;
    private List<String[]> list;
    ViewHolder holder=null;
    View row=null;
    String cbstate; 

    public  ListViewAdapter(Context _context,List<String[]> list)
    {
        this._context=_context;
        this.list=list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return list.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    private static class ViewHolder
    {
        public TextView textView;
        public ImageView imageview;
        public CheckBox cb;

        public ViewHolder(View row) {
            // TODO Auto-generated constructor stub
             textView = (TextView) row.findViewById(R.id.textView);
             cb = (CheckBox) row.findViewById(R.id.cb);  
             imageview = (ImageView)row.findViewById(R.id.imageView);
        }

    }


    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        // TODO Auto-generated method stub


        SharedPreferences state = _context.getSharedPreferences("data",Context.MODE_PRIVATE);

        row=convertView;
        holder=null;

           try{


               if(row==null)
               {
                   LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    row = inflater.inflate(R.layout.row, viewGroup, false);
                   holder=new ViewHolder(row);
                     row.setTag(holder);
                     Log.d("newrow", "New row");
        ////////////////////////////////////////////////////////////////////////


            holder.textView.setText(list.get(position)[0].toString());


            //images entered here0

            if(position==0)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.one))  ;
            }
            else if(position==1)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.two))  ;

            }
            else if(position==2)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.three))  ;
            }
            else if(position==3)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.four))  ;
            }
             else if(position==4)
            {
                 holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.five))  ;
            }
            else if(position==5)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.six))  ;
            }
            else if(position==6)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.seven))  ;
            }
            else if(position==7)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.eight))  ;
            }
            else if(position==8)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.nine))  ;
            }
            else if(position==9)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.ten))  ;
            }
            else if(position==10)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.eleven))  ;
            }
            else if(position==11)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.tweleve))  ;
            }
            else if(position==12)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.thirteen))  ;
            }
            else if(position==13)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.fourteen))  ;
            }
            else if(position==14)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.fifteen))  ;
            }
            else if(position==15)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.sixteen))  ;
            }
            else if(position==16)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.seventeen))  ;
            }
            else if(position==17)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.eighteen))  ;
            }
            else if(position==18)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.nineteen))  ;
            }
            else if(position==19)
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.twenty))  ;
            }

            else
            {
                holder.imageview.setImageDrawable( _context.getResources().getDrawable(R.drawable.ic_launcher))  ;
            }



            //checkbox functions




        //Here we can do changes to the convertView, such as set a text on a TextView 
        //or an image on an ImageView.
        //return convertView;

       }

               else
               {

                    holder= (ViewHolder) row.getTag();
                    Log.d("recycle", "Recycling stuff");

               }

               final SharedPreferences.Editor editor = state.edit();
                holder.cb.setChecked(state.getBoolean("CheckValue"+position,holder.cb.isChecked() ));


               holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {



                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            //Handle your conditions here

                        editor.putBoolean("CheckValue"+position, holder.cb.isChecked());
                        editor.commit();

                        Toast.makeText(_context,"checkbox:"+position,Toast.LENGTH_LONG).show();

                    }




                    });


                   holder.cb.setTag(position);

             //changing color of items alternatively
                if (position % 2 == 0) {
                    row.setBackgroundColor(Color.parseColor("#58D3F7"));  
                } else {
                    row.setBackgroundColor(Color.parseColor("#F5F6CE"));  
                }

           }
           catch(Exception e)
            {
                e.printStackTrace();

            }
        return row;
    }



}




Perform MySql PHP search from a POST form with checkbox array

I have a POST form in which I have a checkbox with the name airport_use[].

<form id="stacks_in_p12751_n11834_page0_form" action="http://ift.tt/1P2KbCL" method="post">
<input type="checkbox" name="airport_use[]" value='Public'> 
<input type="checkbox" name="airport_use[]" value='Private'> 
<input type="checkbox" name="airport_use[]" value='Military'> 
<input type="checkbox" name="airport_use[]" value='Unknown'> 
<button class='ag_submit_button' type='submit'>Get Airport Information</button>
</form>

On the airport_search_results2.php results page I am trying to read in the variable for use in an SQL SELECT statement.

<?php 
$and_flag==0;
$sql = "SELECT * FROM table ";
if(isset($_POST['airport_use'])){
 {  if ($and_flag==0)
    {$clause = "WHERE "; // the first time the field exists use WHERE
    $and_flag=1;}   
    else{$clause = "OR ";} // use OR after the first field exists
        foreach($_POST['airport_use'] as $c){
            if(!empty($c)){
                 $sql .= $clause."airport_use LIKE '%{$c}%'";
                $clause = " OR ";//Change  to OR after 1st WHERE or AND
            }   
        }
    }
}
$sql .= "LIMIT 5000";

?> The problem I'm having is this code is only working if only one of the checkboxes is checked. More than one just makes the query hang. Any suggestions to fix this?

Thanks, Mike




Bootstrap Align Checkbox next to Header

I'm trying to vertically align a bootstrap checkbox & label with a header element. I also want the checkbox & label to be at the far right of the shared grid row.

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-4">
        <div class="form-inline">
             <h3>Chat Room</h3>

            <label class="checkbox-inline">
                <input type="checkbox" checked> <small>enable presence events</small>
            </label>
        </div>
    </div>
</div>

CSS:

.form-inline h3 {
    display: inline-block;
}

label.checkbox-inline {
    float: right;
}

http://ift.tt/1MCjtyx

Results in:

enter image description here

I'm hoping there's a clean & responsive way to do this, other than a hacky margin/padding fix.

Thanks!




fetch data from mysql by multiple checkbox with different names.(array) Codeigniter

I want to fetch data from a database with multiple check box name arrays but I'm having an issue that it only returns the first selected check box on the name arrays and returns nothing when having different combinations of selections. Please help me. Thank you.

HERE IS MY VIEW:

<div class="col-lg-3">
                                    <div class="form-group">
                                        <label>Year Level</label>

                                   <?php if($cat_yr_lvl !== false): ?>
                                            <?php foreach($cat_yr_lvl as $data): ?>
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="yr_lvl[]" value="<?php echo $data->year_level?>"><?php echo $data->year_level?>
                                                </label>
                                            </div>
                                            <?php endforeach;?>
                                    <?php endif; ?>
                                   </div>
                                </div>



                                     <div class="col-lg-3">
                                    <div class="form-group">
                                                <label>Semester</label>
                                       <?php if($cat_sem !== false): ?>
                                            <?php foreach($cat_sem as $data): ?>
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="sem[]" value="<?php echo $data->sem?>"><?php echo $data->sem?>
                                                </label>
                                            </div>
                                            <?php endforeach;?>
                                    <?php endif; ?>
                                    <hr>
                                        <label>Gender</label>
                                        <?php if($cat_gender !== false): ?>
                                            <?php foreach($cat_gender as $data): ?>
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="gender[]" value="<?php echo $data->gender?>"><?php echo $data->gender?>
                                                </label>
                                            </div>
                                            <?php endforeach;?>
                                    <?php endif; ?>
                                </div>
                                </div>

                                    <div class="col-lg-3">
                                    <div class="form-group">
                                        <label>Midterm Grade Description</label>
                                        <?php if($cat_mid !== false): ?>
                                            <?php foreach($cat_mid as $data): ?>
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="mid[]" value="<?php echo $data->mid?>"><?php echo $data->mid?>
                                                </label>
                                            </div>
                                            <?php endforeach;?>
                                    <?php endif; ?>

                                    <hr>
                                        <label>Final Grade Description</label>
                                        <?php if($cat_final !== false): ?>
                                            <?php foreach($cat_final as $data): ?>
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="final[]" value="<?php echo $data->fin?>"><?php echo $data->fin?>
                                                </label>
                                            </div>
                                            <?php endforeach;?>
                                    <?php endif; ?>
                                     </div>

                      </div>

HERE IS MY MODEL:

$student_db = $this->load->database('student_db', TRUE);

    $str_dept = implode(",",$this->input->get('dept_id'));
    $str_sy = implode(",",$this->input->get('sy'));
    $str_yr_lvl = implode(",",$this->input->get('yr_lvl'));
    $str_sem = implode(",",$this->input->get('sem'));
    $str_gender = implode(",",$this->input->get('gender'));
    $str_mid = implode(",",$this->input->get('mid'));
    $str_final = implode(",",$this->input->get('final'));

        $student_db->select('*');
        $student_db->where_in('Department_College_dept_id', $str_dept);
        $student_db->where_in('Student_sy', $str_sy);
        $student_db->where_in('Student_year_level', $str_yr_lvl);
        $student_db->where_in('Student_sem', $str_sem);
        $student_db->where_in('gender', $str_gender);
        $student_db->where_in('midterm_description', $str_mid);
        $student_db->where_in('final_description', $str_final);

        $query = $student_db->get('std_v'); 

        return $query->result();