mercredi 31 août 2016

Why does my program keep creating new elements?

This is part of the interactivity of a form.

A user can select from a range of activities. 6 of the activities are priced as 100, one of them is priced at 200.

As the user checks the boxes, a label appears, telling the user what the total price is.

Right now, the price is being calculated fine.

But every single time a box is checked, a NEW label is added. As opposed to updating the old one. Why is this happening?

This is my code:

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.getElementById("all");
    var framework = document.getElementById("framework");
    var libs = document.getElementById("libs");
    var express = document.getElementById("express");
    var node = document.getElementById("node");
    var build = document.getElementById("build");
    var npm = document.getElementById("npm");

    // Calculate running total of price of events selected
    var mainPrice = 200;
    var otherPrice = 100;
    var totalPrice = 0;


    if(!totalLabel){
        var totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

    if(main.checked == true){
        totalPrice += mainPrice;
    }
    if(framework.checked == true || express.checked == true) {
        totalPrice += otherPrice;
    } 
    if(libs.checked == true || node.checked == true) {
        totalPrice += otherPrice;
    } 
    if(build.checked == true) {
        totalPrice += otherPrice;
    } 
    if(npm.checked == true) {
        totalPrice += otherprice;
    }

    var totalNumber = totalPrice.toString();
    var totalText = "Total is $" + totalNumber;

    totalLabel.innerHTML = totalText;
});

I assumed this would be a problem before, I thought this would fix it by only creating a new element if totalLabel didn't already exist :

if(!totalLabel){
        var totalLabel = document.createElement('label');
        activities.appendChild(totalLabel);
    }

Any suggestions please guys?




Insert into collection if checkbox input is checked

What I'm trying to do: I'm using a checkbox in a form that when checked and submitted using a button, it will create a new item in a collection.

Checkbox > Checked > Form Submit > Create new item in a collection.

Checkbox > Unchecked > Form Submit > Do not create the collection.

I have a collection Schema with the following:

value: {
    Type: Boolean, 
    ...
}

With a default of false. This is fine.

What I have tried I have tried two different ways to pass this through to Meteor server side to insert the new collection:

  • On change of checkbox, update DB value and on submit, check the value in db, if false, don't make collection, if true, make it.

  • On submission of form, check if checkbox is checked or unchecked and create the new collection based on this.

Neither worked as I don't know how to pass the content from the HTML to the js file within Meteor. I know how to do this via JavaScript etc.

I'm using a simple if(value) { } but it seems this is only checking if the input exists and is always return true.

I've tried document.getelementbyID, this returns undefined on document. I've tried using it as an event, this returns that events is undefined.

My question:

How do I pass a checked/unchecked value into the Meteor Javascript?




Why don't all my checkboxes have the same behavior?

I'm adding some interactivity to a form.

A user will select from a range of activities. Some of the activities have a time-clash.

If a user selects one of the activities with a time-clash, then the activity it clashes with will be disabled and unable to be selected.

If the user then DEselects that checkbox, then they are all enabled and are free to choose any checkbox they want.

Right now, I can disable all the correct boxes. But I am unable to disable them again, aside from the first, frameworks. With the others, I am locked with my decision and have to refresh the page. Why is this happening?

Here is my code:

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.getElementById("all");
    var framework = document.getElementById("framework");
    var libs = document.getElementById("libs");
    var express = document.getElementById("express");
    var node = document.getElementById("node");
    var build = document.getElementById("build");
    var npm = document.getElementById("npm");

    var frameworkLbl = document.getElementById("frameworkLabel");
    var libsLbl = document.getElementById("libsLabel");
    var expressLbl = document.getElementById("expressLabel");
    var nodeLbl = document.getElementById("nodeLabel");


    // If the user selects a workshop, don't allow selection of a workshop at the same date and time -- you should disable the checkbox and visually indicate that the workshop in the competing time slot isn't available.
    if(framework.checked == true) {
        express.disabled = true;
        expressLbl.style.color = "grey";
    } else if(express.checked == true) {
        framework.disabled=  true;
        frameworkLbl.style.color = "grey";
    } else if(libs.checked == true) {
        node.disabled = true;
        nodeLbl.style.color = "grey";
    } else if(node.checked == true) {
        libs.disabled = true;
        libsLbl.style.color = "grey";
    } 

    // When a user unchecks an activity, make sure that competing activities (if there are any) are no longer disabled.
    if(framework.checked == false) {
        express.disabled = false;
        expressLbl.style.color = "black";
    } else if(express.checked == false) {
        framework.disabled = false;
        frameworkLbl.style.color = "black";
    } else if(libs.checked == false) {
        node.disabled = false;
        nodeLbl.style.color = "black";
    } else if(node.checked == false) {
        libs.disabled = false;
        libsLbl.style.color = "black";
    }
});



      <fieldset class="activities">
        <legend>Register for Activities</legend>
        <div id="activityReminder"></div>
        <div id="lineBreak"></div>
        <label><input type="checkbox" name="all" id="all" class="activity"> Main Conference — $200</label>
        <label id="frameworkLabel"><input type="checkbox" name="js-frameworks" id="framework" class="activity"> JavaScript Frameworks Workshop — Tuesday 9am-12pm, $100</label>
        <label id="libsLabel"><input type="checkbox" name="js-libs" id="libs" class="activity"> JavaScript Libraries Workshop — Tuesday 1pm-4pm, $100</label>
        <label id="expressLabel"><input type="checkbox" name="express" id="express" class="activity"> Express Workshop — Tuesday 9am-12pm, $100</label>
        <label id="nodeLabel"><input type="checkbox" name="node" id="node" class="activity"> Node.js Workshop — Tuesday 1pm-4pm, $100</label>          
        <label><input type="checkbox" name="build-tools" id="build" class="activity"> Build tools Workshop — Wednesday 9am-12pm, $100</label>
        <label><input type="checkbox" name="npm" id="npm" class="activity"> npm Workshop — Wednesday 1pm-4pm, $100</label>
      </fieldset>




rails: link_to to pass list of selected checkboxes into params

I am not sure what the correct approach is for my situation:

I want to create a link_to pushing all checkboxes with value="1" into an array, or individually if array is not possible, but I am at a loss of how to express that?

<% @cards.each do |card| %>
    <%= check_box("#{card.name}", card.id, {checked: true}) %><%= "#{card.name}" %>
<% end %>

(Rails 4.2)




Why won't all my checkboxes toggle between disabled and enabled?

I'm writing the interactivity for a form.

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.getElementById("all");
    var framework = document.getElementById("framework");
    var libs = document.getElementById("libs");
    var express = document.getElementById("express");
    var node = document.getElementById("node");
    var build = document.getElementById("build");
    var npm = document.getElementById("npm");

    var frameworkLbl = document.getElementById("frameworkLabel");
    var libsLbl = document.getElementById("libsLabel");
    var expressLbl = document.getElementById("expressLabel");
    var nodeLbl = document.getElementById("nodeLabel");


    // If the user selects a workshop, don't allow selection of a workshop at the same date and time -- you should disable the checkbox and visually indicate that the workshop in the competing time slot isn't available.
    if(framework.checked == true) {
        express.disabled = true;
        expressLbl.style.color = "grey";
    } else if(express.checked == true) {
        framework.disabled=  true;
        frameworkLbl.style.color = "grey";
    } else if(libs.checked == true) {
        node.disabled = true;
        nodeLbl.style.color = "grey";
    } else if(node.checked == true) {
        libs.disabled = true;
        libsLbl.style.color = "grey";
    } 

    // When a user unchecks an activity, make sure that competing activities (if there are any) are no longer disabled.
    if(framework.checked == false) {
        express.disabled = false;
        expressLbl.style.color = "black";
    } else if(express.checked == false) {
        framework.disabled = false;
        frameworkLbl.style.color = "black";
    } else if(libs.checked == false) {
        node.disabled = false;
        nodeLbl.style.color = "black";
    } else if(node.checked == false) {
        libs.disabled = false;
        libsLbl.style.color = "black";
    }
}); 

  <fieldset class="activities">
        <legend>Register for Activities</legend>
        <label><input type="checkbox" name="all" id="all"> Main Conference — $200</label>
        <label id="frameworkLabel"><input type="checkbox" name="js-frameworks" id="framework"> JavaScript Frameworks Workshop — Tuesday 9am-12pm, $100</label>
        <label id="libsLabel"><input type="checkbox" name="js-libs" id="libs"> JavaScript Libraries Workshop — Tuesday 1pm-4pm, $100</label>
        <label id="expressLabel"><input type="checkbox" name="express" id="express"> Express Workshop — Tuesday 9am-12pm, $100</label>
        <label id="nodeLabel"><input type="checkbox" name="node" id="node"> Node.js Workshop — Tuesday 1pm-4pm, $100</label>          
        <label><input type="checkbox" name="build-tools" id="build"> Build tools Workshop — Wednesday 9am-12pm, $100</label>
        <label><input type="checkbox" name="npm" id="npm"> npm Workshop — Wednesday 1pm-4pm, $100</label>
      </fieldset>

For some reason, when I check 'framework', it will disable 'express'. If I uncheck 'framework', 'express' is then enabled.

This isn't working correctly for the other boxes. I can get them to disable the other. But I can't toggle it back to normal unless I refresh the page.

What is the reason for this?

Thanks1




Jquery enable/disable checkbox by name

I am trying to disable checkboxes by name in the following table, but it is not working. Any suggestions, why?

<table border="1" class="myTable grid">
  <tr align="center">
    <td>A</td>
  </tr>
  <tr align="center">
    <td>1</td>
    <td>
      <input type="checkbox" name="cb1;1" value="1">
    </td>
  </tr>
  <td>2</td>
  <td>
    <input type="checkbox" name="cb2;1" value="1" checked>
  </td>
  </tr>
  <tr align="center">
</table>
<button id="button1" type="button"> DISABLE </button>
<button id="button2" type="button">ENABLE </button>

This is how I am disable/enable these checkboxes. I have tried .attr('disabled', 'disabled'); for disabling too.

$("#button1").click(function() { 
  var cbname = $j(this).attr("name");
  $("input[name='cbname']").prop("disabled", false);
});

$("#button2").click(function() { 
  var cbname = $j(this).attr("name");
  $("input[name='cbname']").prop("disabled", true);
});




If checkbox Checked then add to datatable from Gridview

I am trying check whether a checkbox is checked in a gridview and if it is checked to add it to the datatable.

However I am getting an error when the checkbox is unchecked for the row:

There is no row at position 1.

Here is my code:

       'Creates a new datatable
        Dim dtQuestions As New DataTable("QuestionsData")

        'Add columns to datatable
        For Each cell As TableCell In example.HeaderRow.Cells

            dtQuestions.Columns.Add(cell.Text)

        Next

        For Each row As GridViewRow In example.Rows

            Dim chkTest As CheckBox = CType(row.FindControl("chkTest"), CheckBox)
            If chkTest.Checked = True Then

                dtQuestions.Rows.Add()

                For i As Integer = 0 To row.Cells.Count - 1

                    Try

                        dtQuestions.Rows(row.RowIndex)(i) = row.Cells(i).Text

                    Catch ex As Exception

                    End Try


                Next

            Else

                'Do not add it to Datatable

            End If

        Next

I am getting the error on this code:

dtQuestions.Rows(row.RowIndex)(i) = row.Cells(i).Text

I do not know how to fix this.




Why can't I check if my checkboxes have been checked?

I am adding interactivity to a form.

A user will select, via checkboxes, activities that they would like to do.

If a user selects an activity that has a time clash with another. Then that other checkbox will be disable.

I don't want to use jQuery for this.

I am having trouble trying to implement this. The error says it cannot read property 'checked' of null?

What am I doing wrong here? I have tried, mixing up whether I'm trying to call upon values, check properties and have tried quite a few attempted solutions but to no avail.

Here is the html:

<fieldset class="activities">
        <legend>Register for Activities</legend>
        <label><input type="checkbox" name="all"> Main Conference — $200</label>
        <label><input type="checkbox" name="js-frameworks"> JavaScript Frameworks Workshop — Tuesday 9am-12pm, $100</label>
        <label><input type="checkbox" name="js-libs"> JavaScript Libraries Workshop — Tuesday 1pm-4pm, $100</label>
        <label><input type="checkbox" name="express"> Express Workshop — Tuesday 9am-12pm, $100</label>
        <label><input type="checkbox" name="node"> Node.js Workshop — Tuesday 1pm-4pm, $100</label>          
        <label><input type="checkbox" name="build-tools"> Build tools Workshop — Wednesday 9am-12pm, $100</label>
        <label><input type="checkbox" name="npm"> npm Workshop — Wednesday 1pm-4pm, $100</label>
      </fieldset>

Here is the JavaScript:

// Register for Activities section of the form.
document.querySelector(".activities").addEventListener("change", function(){
    var main = document.querySelector("all").checked;
    var framework = document.querySelector("js-frameworks").checked;
    var libs = document.querySelector("js-libs").checked;
    var express = document.querySelector("express").checked;
    var node = document.querySelector("node").checked;
    var build = document.querySelector("build-tools").checked;
    var npm = document.querySelector("npm").checked;

    // If the user selects a workshop, don't allow selection of a workshop at the same date and time -- you should disable the checkbox and visually indicate that the workshop in the competing time slot isn't available.
    if(framework == true) {
        express.disabled = true;
    } else if(express == true) {
        framework.disabled = true;
    } else if(libs == true) {
        node.disabled = true;
    } else if(node == true) {
        libs.disabled = true;
    } 

    // When a user unchecks an activity, make sure that competing activities (if there are any) are no longer disabled.
    if(!framework.checked) {
        express.disabled = false;
    } else if(!express.checked) {
        framework.disabled = false;
    } else if(!libs.checked) {
        node.disabled = false;
    } else if(!node.checked) {
        libs.disabled = false;
    } 
});




How to change a normal button status based on checkbutton status in tkinter

Sample of my code is here. I expect my program to change status of "mb2" button based on checkbutton selection status

cb=Checkbutton(mf,text="Past(X hours)",variable=chkvar,padx=20,relief=GROOVE)
cb.pack(side=RIGHT,anchor=E)
chkvar.set(0)

def conf(self):
    if chkvar.get() == 0 :
            mb2.configure(state='normal')
    if chkvar.get() == 1 :
            mb2.configure(state='disabled')
cb.bind('<Button-1>',conf)




Using Ajax to store checkbox in database

I have the following that I've found from some snippets during my searches for help however I cannot get it to work. What I am trying to accomplish is clicking a check box and it automatically populate a row in my database that I can refer to on any other page. Right now when I click the checkbox, nothing happens.

HTML

<td><input type="checkbox" name="<?php echo $brow['WorkOrder']; ?>"  value="<?php echo $brow['WorkOrder']; ?>"></td>

Ajax

     <!-- Checkbox storage -->
     <script>
     $(document).ready(function(){
        $("input[type='checkbox']").on('click', function(){
        var checked = $(this).attr('checked');
        if(checked){
            var value = $(this).val();
            $.post('functions/checkBox.php', { value:value }, function(data){
                // data = 0 - means that there was an error
                // data = 1 - means that everything is ok
                if(data == 1){
                    // Do something or do nothing :-)
                    alert('Data was saved in db!');
                }
            });
        }
        });
    });
    </script>

functions/checkBox.php

<?php
if ($_POST && isset($_POST['value'])) {

    // db connection
    include("../../db.php");

    // sanitize the value
    $value = mysql_real_escape_string($_POST['value']);

    // start the query
    $sql = "INSERT INTO TemporaryCheckBoxID (WorkOrder) VALUES ('$value')";

    // check if the query was executed
    if(mysql_query($sql)){
       // everything is Ok, the data was inserted
       print(1);    
    } else {
       // error happened
       print(0);
    }
}
?>




Changing the color of checkbox if checked

I am trying to change the background color and border of a checkbox but it is not working.

HTML:

<label for="checkbox1" class="checkbox">
  <input id="checkbox1" type="checkbox" role="checkbox" /><span class="custom">Checkbox</span>
</label>

CSS:

.checkbox input:checked {
    border-color: red;
    background-color:red;
}

JSFiddle Demo

UPDATE:

I can't change the markup




trying ticking off the check box twice unticks it where it shouldnt untick the checkbox until the user who ticked or the admin laravel

Only the user who ticked the checkbox can untick the checkbox or the admin can do it but when I try unticking it with any other user then it unticks it on SECOND attemp but on first attempt it stays ticked.

My controller File

public function tickoffUpload($id, $type, User $user) {

    $uploads = $this->upload->get($id); //gets upload id

    if($this->request->isMethod('get')) {
        if($user->can('untick', $uploads) || (Auth::user()->role=='admin')) {
            if($type == 0) {
                $uploads->uploaded = $this->request->upload = 1;

            } else if($type == 1) {
                $uploads->uploaded = $this->request->upload = 0;  

            }

        } else {
            $uploads->uploaded = 1;
         }

    }

    return redirect('/home');

}

User Policy

public function untick(User $user, Upload $upload) { return Auth::id() == $upload->user_id;
}




convert Java to C#, cardview

hello someone could help me convert this code Java to C #, I would greatly appreciate it...........

    @Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
   final int pos = position;
   viewHolder.tvName.setText(stList.get(position).getName());
   viewHolder.tvEmailId.setText(stList.get(position).getEmailId());
   viewHolder.chkSelected.setChecked(stList.get(position).isSelected());
   viewHolder.chkSelected.setTag(stList.get(position));

   viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v;
            Student contact = (Student) cb.getTag();

            contact.setSelected(cb.isChecked());
            stList.get(pos).setSelected(cb.isChecked());

            Toast.makeText(
                    v.getContext(),
                    "Clicked on Checkbox: " + cb.getText() + " is "
                            + cb.isChecked(), Toast.LENGTH_LONG).show();
        }
    });

}




Checking only one item in a Listview

i need to check only one item using checkbox tool in a ListView as shown in the following code in the condition if :

 private void BindUnpaid()
{
  if (HiddenField2.Value == "1")
        {

            foreach (ListViewDataItem item in this.LstViewUnpaid.Items)
            {
                var chk = item.FindControl("IsChecked") as System.Web.UI.HtmlControls.HtmlInputCheckBox;

                chk.Disabled = false;

            }
}




how to save checked check_box_tag after submit, without JS?

I have a view for searching method, if I want to choose some kind of search, I have to check it in the box. How I can to save checked checkbox after submit?

search.html.haml
         .panel-heading
            #collapse0.panel-collapse.collapse.in
              %ul.list-group
                %li.list-group-item
                  .checkbox
                    %label
                      = check_box_tag :day
                      Last day
                      .checkbox
                    %label
                      = check_box_tag :week
                      Last week
                      .checkbox
                    %label
                      = check_box_tag :mounth
                      Last mounth
                %li.list-group-item
                  .checkbox
                    %label
                      = check_box_tag :post
                      All
                %li.list-group-item
                  .checkbox
                    %label
                      = check_box_tag :genre
                      Genre




Check custom checkbox individually

Hi all and thanks in advance for your help!

I'm trying to create some custom checkboxes for a contact form. The default checkbox is not visible and is inside a custom checkbox, in the example you'll understand what I'm looking for. The idea is that once you click on the checkbox, a custom style displays representing that the field has been checked, and if you click again on the same field the style disappears. Right now I'm unable to check, and therefore style, only the selected checbox, instead all the other fields become selected or deselected as well. Another issue is that the checkboxes in the 1st field are checked by default and I need them unchecked.

$('.checkbox input').on( 'click', function() {
    if( $(this).is(':checked') ){
        $('.checkbox').addClass('checked');
    } else {
        $('.checkbox').removeClass('checked');
    }
});
.checkbox{
        width: 125px;
        background-color: #fff;
        border: 2px solid #1AC4F8;
        display: inline-block;
        margin: 10px 0;
    font-size: 14px;
    color: gray;
    text-align: center;
    cursor: pointer;
    -webkit-transition: color 0.8s, background-color 0.8s;
        transition: color 0.8s, background-color 0.8s;
}

.checkbox:hover{
        color: white;
        background-color: #1AC4F8;
}

.checkbox input{
        opacity: 0;
        position: absolute;
        z-index: -1
}

.checkRow{
        text-align: center;     
}

.checked{
        color: white;
        background-color: #1AC4F8;
}
<script src="http://ift.tt/1qRgvOJ"></script>
<div class="checkRow">
                    <label class="checkbox">
                        <input type="checkbox" name="service" value="SEO">SEO
                    </label>
                    <label class="checkbox">
                        <input type="checkbox" name="service" value="SEM">SEM
                    </label>
                    <label class="checkbox">
                        <input type="checkbox" name="service" value="Emailing">Emailing
                    </label>
                    <label class="checkbox">
                        <input type="checkbox" name="service" value="Social networks">Social networks
                    </label>
                    <label class="checkbox">
                        <input type="checkbox" name="service" value="Web design">Web design
                    </label>
                </div>

I hope everything is clear :)




how to change value field of checkbox based on whether it is checked or unchecked

I have a checkbox with

<html:checkbox name="cb" property="cb" value="Yes" disabled="true"></html:checkbox>

when i fetch using property i recieve value "yes"

is there any way to have fields like

  1. checked-value
  2. unchecked-value

    • solution/help using html would be great



Second conditional statement is not triggering -

By default all of the checkboxes are checked, and has a parent child relation. When all the checkboxes are unchecked I want to add a class.But The second else if statement is not working -

if($('#treelist :checkbox:not(:checked)').length == 0){ 
   $('.row.cd-feed-wrapper').addClass('visible');
 } else if($('#treelist :checkbox:checked').length == 0){
  $('.row.cd-feed-wrapper').addClass('hidden');
}

The first one when the page loads.

codepen setup : http://ift.tt/2c3LDam

<ul id="treeList">
  <li>
    <input type="checkbox" name="selectedRole" checked> mCRC
  <ul>
  <li>
    <input type="checkbox" name="selectedRole" checked> STIVARGA Efficacy
    <ul>
      <li>
        <input type="checkbox" name="selectedRole" checked> Long-Term Responders
      </li>
      <li>
        <input type="checkbox" name="selectedRole" checked> STIVARGA in Clinical Practice
      </li>
    </ul>
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> STIVARGA AE Management
  </li>

  <li>
    <input type="checkbox" name="selectedRole" checked> Dosing
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> Patient Communication
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> Case Studies
  </li>
</ul>

<li>
  <input type="checkbox" name="selectedRole" checked> GIST
</li>




mardi 30 août 2016

android setKeyListener event not setting the keys as desired

Myself trying to enable/disable a textfield using checkbox as,

 tv = (EditText) findViewById(R.id.tv);
 cb = (CheckBox) findViewById(R.id.cb);
 tv.setFocusable(false);
 tv.setKeyListener(null);
 tv.setEnabled(false);

  cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

           @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked) {
                        tv.setFocusable(true);
                        tv.setEnabled(true);
                        tv.setKeyListener(new DigitsKeyListener(false, true));
                    } else {
                        tv.setFocusable(false);
                        tv.setEnabled(false);
                        tv.setKeyListener(null);
                    }
                }
            }
        );

The above code is in onCreate method. But even when the checkbox checked, the tv.setKeyListener(new DigitsKeyListener(false, true)); doesn't enabling the keys. Where myself missed?




jqyery allways have one checkbox checked

With the following HTML checkbox code

<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010

What changes do I need to make to the following jQuery

 $(function() { 
     $('input[type="checkbox"]').bind('click',function() {
        $('input[type="checkbox"]').not(this).prop("checked", false);
     });
});

so that one of the checkboxes is checked at all times not allowing blank checkboxes?




Click on the checkbox inside div which changes the state of the checkbox. jQuery

Can someone help me with this problem?

$('.check_group').click(function () {
    var check = $(this).children('input')[0];
    check.checked = !check.checked;
    alert(check.checked);
    //run something else
});
<script src="http://ift.tt/1qRgvOJ"></script>
<div class="check_group" style="background-color: rgb(200, 138, 59);">
  <input type="checkbox" />
</div>

So, when I click on the checkbox - change the state of the checkbox, and then triggered jQuery and status changes back.

How to make so that when you click on the div / Checkbox - checkbox has changed and there is an alert?




Aligning custom checkbox issue css

I am tying to align the text of the right of my checkbox. Currently the text is appearing in multiple lines.

I have tried changing the width and giving it a fixed width:

.checkbox span.custom  {
  margin-left: 34px;
  display: inline-block;
  width: 100px; // MY TRY
}

but it is changing the size of the checkbox not the text next to it.

CSS:

* {
  box-sizing: border-box;
}

label {
  display: inline-block;
}

.checkbox {
  position: relative;
  min-height: 24px;
  font-size: 1.6rem;
}

.checkbox input {
  -webkit-tap-highlight-color: transparent;
  height: 10px;
  margin: 6px;
  opacity: 0;
  outline: none;
  position: absolute;
  left: 1px;
  top: 1px;
  width: 10px;
}

.checkbox .custom {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
  display: inline-block;
  height: 24px;
  left: 0;
  position: absolute;
  top: 0;
  width: 24px;
}

.checkbox span {
  display: inline-block;
  margin-left: 34px;
  margin-top: 0;
  position: relative;
  top: 3px;
}

.checkbox input:checked:not(:disabled) + .custom {
  background-color: #0574ac;
  border-color: #0574ac;
}

.checkbox span {
  margin-left: 0px;
}

.checkbox span.custom  {
  margin-left: 34px;
  display: inline-block;
  width: 100px; // MY TRY
}

.checkbox span.custom .radio span.custom {
  margin-left: 34px;
  margin-right: 34px;
  display: flex;
}

.radio input:checked + .custom:after {
  background-color: #0574ac;
  border-radius: 100%;
  border: 3px solid #fff;
  content: "";
  display: block;
  height: 16px;
  position: absolute;
  width: 16px;
}

HTML:

<label for="checkbox1" class="checkbox">
      <input id="checkbox1" type="checkbox" role="checkbox" /><span class="custom">Checkbox 1</span>
</label>

JSFiddle Demo




How to check if all of the checkbox are checked

How can I check if all of my checkboxes are checked or unchecked with jquery,I have child and grandchild input elements-

codepen setup : http://ift.tt/2bzB3Zn

<ul id="treeList">
  <li>
    <input type="checkbox" name="selectedRole"> mCRC
  <ul>
  <li>
    <input type="checkbox" name="selectedRole"> STIVARGA Efficacy
    <ul>
      <li>
        <input type="checkbox" name="selectedRole"> Long-Term Responders
      </li>
      <li>
        <input type="checkbox" name="selectedRole"> STIVARGA in Clinical Practice
      </li>
    </ul>
  </li>
  <li>
    <input type="checkbox" name="selectedRole"> STIVARGA AE Management
  </li>

  <li>
    <input type="checkbox" name="selectedRole"> Dosing
  </li>
  <li>
    <input type="checkbox" name="selectedRole"> Patient Communication
  </li>
  <li>
    <input type="checkbox" name="selectedRole"> Case Studies
  </li>
</ul>

<li>
  <input type="checkbox" name="selectedRole"> GIST
</li>




Checkbox checked if boolean is true with Angular2

I would like to know how to make a checkbox checked if the value is true, and unchecked if false with Angular2.

Adult <input type="checkbox" value="">

is a boolean

Can someone please suggest anything? Thanks




How can I auto select the existing data in a Angular Material Checkbox?

I want to auto select the Checkbox if it already exists in the model

I tried with the following code

Controller

$scope.model = {
  items: [{"key":1, "value": "One"},{"key":2, "value": "Two"},{"key":3, 
  "value": "Three"},{"key":4, "value": "Four"},{"key":5, "value": "Five"}]
};
   $scope.selected = [{"key":2, "value": "Two"},{"key":5, "value": "Five"}];
   $scope.toggle = function(item, list) {
    var idx = list.indexOf(item);
    if (idx > -1) {
        list.splice(idx, 1);
    } else {
        list.push(item);
    }
};

$scope.exists = function(item, list) {
    return list.indexOf(item) > -1;
};

HTML

<div flex="25" ng-repeat="item model.items">
    <md-checkbox  ng-checked="exists(item, selected)" 
        ng-click="toggle(item, selected)">
     
    </md-checkbox>
</div>

But the checkbox for Key '2' and '5' not selected by default.

If I replace the following code,

$scope.exists = function (item, list) {
 for (var i = 0; i < list.length; i++) {
        if (list[i].key === item.key) {
            return true;
        }
    }
    return false;
};

It selects 2 and 5 while page loading but not able un check both. Other 1,3 and 4 works as expected.




Is there a way to have a Check Mark box that if selected it will cross out the entire line of text?

I am trying to have an Excel spreadsheet that has a column of Check Boxes. I would like for when the check mark box is checked then the whole row of text is then crossed off. As in I checked a box to signify that the action was completed but then strikes through all the data in that row.




PHP action when more than one checkbox was selected

I've got a POST form with its action on the same page. The form has many checkboxes and I'd like run some PHP line when the user has checked more than one checkbox (PHP should run after submitting the form).

So basically I'd need following in PHP:

If checked checkboxes of #FormXY > 1
...do something...
else (which means 0 or 1 checked checbox)
...do something else

Thanks in advance, Tom




Apply css on form collection

I'd like to apply this style :

       .tag-wrapper
          %ul
            %li.tag.fa.fa-plus
              = tag.name

on my current code :

= f.input :all_tags, :as => :check_boxes, :collection => @tags.map{|tag| tag.name}

But I don't know how to manage collection. And for know it looks like that : enter image description here

They are all display one over the over and not like a list or any other way which allow the user to click on each item.




Get checkbox value in grid view instead of using foreach loop

I am using foreach loop to get value of checkbox from a grid view and update the records by geting the current user regID on checkbox CheckedChanged event.

In ASPX

   <Columns>
      <asp:TemplateField >
                            <ItemTemplate>
                                <asp:CheckBox ID="cbPaid" runat="server" AutoPostBack="true" OnCheckedChanged="cbPaid_CheckedChanged" Checked='<%# bool.Parse(Eval("status").ToString() == "Paid" ? "True": "False") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>

And in aspx.cs

protected void cbPaid_CheckedChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GdParticipants.Rows)
    {
        CheckBox cbPaid = (CheckBox)row.FindControl("cbPaid");

        if (cbPaid!=null && cbPaid.Checked == true)
        {
            string status = "Paid";
            int amount = Convert.ToInt32(ViewState["EventFee"]);
            DateTime date = DateTime.Now;
            string user = Session["user_id"].ToString();
            string regID = row.Cells[2].Text;

            string type = "Deposit";
            string account = "Participation";
            int balance = BAL.fetch_availableBalance();
            int total_balance = amount + balance;
            string detail = "Participant: "+regID+" fee has been Recieved";
            BAL.updateParticipants(regID, status, amount, user, date);
            BAL.saveBudgetTracking(type,account,amount,0,total_balance,detail,date);

        }
    }
    Response.Redirect("~/show_members.aspx");
}

The problem with this approach is whenever a new user updated a new record by checking a check box it will loop through the whole records and update the current change all over the previous records.

Anyone please guide me how can I get only the current regID from the row on which the checkbox was being checked and the checkbox value on checkbox-CheckedChanged event, instead of a loop?




Binding checkbox to Datatable

I have checkboxes that needs to be bound to a DataTable. Problem is that checkboxes store "YES" and "NO" values in Oracle DB fields, NOT Boolean. How can I bind to those values ?

This doesn't work:

ChkInUse.DataBindings.Add("Checked", dtb, "IN_USE")

I get error: "String was not recognized as a valid Boolean".




using boolean to check model listview state android

Am working saving the current state of a check item while scrolling, and it worked, but i couldn't save the state of the TextView noting the count when the checkbox is checked or unchecked.

this is my Adapter,

NewsAdapter.java

public class TestNewsAdapter extends RealmBaseRecyclerViewAdapter<NewsTrend, TestNewsAdapter.PostsViewHolder> {

public RealmResults<NewsTrend> realmResults;
public Context context;
static  String fbid;
private User user;


private RetrofitInterface restApi;

ArrayList<Boolean> positionArray;



public TestNewsAdapter(Context context, RealmResults<NewsTrend> realmResults,
                       boolean automaticUpdate, User user) {
    super(context, realmResults, automaticUpdate);
    this.realmResults = realmResults;
    this.context = context;
    this.user = user;

    positionArray = new  ArrayList<>(realmResults.size());
    for(int i =0;i<realmResults.size();i++){
        positionArray.add(false);
    }
}

@Override
public PostsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    fbid = user.getId();
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_news, viewGroup, false);
    PostsViewHolder mediaViewHolder = new PostsViewHolder(v);
    return mediaViewHolder;
}

@Override
public void onBindViewHolder(final PostsViewHolder holder, final int position) {

    final NewsTrend postsData = getItem(position);

    holder.itemView.setTag(postsData);
    holder.tvNewsCountLike.setText(""+ postsData.getLike_count());

    Glide.with(context)
            .load(postsData.getImage())
            .centerCrop()
            .placeholder(R.drawable.tw_logo)
            .into(holder.ivNewsImage);



    if (postsData.getLike_status() == 1) {
        holder.ivLike.setChecked(true);
    } else {
        holder.ivLike.setChecked(false);
    }

    holder.ivLike.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(View view, boolean checked) {
            if (checked) {
                like(postsData.getNews_id());
                holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) + 1));
                positionArray.set(position, true);
            } else {
                like(postsData.getNews_id());
                holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) - 1));
                positionArray.set(position, false);
            }
        }
    });
}




@Override
public NewsTrend getItem(int i) {
    return realmResults.get(i);
}

public void swapData(RealmResults<NewsTrend> realmResults) {
    this.realmResults = realmResults;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public int getItemCount() {
    return realmResults.size();
}

public static class PostsViewHolder extends RecyclerView.ViewHolder {


    public ImageView ivFavorite;
    public TextView tvNewsCountLike;

    PostsViewHolder(View itemView) {
        super(itemView);
        ivLike = (ShineButton) itemView.findViewById(R.id.ivLike);

        tvNewsCountLike = (TextView)   itemView.findViewById(R.id.tvNewsCountLike);

            ivLike.setOnCheckStateChangeListener(null);
       }
    }
}




checked box value is undefined in request object

I'm submitting this from using EJS to server and getting all values except the check box value which is undefined when is receive request object

                 <form method="post" action="">

                        <div class="form-group">

                         <label for="title">Title:</label>

                        <input type="text" name="title" class="form-control" id="title" placeholder="Enter Artical Name"></div>

                    <div class="form-group">
                      <label for="email">Email:</label>
                      <input type="email" name="email" class="form-control" id="email" placeholder="Enter email">
                    </div>

                    <div class="form-group">
                      <label for="content">Artical Content:</label>
                      <textarea class="form-control" rows="5" name="artical" id="comment"></textarea>
                    </div>

                    <div class="checkbox">
                      <label><input type="checkbox" value="1" name="active" checked="true"> Published or Not Published</label>
                    </div>

                    <button type="submit" class="btn btn-default">Submit</button>
                  </form>




Display checkbox from loop elements

I have a form to create a new recipe. Each recipe can have multiple tags. I would like to display all the tags possibility and allow the user to check or uncheck them. I'm able to have a pretty display of the tags but I don't know how to turn them into checkboxes...

= simple_form_for @recipe, html: {multipart: true} do |f|
  - if @recipe.errors.any?
    #errors
      %p
        = @recipe.errors.count
        prohibited this recipe from being saved:
      %ul
        - @recipe.errors.full_messages.each do |message|
          %li= message
  .row
    .panel-body
      = f.input :title, input_html: {class: 'form-control'}
      = f.input :description, placeholder: 'Dites nous ce que vous aimez dans cette recette ? où l\'avez-vous découverte ? avec quoi l\'accompagnée vous ? ...', input_html: {class: 'form-control'}
      = f.input :image, input_html: {class: 'form-control'}
      .tag-wrapper
        - @tags.each do |tag|
          %ul
            %li.tag.fa.fa-plus
              = tag.name




Change checked attribute of controlled checkbox (React)

I am new to React and am probably lacking the correct terminology to find a solution to my problem. It cannot be that hard.

I am building a simple app which displays a set of questions, one question at a time. After answering one question, the next question is shown.

I have a component Question that renders 3 checkboxes, each checkbox represents one possible answer to the Question.

{this.props.question.answers.map((answer, index) => {
  return (
    <li className="Question__answer" key={answer.id}>
      <label className="Question__answer-label">
        <input
          className="Question__answer-checkbox"
          type="checkbox"
          value={index}
          onChange={this.props.setAnswer}
          defaultChecked={false} />
        {answer.answer}
      </label>
    </li>

    ...

    <button className="Question__next" type="button" onClick={this.props.onNext} disabled={this.props.isDisabled}>
        Next question
      </button>
  )
})}

Inside my main component Quiz I call the component like this:

<Question step={this.state.step} question={this.state.questions[this.state.step]} setAnswer={this.setAnswer} onNext={this.onNext} isDisabled={this.isDisabled()} />

onNext is my function which increments this.state.step in order to display the next question:

onNext(event) {
    this.setState({step: this.state.step + 1});
}

Everything works fine, except: When the next question is displayed, I want all 3 checkboxes to be unchecked again. Currently they remember their checked state from the previously answered question.




Set checkbox value in React JS

I'm trying to change the value of the checkbox with the onChange function of another input field.

I have something like this :

class price extends React.Component {
constructor(props){
    super(props);

    this.state = {
        minValue: 0,
        maxValue: 20000,
        step: 1000,
        firstValue: null,
        secondValue: null,
        chcboxValue: false
    };

    this.handleChange = this.handleChange.bind(this);
}

componentWillMount(){
    this.setState({firstValue: this.state.minValue, secondValue: this.state.maxValue});
}

handleChange(name, event){
    let value = event.target.value;
    //We set the state value depending on input that is clicked
    if(name === "second"){
        if(parseInt(this.state.firstValue) < parseInt(value)){
            this.setState({secondValue:value});
        }
    }else{
        //The first value can't be greater than the second value
        if(parseInt(value) < parseInt(this.state.secondValue)) {
            this.setState({firstValue: value});
        }
    }

    //We set the checkbox value
    if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)){
        this.setState({chcboxValue: true});
    }else{
        this.setState({chcboxValue: false});
    }
}

render(){
    const language = this.props.language;
    return (
        <div>
            <div className="priceTitle">{language.price}</div>
            <InputRange language={language}
                        firstValue={parseInt(this.state.firstValue)}
                        secondValue={parseInt(this.state.secondValue)}
                        minValue={parseInt(this.state.minValue)}
                        maxValue={parseInt(this.state.maxValue)}
                        step={parseInt(this.state.step)}
                        handleChange={this.handleChange}
                        chcboxValue={this.state.chcboxValue}/>
        </div>
    );
}
}

My InputRange component is something like this :

const inputRange = ({language, firstValue, secondValue, minValue, maxValue, step, handleChange, chcboxValue}) => {
return (
    <div>
        <div className="rangeValues">Range : {firstValue} - {secondValue}</div>


        <section className="range-slider">
            <input type="checkbox" checked={chcboxValue} />
            <input type="range" value={firstValue} min={minValue} max={maxValue} step={step}  onChange={handleChange.bind(this, "first")}/>
            <input type="range" value={secondValue} min={minValue} max={maxValue} step={step} onChange={handleChange.bind(this, "second")}/>

            <div className="minValue">{minValue}</div>
            <div className="maxValue">{maxValue}</div>
        </section>
    </div>
);
};

I that the checkbox value on initial load is set to false. When user changes the values of the price range slider I want that the checkbox value changes to true.

When user changes the values of the price range slider to their initial values (min and max values) I want that the checkbox value again changes to false.

In my exaample it isn't working.

Any ideas?




Create a Dynamic Checkbox and check if it has been checked

So i am trying to create a mobile website with jquery mobile. I have a fieldset with multiple checkboxes like this. The user has to check all of those checkboxes in order to proceed. That works fine so far.

<div>
    <fieldset id="checkBoxContainer" data-role="controlgroup" data-type="vertical">
        <input name="CheckBoxGroup" class="CheckBox" id="CheckBox_1" type="checkbox">
        <label for="CheckBox_1">The first Checkbox</label>
        <input name="CheckBoxGroup" class="CheckBox" id="CheckBox_2" type="checkbox">
        <label for="CheckBox_2">The secondCheckbox</label>
        <input name="CheckBoxGroup" class="CheckBox" id="CheckBox_3" type="checkbox">
        <label for="CheckBox_3">The third Checkbox</label>
    </fieldset>
</div>

Now i wanted to dynamically create those text checkboxes with something like that:

function createCheckBox(theClass, theId) {

    $('#checkBoxContainer').controlgroup("container").append('<label for='
        theId '><input type="checkbox" class='
        theClass ' name="clock-place" "id='
        theId ' />Checkbox</label>');

    $("#checkBoxContainer").enhanceWithin().controlgroup("refresh");

}

But somehow how i cant set the ID and the class based on the Parameter for the input and label element what am i doing wrong how can i do it?
The second question is then how would I check if those dynamically added checkboxes are checked I need the Id somehow dont i how do i solve this problem?
Currently i am checking them like that:

function controlCheckBoxStatus() {
    $("input.CheckBox").on("change", function() {


        if ($("input#CheckBox_1").is(":checked") &&
            ($("input#CheckBox_2").is(":checked")) &&
            ($("input#CheckBox_3").is(":checked"))) {
            checkBoxStatus = true;
            alert("All checkboxes checked!");

        } else {
            checkBoxStatus = false;
        }
    })

}




jQuery - Check and uncheck the 2nd checkbox when first clicked using name attribute

I am trying to check the 2nd checkobx (Delete it!) automatically, when first one (Hide it) is clicked? System generated html doesn't contain any id or class for the checkbox elements. I tried to target the name attribute, but it failed every time.

HTML

<fieldset class="es-el eddhd">
    <div class="es-label">
        <label for="es-eddhd">Hide it</label>
        <br>
    </div>
    <div class="es-fields">
        <span data-required="no" data-type="radio"></span>
        <label>
            <input name="eddhd[]" value="Yes" type="checkbox"> Yes
        </label>
    </div>
</fieldset>
<fieldset class="es-el eddhrd">
    <div class="es-label">
        <label for="es-eddhrd">Delete it!</label>
        <br>
    </div>
    <div class="es-fields">
        <span data-required="no" data-type="radio"></span>
    <label>
        <input name="eddhrd[]" value="Yes" type="checkbox"> Yes
    </label>
    </div>
</fieldset>

jQuery

jQuery(document).ready(function($){
    $("input:checkbox[name='eddhd']").click(function() {
        $(this).parents('.eddhrd::nth-child(2))').siblings("input:checkbox[name='eddhrd']").find('input:checkbox').attr("checked","checked");
    });
});




lundi 29 août 2016

Checkbox Parent and Child Issue in recyclerview

Here my view is like the Country and its states...Like India,America,China etc and there sub States like for India is Delhi,UP,Gujarat for America Is Like Washington DC,LA etc now issue is I am using Checkbox when India is selected its child should select automatically and When America is selected there states should checked automatically here prob is when I select India It select all to American State rather then India I had used Recyclerview for this purpose as i am new i dont have any clue to add Images here.Parent have no issue.But child do have.Here is my code

Parents value in custom Adapter :

    public void onBindViewHolder(final MyViewHolder holder, final int position) {

    dynamiclist1();

    final Employee emp = list.get(position);
    holder.tv.setText(emp.getName());
    if (emp.getName() == "India") {
        holder.chkbox_parent.setTag("India");

    }
    holder.rv.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(context);
    holder.rv.setLayoutManager(llm);
    holder.rv.setHasFixedSize(true);
    holder.chkbox_parent.setTag(emp.getName());
    if (emp.getName() == "India") {
        cuChild = new CustomAdapter_child(context, child1, "India");
    } else {
        cuChild = new CustomAdapter_child(context, child1, "");

    }
    holder.rv.setAdapter(cuChild);
    holder.chkbox_parent.setTag(emp.getName());
    holder.chkbox_parent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            Toast.makeText(context, "" + holder.chkbox_parent.getTag(), Toast.LENGTH_SHORT).show();
            try {
                RecyclerView rv1 = (RecyclerView) itemview.findViewById(R.id.rv2);
                Toast.makeText(context, "" + rv1.getChildCount(), Toast.LENGTH_SHORT).show();
                CheckBox cb;
                TextView txt;
                for (int i = 0; i < rv1.getChildCount(); i++) {



                    cb = (CheckBox) rv1.getChildAt(i).findViewById(R.id.chkbox_child);
                    //txt = (TextView) rv1.getChildAt(i).findViewById(R.id.tv2);
                    Toast.makeText(context, "" + cb.getText(), Toast.LENGTH_SHORT).show();
                    //if (holder.chkbox_parent.getTag() == cb.getTag()) {
                        cb.setChecked(holder.chkbox_parent.isChecked());

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


}

Here is a child Adapter:

    public void onBindViewHolder(MyViewHolder holder, int position) {

    Employee_Child emp = list.get(position);
    holder.tv.setText(emp.getName1().concat("-").concat(this.TAG ).concat(""+position));

    if (this.TAG == "India") {
        holder.chkchild.setText("India");
    }

}

I had used recyclerview in Cardview i.e first recyclerview for Parent and cardview and recyclerview for its child In short I Had used nested Recyclerview.I had seen many examples but not got any single solution. Thank You in advance




Parent and child grandchild checkboxes

<div class="col-lg-3 col-xs-3 col-left">
            <h4>Topics</h4>
            <div class="checkbox">
                <label>
                    <input type="checkbox" value="1" checked> mCRC
                </label>
            </div>
            <div class="checkbox ml10">
                <label>
                    <input type="checkbox" value="2" data-parent="1" id="stivarga-efficacy" checked> STIVARGA Efficacy
                </label>
            </div>
            <div class="checkbox ml20">
                <label>
                    <input type="checkbox" value="3" data-parent="1,2" id="long-term" checked> Long-Term Responders
                </label>
            </div>
            <div class="checkbox ml20">
                <label>
                    <input type="checkbox" value="4" data-parent="1,2" id="stivarga-in-clinical" checked> STIVARGA in Clinical Practice
                </label>
            </div>
            <div class="checkbox ml10">
                <label>
                    <input type="checkbox" value="5" data-parent="1" checked> STIVARGA AE Management
                </label>
            </div>
            <div class="checkbox ml10">
                <label>
                    <input type="checkbox" value="6" data-parent="1" checked> Dosing
                </label>
            </div>
            <div class="checkbox ml10">
                <label>
                    <input type="checkbox" value="7" data-parent="1" checked> Patient Communication
                </label>
            </div>
            <div class="checkbox ml10">
                <label>
                    <input type="checkbox" value="8" data-parent="1" checked> Case Studies
                </label>
            </div>

            <div class="checkbox">
                <label>
                    <input type="checkbox" value="9" checked> GIST
                </label>
            </div>

        </div>

There are some checkboxes on a page.I have need:

  1. Check all childs if parent is checked.
  2. Uncheck parent if all childs are unchecked.
  3. Check parent if at least one child is checked.

How can I accomplish this ? I found a solution here Parent and child checkboxes it, I am having problem with the grand child functionality

codepen http://ift.tt/2c6ve42




Correct radio syntax (not checkbox)

I have this syntax to provde a series of checkboxes. This works fine, however no matter what syntax I use to get radios I get nothing, just a blank space.

I've tried 'type' => 'radio', and tried 'type' => 'radiogroup',

this what I'm using now.

array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),

any ideas? Is there a different way to get radios instead of checkboxes?




PHP array checkbox issue, keep the 'right' boxes checked after submit

I am currently created a checkbox system based on each school in an array. Everything works fine except, that after submit, only the first checkboxes are checked. Example: I have 10 checkboxes, and check box number 4,5 and 6. After submit, box 1,2 and 3 are checked. I want box 4,5 and 6 to keep their selection after submit. Hope that you can imagine by problem.

<!--Start Checkbox system for schools-->
<form method="POST">
<?php
$q = "SELECT id, name FROM $school_table";  
$result = mysqli_query($con, $q);
    while(($row =  mysqli_fetch_array($result))) {
    //First line of <input>
    echo '<input type="checkbox" name="check_list[]" value="';  

    //Value of the input (school ID)
    echo $row['id'] .'"';                                       

    //Keep the box checked after submit. PROBLEM MIGHT BE HERE!!!
    if(isset($_POST['check_list'][$row['id']])){echo 'checked="checked"';} 

    //Echos the school name out after the checkbox. 
    echo '>' . $row['name'] . " <br> ";                         
    }
?>
<script language="javascript">
//Select all on/off function
function checkAll(bx) {
    var cbs = document.getElementsByTagName('input');
    for(var i=0; i < cbs.length; i++) {
            if(cbs[i].type == 'checkbox') {
            cbs[i].checked = bx.checked;
            }
    }
}
</script>
<!--Check all mark. Works with Javascript written above-->
<input type="checkbox" name="check_all" onclick="checkAll(this)" <?php if(isset($_POST['check_all'])){echo "checked";} ?>> Check all: On/Off
<input type="submit" name="submit" value="sort"> 
</form>
<!--End Checkbox system for schools-->

Image of the problem. Take a look

Hope you guys can help me out :)




Checkbox Change event to trigger another field to be required

I have a form with several checkbox fields and a corresponding Comments fields for each checkbox. I dynamically create these fields. For example, the checkbox field, tag1, would correspond to comments1. When the checkbox is checked, I don't want to require comments. When it is not checked, I want to require comments.

Sometimes the fields are pre-populated based on a user's last input. In other words, the checkbox may already be checked when the page loads or it may not be. I have logic set to build the corresponding comments field as required or not required based on this.

Everything situation seems to be working except one. When I check the box and then uncheck the box, the form allows me to submit with no comments. Below is what I have tried.

$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#comments' + this.id.replace('tag', ''));


  otherInput.removeProp('required', !checkbox.is(':checked'));
  if (!checkbox.not(':checked')){
    otherInput.prop('required',true);
  }
});

--------------------second attempt

$(document).on('change', 'input[type=checkbox]', function() {
  var checkbox = $(this),
    otherInput = $('#comments' + this.id.replace('tag', ''));

  otherInput.prop('required', !checkbox.not(':checked'));
  otherInput.removeProp('required', !checkbox.is(':checked'));

});

Both of these solve the same situations, except the one noted above. Please advise.




Updating MySQL table with PHP and checkboxes in WordPress

On my website enter link description here I'm using checkbox buttons for updating data in a MySql table (pages are with login) and use this code in PHP that's working fine:

<?php
    $sql="SELECT *,cast(DATE_FORMAT(datum,'%d-%m-%Y ') AS CHAR(32)) as datum FROM wedstrijden";
    $result=mysqli_query($db,$sql);

    $count=mysqli_num_rows($result);

?>
<table style="width: 100%;">
<tr>
<td><form name="frmactive" action="1fanionchange.php" method="post">
<tr>
<td colspan="6"><input name="activate" type="submit" id="activate" value="Open selected" />

</tr>
<tr>
<td>&nbsp;</td>
</tr><tr>
<td align="center"><!--<input type="checkbox" name="allbox" title="Select or Deselct ALL" style="background-color:#ccc;"/> --></td>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Datum</strong></td>
<td align="center"><strong>Uur</strong></td>
<td align="center"><strong>Thuis</strong></td>
<td align="center"><strong>Uit</strong></td>
</tr>
<?php
 while($rows=mysqli_fetch_array($result)){
?>
<tr>
<td align="center"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td align="center"><? echo $rows['id']; ?></td>
<td align="center"><? echo $rows['datum']; ?></td>
<td align="center"><? echo $rows['uur']; ?></td>
<td align="center"><? echo zoeknaam($rows['thuisploeg']); ?></td>
<td align="center"><? echo zoeknaam($rows['uitploeg']); ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6"><input name="activate" type="submit" id="activate" value="Open selected" />
</tr>
</form>
</td>
</tr>
</table>

But when I use the same code in WordPress (I'm trying to make the website in WordPress), it is not working and I get no records. When I put this code: echo $count. "<br />"; I get the right number of records in that table, only the records are not showed?

Any idea how to handle the problem? Thanks.

PS. I use the plugin phpexec in WordPress!




jQuery, getting the array of values corresponding to selected checkboxes

<form id="myform">
<table>         
<tbody>
    <tr>
    <td class="textcenter">
        <input type="checkbox" name="domains[]" value="mydomainname.com" checked=""> 
        <input type="hidden" name="action[]" value="buy">
    </td>
    <td>mydomainname.com</td>
    <td >Available! Choose the number of years</td>
    <td class="textcenter">
        <select class="leftmargin10 bottommargin10 form-control" name="period[]">
            <option value="1">1 Year/s @ $24.99</option>
            <option value="2">2 Year/s @ $49.98</option>
            <option value="3">3 Year/s @ $74.97</option>
        </select>
    </td>
    </tr> 
    <tr>
    <td class="textcenter">
        <input type="checkbox" name="domains[]" value="mydomainname.net"> 
        <input type="hidden" name="action[]" value="transfer">
    </td>
    <td>mydomainname.net</td>
    <td>Available! Choose the number of years</td>
    <td class="textcenter">
        <select class="leftmargin10 bottommargin10 form-control" name="period[]">
            <option value="1">1 Year/s @ $24.99</option>
            <option value="2">2 Year/s @ $49.98</option>
            <option value="3">3 Year/s @ $74.97</option>
        </select>
    </td></tr> 
</tbody></table>

<button type="submit" name="submitButton" class="btn-yellow" value="Buy">Register Now!</button>
</form>

There'll be 10-15 rows like above.

On the jQuery side I have:

$("#domainform").submit(function(){
        event.preventDefault();
        var domains= $('input[name="domains[]"]:checked').map(function(){
                return $(this).val();
            }).get();

        var action= $('input[name="action[]"]').map(function(){
            return $(this).val();
            }).get();

        var period= $('select[name="period[]"]').map(function(){
            return $(this).val();
            }).get();
});

This code currently gives me the correct checkbox values but it gives the values for all the dropdowns (regardless of checkbox statuses). How do I tie these two together and get only the values for the dropdowns corresponding to the checked checkboxes.

Thank you!




Select all issue in Parent and Child Checkbox

Well My task is to perform parent and child Checkbox in recyclerview like there are 4 states and all states have there few cities.Now problem is When I checked in parent(State) but properly cities are not get selected.lets say Gujarat State have surat,ahmedabad cities but when we select Gujarat checkbox it got select all in other state child maharastra cities.

Here is a code(this code is in master Custom adapter):

public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_row, parent, false); MyViewHolder myViewHolder = new MyViewHolder(itemview);

    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    dynamiclist1();
    final Employee emp = list.get(position);

    holder.setIsRecyclable(false);
    holder.tv.setText(emp.getName());
    if (emp.getName() == "Gujarat") {
        holder.chkbox_parent.setTag("Gujarat");

    }
    holder.rv.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(context);
    holder.rv.setLayoutManager(llm);
    holder.rv.setHasFixedSize(true);
    holder.chkbox_parent.setTag(emp.getName());
    if (emp.getName() == "Gujarat") {
        cuChild = new CustomAdapter_child(context, child1, "Gujarat");
    } else {
        cuChild = new CustomAdapter_child(context, child1, "");

    }
    holder.rv.setAdapter(cuChild);
    holder.chkbox_parent.setTag(emp.getName());
    holder.chkbox_parent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            Toast.makeText(context, "" + holder.chkbox_parent.getTag(), Toast.LENGTH_SHORT).show();
            try {
                RecyclerView rv1 = (RecyclerView) itemview.findViewById(R.id.rv2);
                Toast.makeText(context, "" + rv1.getChildCount(), Toast.LENGTH_SHORT).show();
                CheckBox cb;
                TextView txt;
                for (int i = 0; i < rv1.getChildCount(); i++) {



                    cb = (CheckBox) rv1.getChildAt(i).findViewById(R.id.chkbox_child);
                    //txt = (TextView) rv1.getChildAt(i).findViewById(R.id.tv2);
                    Toast.makeText(context, "" + cb.getText(), Toast.LENGTH_SHORT).show();

                        cb.setChecked(holder.chkbox_parent.isChecked());

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


}

(this is child Custom adapter):

public void onBindViewHolder(MyViewHolder holder, int position) {

    Employee_Child emp = list.get(position);
    holder.tv.setText(emp.getName1().concat("-").concat(this.TAG ).concat(""+position));

    if (this.TAG == "Gujarat") {
        holder.chkchild.setText("Gujarat");
    }

}




WPF MVVM CheckBoxes

I'm pretty new to the MVVM style of programming. The problem I am having is, I'm trying to set the property of a checkbox when the wpf window loads. I do not need the property to be able to be changed. I merely need to show that it is checked or not.

XAML:

<CheckBox x:Name="UpdateClosingCostAutoResult"  Grid.Column="1" IsHitTestVisible="False" Focusable="False" IsChecked="{Binding IsSelected}" />

ViewModel:

private bool _isSelected = true; public bool IsSelected { get { return _isSelected; } set { SetProperty(ref _isSelected, value); } }

Not entirely sure if the ViewModel is correct or even remotely going in the right direction.




JavaFX8 CheckBoxTreeItem disable antialiasing in popup

In order for the end-user to constrain a search to some columns of the main TableView, I needed a treeview with checkboxes. I decided to embed this TreeView in a popup, showing on click on a custom button.

I have created the following class, inspired from the question: Java FX8 TreeView in a table cell

public class CustomTreeMenuButton extends MenuButton {
    private PopupControl popup = new PopupControl();
    private TreeView<? extends Object> tree;
    private CustomTreeMenuButton me = this;

    public void setTree(TreeView<? extends Object> tree){
        this.tree=tree;
    }

    public CustomTreeMenuButton() {
        super();
        this.addEventHandler(MouseEvent.MOUSE_CLICKED,
                        new EventHandler<MouseEvent>() {

                            @Override
                            public void handle(MouseEvent event)
                            {
                                if(!popup.isShowing()){

                                    Bounds b = me.localToScreen(me.getBoundsInLocal());
                                    double x = b.getMinX();
                                    double y = b.getMaxY();


                                    popup.setAutoHide(true);
                                    //popup.setAutoFix(true);
                                    popup.setAnchorX(x);
                                    popup.setAnchorY(y);

                                    popup.setSkin(new Skin<Skinnable>(){
                                        @Override
                                        public void dispose() {
                                        }
                                        @Override
                                        public Node getNode() {
                                            return tree;
                                        }
                                        @Override
                                        public Skinnable getSkinnable() {
                                            return null;
                                        }
                                    });;
                                    popup.show(me.getScene().getWindow());

                                }
                            }
                        });
    }
}

The tree I am working with contains CheckBoxTreeItem objects, and while the popup is working, there is some weird blur on all checkboxes, whenever the focus is not on a checkbox. (See GIF below)

CheckBoxTreeItem Blur

First, I was thinking it was maybe an antialiasing problem, but popup.getScene().getAntiAliasing().toString() returns DISABLED

Then, I saw that non integer anchor points could cause problems. However popup.setAutoFix(true) did nothing, nor did the following:

popup.setAnchorX(new Double(x).intValue());
popup.setAnchorY(new Double(y).intValue());

It might be worth noting that I am working with FXML.

How can I get sharp checkboxes regardless of their focus ?




af:selectBooleanCheckbox (SelectAll checkbox) is not updating the chckboxes the first time i click on it

I'm new to ADF tables so forgive me if this sounds stupid . i have a table with a column containing check boxes for each row . i want to add a (Select/deselect All) checkBox on the checkBoxes column header . my problem is this , whenever i check the (Select All) checkbox , it selects all the rows , but it doesn't put the (check) mark on the checkboxes , which means ; the rows are actually selected but the checkboxes are not checked.

the second time i do that , everything works fine , the rows are selected and the checkboxes are checked.

please advise .

Checkbox column and header:

<af:column sortProperty="#{bindings.myView.hints.SelectRow.name}" 
   sortable="false"
   id="vheck1">
   <af:selectBooleanCheckbox styleClass="checkboxPaddingTable" autoSubmit="true" immediate="true" value="#{row.SelectedRow}" id="checkBox1"/>
   <f:facet name="header">
      <af:selectBooleanCheckbox id="selectAllCheckBox" 
         immediate="true"
         valueChangeListener="#{myBean.selectAllCheckBox}" 
         autoSubmit="true"/>
   </f:facet>
</af:column>




checkbox onchange firing twice

I'm currently working on this page: http://ift.tt/2bwHfhZ I'm attaching an onchange event on checkboxes like this:

                    $("input[type='checkbox'][name='auswahl[]']").on("change", function () {
                        alert($(this).attr("id") + ' ' + $("label[for='" + $(this).attr("id") + "']").text() + $(this).attr("checked"));
                    });

The checkboxes look like this:

<input type="checkbox" name="auswahl[]" id="aus_nunatsiaqnews_ca"><label for="aus_nunatsiaqnews_ca" title="Canada">Nunatsiaq News</label>

Unfortunately the event is firing twice. When I isolate the code given above and put it on a test page everything is fine and the event is firing only once. Need help.




dimanche 28 août 2016

Checkbox becomes redundant after returning to a view

I am trying to have a checkbox on my homepage, which when checked, should take me to an another view, else, displays an error message on the same view.

This works fine the first time only. If unchecked, it displays the error, and if checked, renders the next view.

However, when I return to this homepage using back button, this time the checkbox becomes redundant. Even unchecking it renders the next page correctly.

If I remove all the views of the ViewGroup, it removes them permanently, and the homepage is empty once I return to it. I believe the checkbox needs to be reset every time I return to the view. However, I am unable to do the same.

Please find my code below(I am a beginner to Android development):

    public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE="com.android.AI";
public boolean isCheckBoxClicked=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
    //isChecked is the onClick attribute for checkbox in the main.xml here
public void isChecked(View view){
    boolean isChecked= ((CheckBox) view).isChecked();
    if(isChecked){
        isCheckBoxClicked=true;
    }
    else{
        isCheckBoxClicked=false;
    }
}
//Send message is onClick for a submit button
public void sendMessage(View view){
    if(isCheckBoxClicked) {
        Intent intent = new Intent(this, SeniorTeam.class);
        startActivity(intent);
    }
    else {
        TextView acceptTerms = new TextView(this);
        acceptTerms.setTextSize(15);
        acceptTerms.setText("Please accpet terms and conditions before proceeding");
        ViewGroup terms = (ViewGroup) findViewById(R.id.activity_main);
        terms.addView(acceptTerms);
    }
}

}




HTML value support multiple custom field values

I create a custom field AJAX Post filter, its filter values correct way.. Now i need to make it more optional after that it support multiple values of one custom field..

Working This way:

Custom field Key & Value ===> display = 4 ... This is for 1st input others value will be 5,6 and 7.

<div class="display">   
    <li><input type="checkbox" name="display" value="4" class="br"> 4 inch  </li>
    <li><input type="checkbox" name="display" value="5" class="br"> 5 inch  </li>
    <li><input type="checkbox" name="display" value="6" class="br"> 6 inch </li>
    <li><input type="checkbox" name="display" value="7" class="br"> 7 inch </li>
</div>

Required That way:

Custom field Key & Value ===> display = 3.5 .. for first input

<div class="display">   
    <li><input type="checkbox" name="display" value="1.0 - 4" class="br"> Below - 4.0 inch  </li>
    <li><input type="checkbox" name="display" value="4.1 - 5" class="br"> 4.1  - 5 inch  </li>
    <li><input type="checkbox" name="display" value="5.1 - 6" class="br"> 5.1  - 6.0 inch </li>
    <li><input type="checkbox" name="display" value="6.1 - 8" class="br"> 6.1  - above inch  </li>
</div>

Required in More Detail:

when i put value 1 to 4 in custom field then first checkbox filter it.. How to manage in input tag value 1 - 4 that will support custom field values that will also between 1 - 4??

In others words inside input tag value support multiple values.




Post Multiple Checkbox from Table To Database Using Codeigniter

I've the problem to post my checkbox to database. Please help me...

Here is my view :

<table>
    <tr>
        <td>
            <input type='hidden' name='userid[]' value='1'>
            <input type='text' name='username[]' value='username1'> 
        </td>
        <td>
            <input type='checkbox' name='as_admin[]' value=1>
        </td>
    </tr>
    <tr>
        <td>
            <input type='hidden' name='userid[]' value='2'>
            <input type='text' name='username[]' value='username2'> 
        </td>
        <td>
            <input type='checkbox' name='as_admin[]' value=1>
        </td>
    </tr>
</table>

This is my controller :

$this->Model_user->insert_user();

And this is my model :

function insert_user(){
    $user_count = count($this->input->post('userid'));
    $userid     = $this->input->post('userid');
    $username   = $this->input->post('username');
    $as_admin   = $this->input->post('as_admin');

    for ($i=0; $i < $user_count; $i++){
        $info_user = array(
            'user_id'   => $userid[$i],
            'user_name' => $username[$i],
            'as_admin'  => $as_admin[$i],
        );
        $this->db->insert($info_user);
    }
}

And the problem is when 'username2' mark as admin (second row checkbox checked), in the database will be like this :

|user_id|user_name|as_admin|
|   1   |username1|   1    |
|   2   |username2|   0    |

it should be like this :

|user_id|user_name|as_admin|
|   1   |username1|   0    |
|   2   |username2|   1    |

Does anyone now how to save those thing, Please...

Thanks in advance...




Checking all the checkboxes at once but not in XAML

I'm trying to learn how to use checkboxes more efficiently, and I found this example on how to accomplish something that I am trying to accomplish but I don't want to do it in XAML.

<CheckBox Content="Do Everything" IsChecked="{Binding DoEverything}" IsThreeState="True"/>
<CheckBox Content="Eat" IsChecked="{Binding DoEat}" Margin="20,0,0,0"/>
<CheckBox Content="Pray" IsChecked="{Binding DoPray}" Margin="20,0,0,0"/>
<CheckBox Content="Love" IsChecked="{Binding DoLove}" Margin="20,0,0,0"/>

So what it does is it checks all 3 if 1 is checked,

How do I accomplish this but with C# code.




customized checkbox inside the sidebar is not working as expected and i am not sure how to fix it

I am trying to customize the checkbox inside the sidebar but it is not working as the tick mark is coming out of checkbox .

please refer the image also . the Tick mark should come inside the checkbox when it is clicked . I am not sure how to make this work ,please suggest how to fix it .

            CSS for sidebar and the customized checkbox, tick mark should come inside the checkbox but it is showing outside when clicked : 
                #wrapper {
                  padding-left: 0;
                  -webkit-transition: all 0.5s ease;
                  -moz-transition: all 0.5s ease;
                  -o-transition: all 0.5s ease;
                  transition: all 0.5s ease;
                }
                #sidebar-wrapper {
                  z-index: 1000;
                  position: fixed;
                  left: 250px;
                  width: 0;
                  height: 100%;
                  margin-left: -250px;
                  overflow-y: auto;
                  background: grey;
                  -webkit-transition: all 0.5s ease;
                  -moz-transition: all 0.5s ease;
                  -o-transition: all 0.5s ease;
                  transition: all 0.5s ease;
                }
                /* Sidebar Styles */
            
                .sidebar-nav {
                  position: absolute;
                  top: 0;
                  width: 200px;
                  margin: 0;
                  padding: 0;
                  list-style: none;
                }
                .sidebar-nav li {
                  text-indent: 20px;
                  line-height: 40px;
                }
                .sidebar-nav li {
                  display: block;
                  text-decoration: none;
                  color: #999999;
                  border: 2px solid red;
                }
                .sidebar-nav li:hover {
                  text-decoration: none;
                  color: green;
                  background: rgba(255, 255, 255, 0.2);
                }
                .sidebar-nav li:active,
                .sidebar-nav li:focus {
                  text-decoration: none;
                }
                @media(min-width:768px) {
                  #wrapper {
                    padding-left: 250px;
                  }
                  #wrapper.toggled {
                    padding-left: 0;
                  }
                  #sidebar-wrapper {
                    width: 250px;
                  }
                }
                .sidebar-nav li input\[type="checkbox"\]:not(:checked),
                .sidebar-nav li input\[type="checkbox"\]:checked {
                  position: absolute;
                  left: -9999px;
                }
                .sidebar-nav li input\[type="checkbox"\]:not(:checked) + label,
                .sidebar-nav li input\[type="checkbox"\]:checked + label {
                  position: relative;
                  padding-left: 25px;
                  cursor: pointer;
                  height: 40px;
                  width: 200px;
                  left: -20px;
                }
                /* checkbox aspect */
            
                .sidebar-nav li input\[type="checkbox"\]:not(:checked) + label:before,
                .sidebar-nav li input\[type="checkbox"\]:checked + label:before {
                  content: '';
                  position: absolute;
                  left: 5px;
                  top: 15px;
                  width: 18px;
                  height: 18px;
                  border: 1px solid black;
                  background: #f8f8f8;
                }
                /* checked mark aspect */
            
                \[type="checkbox"\]:not(:checked) + label:after,
                \[type="checkbox"\]:checked + label:after {
                  content: '✔';
                  position: absolute;
                  top: 14px;
                  left: 6px;
                  width: 18px;
                  height: 18px;
                  font-size: 14px;
                  line-height: 0.8;
                  color: white;
                  background: #76bfa3;
                  transition: all .2s;
                }
                \[type="checkbox"\]:not(:checked) + label:after {
                  opacity: 0;
                  transform: scale(0);
                }
            
            
            HTML for sidebar and the customized checkbox  : 
            
                <div id="wrapper">
            
                  <!-- Sidebar -->
                  <div id="sidebar-wrapper">
                    <ul class="sidebar-nav">
                      <li>
                        <input type="checkbox" id="test1" />
                        <label for="test1">PLK-AL10</label>
                      </li>
                      <li>
                        <input type="checkbox" id="test1" />
                        <label for="test1">PLK-AL10</label>
                      </li>
                      <li>
                        <input type="checkbox" id="test1" />
                        <label for="test1">PLK-AL10</label>
                      </li>
                      <li>
                        <input type="checkbox" id="test1" />
                        <label for="test1">PLK-AL10</label>
                      </li>
            
                    </ul>
                  </div>
                  </div>
            
][1] [1]: http://ift.tt/2buDMoy


How to add checkbox items from a table to a list in Python with PyQt?

I have built a program in Python that runs a GUI and displays various tables. The format I have been using works so far, but now I have to add a checkbox column to the table, and i really don't know what to do. My teacher doesn't know how to use PyQt. The table has a name field, an email field, and a check field.

here is the table with checkbox I have currently:

def trigger_file_delete_student(self):
    self.label_title.setText("Students list")
    self.tableName = "StudentList"
    self.cur.execute("""SELECT FullName, EmailAddress FROM StudentProfile""")
    self.all_data = self.cur.fetchall()
    self.table.setRowCount(len(self.all_data))
    self.table.setColumnCount(3)
    self.tableFields = ['Full name', 'Email address', "Check"]
    self.table.setHorizontalHeaderLabels(self.tableFields)
    self.chkBoxItem = QtGui.QTableWidgetItem()
    self.chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    self.chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
    for i, item in enumerate(self.all_data):
        FullName = QtGui.QTableWidgetItem(str(item[0]))
        EmailAddress = QtGui.QTableWidgetItem(str(item[1]))
        self.table.setItem(i, 0, FullName)
        self.table.setItem(i, 1, EmailAddress)
        self.table.setItem(i, 2, self.chkBoxItem)

Here is a screenshot of what happens when run:

How do I get it so that when a button is clicked, all the names that are ticked get added to a list?

I only have a couple of other tables that I have set up, so if you think it would be better for me to try this in a different table format to make it easier, I can easily change to that. I have never done any work on tables in PyQt GUIs before, so I really have no idea how I am meant to do things.




how show checkboxes's names onClick on checkboxes

this method:

public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }

works onClick a button;but i want that this method works when i click on all checkbox.

This is my code:

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{



    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";
    private Spinner spinner;
    String selState;
    EditText cristo;
    private String zao;
    private CheckBox ck;
    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);





        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
    //  txtName = (TextView) rootView.findViewById(R.id.name);
    //  txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);
        //spinner  = (Spinner) rootView.findViewById(R.id.simpleSpinner);
//      selState = (String) spinner.getSelectedItem().toString();
        //cristo=(EditText)rootView.findViewById(R.id.editText2);
        ck=(CheckBox)rootView.findViewById(R.id.chk_box);




        return rootView;
    }







    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella)"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }



    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità();

            }
        }
        Toast.makeText(
                getActivity(),
                "Clicked on Pizza: " + pizzeOrdinate + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)


    public String showResultTotale2(View v) {

        //selState=cristo.getText().toString();


        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità();

            }
        }
        return pizzeOrdinate;
    }


    public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }





}

Who can help me?

THANKS IN ADVANCE!




how show TOAST every click on checkbox in list view

i need to show TOAST every click on checkbox into my list view.

this is my code:

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{



    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";
    private Spinner spinner;
    String selState;
    EditText cristo;
    private String zao;
    private CheckBox ck;
    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);





        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
    //  txtName = (TextView) rootView.findViewById(R.id.name);
    //  txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);
        //spinner  = (Spinner) rootView.findViewById(R.id.simpleSpinner);
//      selState = (String) spinner.getSelectedItem().toString();
        //cristo=(EditText)rootView.findViewById(R.id.editText2);
        ck=(CheckBox)rootView.findViewById(R.id.chk_box);




        return rootView;
    }







    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella)"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }



    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità();

            }
        }
        Toast.makeText(
                getActivity(),
                "Clicked on Pizza: " + pizzeOrdinate + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)


    public String showResultTotale2(View v) {

        //selState=cristo.getText().toString();


        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità();

            }
        }
        return pizzeOrdinate;
    }

the method showResultTotale2() works if i click on button, but i want the same method that works on every click on checkbox.

Who can help me?Thanks in advance!