mardi 31 décembre 2019

How to disable or inactive checkbox when select current in jQuery

I want to disable other checkbox when current checkbox is checked or selected.

Following is my code. I have tried but not work

HTML

<input type="checkbox" name="test" id="test" class="test">One
<input type="checkbox" name="test" id="test" class="test">Two
<input type="checkbox" name="test" id="test" class="test">Three
<input type="checkbox" name="test" id="test" class="test">Four
<input type="checkbox" name="test" id="test" class="test">Five

JQuery Script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){

        $(".test").each(function(){
            if($(this).is(':checked')){
                $(this).prop('checked',true);
                $('.test').prop('checked',false);
            }
        })
    })  
</script>



How can I know which row is checked using checkbox and listview?

  1. Below is ListView Item Class

     public class CategoryItem06 {
    
     private String text;
     private boolean checked;
    
     public void setText(String text) {
     this.text = text;
     }
    
     public String getText() {
     return this.text;
     }
    
     //    public void setCheck(boolean checked) {
     this.checked = checked;
     }
    
     //    public boolean getCheck() {
     return this.checked;
     }
     }
    
  2. Below is Adapter

    public class CategoryAdapter06 extends BaseAdapter {
    
      public ArrayList<CategoryItem06> listViewItemList = new ArrayList<CategoryItem06>() ;
    
      public CategoryAdapter06() {
    
      }
    
      @Override
      public int getCount() {
      return listViewItemList.size() ;
      }
    
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
    
      final int pos = position;
      final Context context = parent.getContext();
    
      if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) 
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.category_item06, parent, false);
       }
    
      TextView textTextView = (TextView) convertView.findViewById(R.id.textView1) ;
      CheckBox checkBox=(CheckBox) convertView.findViewById(R.id.checkBoxMafia);
    
      CategoryItem06 listViewItem = listViewItemList.get(position);
    
      textTextView.setText(listViewItem.getText());
      checkBox.setChecked(listViewItem.getCheck());
      return convertView;
      }
    
      @Override
      public long getItemId(int position) {
      return position ;
      }
    
      @Override
      public Object getItem(int position) {
      return listViewItemList.get(position) ;
      }
    
      public void addItem( String text) {
      CategoryItem06 item = new CategoryItem06();
      item.setText(text);
    
      listViewItemList.add(item);
      }
      }
    
  3. Below is Checkable Relative Layout

    public class CategoryCheckableRelativeLayout extends RelativeLayout implements Checkable {
    
    public CategoryCheckableRelativeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    // mIsChecked = false ;
    }
    @Override
    public boolean isChecked() {
    CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
    return cb.isChecked();
    // return mIsChecked ;
    }
    
    @Override
    public void toggle() {
    CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
    
    setChecked(cb.isChecked() ? false : true);
    // setChecked(mIsChecked ? false : true) ;
    }
    
    @Override
    public void setChecked(boolean checked) {
    CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
    
    if (cb.isChecked() != checked) {
        cb.setChecked(checked);
    }
    } 
    }
    
  4. Below is Activity that uses ListView

    public class CategorySelection06 extends AppCompatActivity {
    Singleton s1 = Singleton.getInstance();
    ListView listview;
    // Creating Adapter
    CategoryAdapter06 adapter = new CategoryAdapter06();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category_selection06);
    
    listview = (ListView) findViewById(R.id.listview1);
    listview.setAdapter(adapter);
    
    // Adding Items
    adapter.addItem("Pets");
    adapter.addItem("Singers");
    adapter.addItem("Game");
    adapter.addItem("Nations");
    
    Button button = findViewById(R.id.button6);
    
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < adapter.listViewItemList.size(); i++) {
                if (adapter.listViewItemList.get(i).getCheck()) {
                    s1.ListViewCategory.add(adapter.listViewItemList.get(i).getText());
                }
            }
            Intent intent = new Intent(getApplicationContext(), RoleSelection07.class);
            startActivity(intent);
            finish();
            }
       });
     }
     }
    

My ListView's form is like this: TextView ------- Checkbox

I want to make an Activity like this: if user checks checkbox, then the checked row's text is saved in ArrayList in Singleton class.

For example, if a user checked checkbox of "Pets" and "Nations" then these words goes into the ArrayList s1.ListViewCategory, which is in Singleton class.

I've tried for loops and if statements in CategorySelectionActivity like this:

    button.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
            for (int i = 0; i < adapter.listViewItemList.size(); i++) {
                if (adapter.listViewItemList.get(i).getCheck()) {
                    s1.ListViewCategory.add(adapter.listViewItemList.get(i).getText());
                }
            }
            Intent intent = new Intent(getApplicationContext(), RoleSelection07.class);
            startActivity(intent);
            finish();
            }

However,getCheck() doesn't work because setCheck() is not in the addItem() in CategoryAdapter class.

I tried to put setCheck() in the addItem() method , but then I have to put another parameter in add(), then I got red lines and errors.

Since I am a novice, I copied these codes from sites, but I don't really get the idea of using CheckableRelativeLayout.

This Layout shows that the checkbox is checked or not, but it doesn't indicate which row is checked.

To sum up, my question is ' how can I get texts from multiple rows that are checked, and know which row is checked ?

I know the question is super long, but I really need to solve this problem... I will be super grateful if someone answers my question Thank you




lundi 30 décembre 2019

Set values on ionic checkbox and save the values in storage - Ionic 4

I am trying to make a TV Show Tracking application, with the help of checkbox I want the user to mark what episodes he/she watched. And I want with SQLite storage to save the checkboxes value and load them when the user opens the modal of that show.

With the functions I have, when I click a certain checkbox that episode is added to the array selected, let's say I add 3 episodes as watched and by mistake, I uncheck one of the three episodes, all of them are deleted from the array selected. I want to fix that, and also also to be able to save the "watched" episodes in the storage and get their values(watched-checked, not watched-unchecked) when the user opens the modal of that show.

The data that the API returns per season episodes it looks like this: Picture 1

Visual image: Picture 2

HTML:

<button ion-button color="dark" (click)="checkAll()">Mark all as watched</button>
  <ion-item *ngFor="let episodes of seasonepisodes; let i = index;">
    <ion-thumbnail style="width: 150px; height: 100px;" slot="start">
      <img src="https://image.tmdb.org/t/p/w300">
    </ion-thumbnail>
    <ion-card-subtitle>Episode :
      <br>
      
      <br>
      
    </ion-card-subtitle>
    <ion-checkbox slot="end" color="dark" (ionChange)="selectMember(episodes)" 
    [(ngModel)]="episodes.checked"></ion-checkbox>
</ion-item>

TS:

seasonepisodes = null;
this.seasonepisodes = ((this.seasondetails || {}).episodes); (this gets only the episodes in particular season - it returns an array of objects(see Picture 1)

selected: any = [];

 checkAll(){
   for(let i =0; i <= this.seasonepisodes.length; i++) {
      this.seasonepisodes[i].checked = true;
   }
   console.log(this.seasonepisodes);
 }

  selectEpisode(data){
    if(data.checked == true) {
      this.selected.push(data);
    } else {
     let newArray = this.selected.filter(function(el) {
       return el.testID !== data.testID;
    });
     this.selected = newArray;
   }
   console.log(this.selected);
  }

Thanks




How do I call upon checkboxes with groupname or tag?

Am creating a form in which the user will be able to select 4 checkboxes. Blue, Green, Yellow, Red. They have to do this atleast twice, up to 5 times in total.

The first checkboxes are on the form, the other 4 grouped checkboxes are on multipages.

I've tried giving them a group name "Reeks" to "Reeks4", to then print their values into a single cell separated by comma.

The code I've found so far does print the values neatly, however, it grabs every available checkbox on my form instead of just from the group "Reeks".

The ways I've tried to add the groupname (or tag, named them both the same) to the code, only gives me errors.

For Each Control In Me.Controls
   If TypeName(Control) = "CheckBox" Then
               'If Control.GroupName = "Reeks" Then
                If Control.Value Then 
            Reeks = IIf(Reeks <> "", Reeks & ", ", "") & Control.Caption
        End If
        End If
    Next
With ws 
.Cells(iRow, 5).Value = Reeks
End With

Any help is welcome, but if at all possible please add comments as I only started on VBA last week.

(Side note. I also have framed checkboxes on the multipages in which the user can select the location of said colour. Side + Top view. Which will need to work the same as with the colours, but printed in different columns. )




ngModel and checkbox/radio not working properly

I made html template for my app. Basically it's a radio/checkboxes with text inputs which contain answers to questions. It worked just fine until I've decided to add ngModel to them. The thing is that when I add 2 or more answers and click on a label to set the correct one(/s) only the last one selects, moreover the answertext dissapears whenever I click on label.

html text:

<div  *ngIf="question.typeQuestions==1">                
  <div *ngFor="let item of question.selectedAnswer; let i = index" class="checkbox-variable">
   <input type="checkbox" id="customCheckbox" name="customCheckbox" class="checkbox-square" [(ngModel)]="item.isCorrect" >
    <label class="checkbox-label" for="customCheckbox"><input class="checkbox-text" type="text" [(ngModel)]="item.text"></label>
 </div>
</div>  



dimanche 29 décembre 2019

how to check if a checkbox is checked when sending data via ajax to php

I have a foreach loop which creates tr's with inside a checkbox and some input fields. Each row has a checkbox with the id as value. Each row has also a hidden input field with the id as value.

I want to distinguish whether a request is send via the own delete button in each row, or via the checkbox what is checked for (these) rows. (when multiple checkboxes are checked, i can delete them all at once)

<tr>
    <input type="hidden" name="file_id" value="<?php echo $file_id; ?>" /> <!-- file id which belongs to each row -->
    <td><input type="checkbox" class="checkbox" value="<?php echo $file_id; ?>" /></td>
    ...
    <button class="btn btn-sm btn-danger submit" type="submit" name="delete_file">Delete</button>
</tr>

i send the data via jquery ajax to the php file:

// checkboxes value 
    $(document).on('click' , '.submit' , function() { 
        var checkbox_value = [];
        var file_id = $(this).closest("tr").find("input[name='file_id']").val();


        $('.checkbox').each(function() {
            if ($(this).is(":checked")) {
                checkbox_value.push($(this).val());
            }
        });
        checkbox_value = checkbox_value.toString();
        $.ajax({
            url: "admin.php",
            method: "POST",
            data: {
                checkbox_value: checkbox_value,
                file_id : file_id

            },
            success: function(data) {
                $('.result').html(data);

            }
        });
    });

The php:

if(isset($_POST["checkbox_value"])) {

        $checkboxfiles[] = $_POST["checkbox_value"];
        $category = $_POST["category"]; 

        // checkbox loop
        foreach ($checkboxfiles as $checkboxfile) {
            foreach(explode(',', $checkboxfile) as $id) {

                echo $id.'<br />';
                echo 'delete via checkbox is choosen';

            }
        }

        exit;
}

if(isset($_POST["file_id"])) {
        ...
        echo 'delete via single row is choosen';

}

Problem: When i choose to delete via single row (no checkbox is checked), it still sends the echo delete via checkbox is choosen




Autofill checkbox using string query in url but specifying a fieldset

I'm trying to get filtered data from a webform more quickly. Basically I want to use URL input to specify a date and to precheck a checkbox. I'm getting stuck with how to specify the check box as I'm not sure what the value should be.

<form action="/xxx/yyy" class="form-inline d-flex justify-content-end" method="get">      <div class="input-group input-group-lg mb-2">
        <div class="input-group-prepend">
          <span class="input-group-text"><i class="fa fa-calendar"></i></span>
        </div>
        <input type="text" name="from" value="" class="form-control datetimepicker-input" id="datetimepicker7" data-toggle="datetimepicker" data-target="#datetimepicker7" autocomplete="false">
        <div class="input-group-append">
          <button type="submit" class="btn btn-dark"><i class="fas fa-arrow-right"></i></button>
        </div>
      </div>
</form>

####snip and skip to the part of the form I wish to pre-check####

<fieldset id="departureGatewayFilters">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" value="AMS" id="departureGatewayCheck_AMS">
              <label class="form-check-label" for="departureGatewayCheck_AMS">
                AMS
              </label>
            </div>

So far I'm using URL string: /xxx/yyy?from=2020-03-05 - what would I need next to pre-check the checkbox as well?

Thanks in advance!

Clare




samedi 28 décembre 2019

TKinter adjust text position besides checkbox

Is it possible to move the checkbox description closer to the CheckBox?

CheckBox




vendredi 27 décembre 2019

checkbox not changing value

The following will not change the value of the checkbox to true or false, it seems to be stuck on true.

So even if a user does not want to agree to the terms it is making it look like the user has not unclicked the checkbox (yes the checkbox does remove the tick tho)

I am wondering what do I need to change in the following to get it to update the const.

const [state, setState] = React.useState({
    marriedstatus: '',
    employmentstatus: '',
    dependants: '',
    income:'',
    firsthomebuyer:'',
    interest:'',
    whentobuild:'',
    firstname: '',
    lastname:'',
    email:'',
    mobile:'',
    state:'',
    suburb:'',
    country:'',
    besttimetocall:'',
    agree: false,
  });




const handleChange = name => event => {
    setState({
      ...state,
      [name]: event.target.value,
    });
  };


 <Grid item lg={6} xs={12}> 
            <Controller as={<FormControl variant="outlined" fullWidth="true">
            <InputLabel ref={inputLabel} htmlFor="agree">
            Agree
            </InputLabel><Checkbox
        name="agree"
        value={state.agree}
        checked={true} 
        onChange={handleChange('agree')}
        inputProps=aria-label
/></FormControl>} name="Agree" control={control} />
        </Grid>



Pseudo classes/selectors cancel eachother out, how do I fix it?

I'm trying to get a image to change color when I selected a checkbox but it cancels out the other classes I have linked to the same checkbox (classes that lock div sizes). The website is spread out through a few pages so I won't be able to upload the html code here but I can show you the website: sw-guild.com (the image I'm talking about is the arrow on all other pages but 'Home')

for some reason i'ts only '.top-list' that gets cancelled out

here is the CSS:

    input.check:checked + .top-list {       
        height: 35px;
    }

    input.check:checked ~ .middle-list {        
        height: 35px;
    }

    input.check:checked ~ .bottom-list {        
        height: 35px;
    }

    .arrow {
        filter: brightness(200%) hue-rotate(150deg);
    }

    input.check:checked + .arrow  {
        filter: hue-rotate(0deg) ;
    }



jeudi 26 décembre 2019

How to dynamically add IDs in checkboxes with vue?

I'm trying to create a table so that someone can check the people they want to add to a group. So far I've managed to retrieve them from the DB with PHP and display them with vue in HTML. Now I would like to assign each checkbox ID with the email of the student, so i can send the checked students back to PHP later. There may be (a lot) better ways to do this, but I'm very new to this.

This is my current output: My Output

My HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <!-- Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>

<body>

    <div id="vue-app">
        <table>
            <thead>
                <tr>
                    <th>Select</th>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(student, index) in students">
                <td><input type="checkbox" id="></td>
                <td></td>
                <td></td>
                </tr>
            </tbody>
        </table>
    </div>
 var app = new Vue({

            el: '#vue-app',
            data: {
                students: []
            },
            mounted: function () {
                axios.get('get_students_list.php')
                    .then(response => {
                        this.students = response.data;
                        console.log(students);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
        })

get_students_list.php:

try {
include("db_connection.php");
$isteacher = false;

$query = "SELECT firstname, lastname, email FROM persons WHERE isteacher = :isteacher";
$statement = $conn->prepare($query);
$statement->bindParam(':isteacher', $isteacher);

$statement->execute();

//gets row as associative array
$users = $statement->fetchAll(PDO::FETCH_ASSOC);


$students = json_encode($users);
echo $students;

} catch (PDOException $error) {
echo $error;
}

I've tried the above id allocation and I also tried creating a checkbox with javascript with the following code (which didn't work either, because for one i can't acces the vue elements from there):

                var checkbox = document.createElement('input');
                checkbox.type = "checkbox";
                checkbox.id = ;
                checkbox.checked = false; 



mercredi 25 décembre 2019

How to add picture instead of checkbox?

I need to change this checkbox to be displayed as a picture

<li>
    <input id="checkbox_example" type="checkbox" name="choice" value="light_mode">
    <label for="light_mode" data-sentence="Let's turn light on'">Brightness</label>
</li>



when I click label of input type="checkbox" first status "false"

if(clickEl.parentNode.querySelector('input').checked === true) {
  console.log(555);
} else {
  console.log(111);
} 
<li class="dropdown-category-list__list" data-filter="sneakers">
  <input type="checkbox" id="filterSneakers">
  <label for="filterSneakers">Sneakers</label>
</li>

When I click on input everything works fine, result = 555,111,555,111 and so on But when I click label result 111,555,555,111,111,555,555,111 and it is wrong behaviour

I know that I can wrap input into label but how to fix it withour editing html structure




lundi 23 décembre 2019

Adding check boxes to datatable where data is pulled from an api

I have my data as json key value pairs in an array.

$(document).ready(function () {
        var table = $("#main").DataTable({
            columns: [{
                    "data": "ProductNumber",
                    "title": "ProductNumber"
                },
                {
                    "data": "ReceivingDate",
                    "title": "ReceivingDate"
                }]

I want to add checkboxes so that users can select some rows.

columnDefs: [{
                targets: 0,
                searchable: false,
                orderable: false,
                className: 'dt-body-center',
                render: function (data, type, full, meta) {
                    return '<input type="checkbox" name="id[]" value="' +
                        $('<div/>').text(data).html() + '">';
                }
            }]

I found the columnDef example from the DataTable website. The issue is, it is told to render this checkbox on column 0 which replaces my productnumber column. And I can't add an empty column as my json data has the exact number of data as the columns have. Are there any other ways I can achieve this?




How to Show and Hide with id when the checkbox is checked

I have a problem, I would like to know how to display data thanks to their id when the chebkbox is checked.

For example when the first checkbox is checked I just want the address named "0" and hidde the rest of the others adress I already try to do but I'm stuck and I would like to learn how to do .

I'm using firebase as db :

enter image description here

import React, { Component } from "react";
import * as firebase from "firebase";
import { Table, InputGroup } from "react-bootstrap";
class ListClients extends React.Component {
  state = {
    loading: true,
    selectedOption: "option0",
    selectedStyle : {display : 'none'},
    selectedId : ""
  };

  componentWillMount() {
    const ref = firebase
      .database()
      .ref("listClients")
      .orderByChild("id");
    ref.on("value", snapshot => {
      this.setState({
        listClients: snapshot.val(),
        loading: false
      });

    });
  }

  handleOptionChange = changeEvent => {

    this.setState({
      selectedOption: changeEvent.target.value,
      selectedStyle : {display : 'block'},
      selectedId: 1
    });


  };

  render() {
    let selectedStyle = this.state.selectedStyle

    if (this.state.loading) {
      return <h1>Chargement...</h1>;
    }
    const clients = this.state.listClients.map((client, i) => (
      <tr>
        <td>
          <input
            key={client + i}
            id={"checkbox" }
            type="checkbox"
            value={"option"+i}

            onChange={this.handleOptionChange}
            checked={this.state.selectedOption === "option"+i}
          />
        </td>
        <td>{client.nom}</td>
        <td>{client.prenom}</td>
      </tr>
    ));

    const clientAdr = this.state.listClients.map((client, i) => (
      <tr key={i}>
        <td id={"myDIV" + i}   value={"option"+i} onChange={this.handleOptionChange} style={selectedStyle}>
          {client.adresse}
        </td>
      </tr>
    ));




    return (
      <>
        <Table className="ContentDesign" striped bordered hover>
          <thead>
            <tr>
              <th></th>

              <th>First Name</th>
              <th>Last Name</th>
            </tr>
          </thead>
          <tbody>{clients}</tbody>
        </Table>

        <Table className="ContentDesign" striped bordered hover>
          <thead>
            <tr>
              <th>Adresse : </th>
            </tr>
          </thead>

          <tbody>{clientAdr}</tbody>
        </Table>
      </>
    );
  }
}

export default ListClients;

What I have for the moment :

enter image description here




When I scroll the list view radio button gets automatically selected or deselected not able to maintain the state of radio button

I am creating a android app the layout of my application is below given.

On clicking of submit button, I need the selected check box, and radio buttons value.

Example Linux is not checked, cc(radio button) is checked.

Records are populated dynamically in list view, but I am not able to make it work. A lot of problems are there.

1) When I scroll the list view radio button gets automatically selected or deselected not able to maintain the state of radio button. 2) On click of button not getting the selected radio button as well as check box.

Below is my layout as well as java program. Suggest me to get the correct values.

enter image description here

Main.xml
<ListView
    android:id="@+id/my_list"
    android:layout_width="fill_parent"
    android:layout_height="199dp" />

<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    />
row.xml
<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@+id/label"
    android:layout_toRightOf="@+id/check"
    android:textSize="20sp" >
</TextView>

<CheckBox
    android:id="@+id/check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="4dip"
    android:layout_marginRight="10dip"
    android:focusable="false"

    android:focusableInTouchMode="false" >
</CheckBox>

 <RadioGroup
     android:id="@+id/radioSex"
     android:layout_width="wrap_content"
     android:layout_height="fill_parent"
     android:layout_alignParentRight="true"
     android:layout_alignParentTop="true"
     android:orientation="horizontal" >

     <RadioButton
         android:id="@+id/to"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="10dip"
         android:checked="true"
         android:text="To" />

     <RadioButton
         android:id="@+id/cc"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="10dip"
         android:text="CC" />
 </RadioGroup>
MyAdapter.java

private class ViewHolder {
    protected TextView text;
    protected CheckBox checkbox;
    protected RadioGroup radioGroup;
}

public class MyAdapter extends ArrayAdapter<Model> {

    private final List<Model> list;
    private final Activity context;
    boolean checkAll_flag = false;
    boolean checkItem_flag = false;

    public MyAdapter(Activity context, List<Model> list) {
        super(context, R.layout.row, list);
        this.context = context;
        this.list = list;
    }

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

        ViewHolder viewHolder = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.row, null);

            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) convertView.findViewById(R.id.label);
            viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
            viewHolder.checkbox.setTag(position);
            viewHolder.radioGroup = (RadioGroup) convertView.findViewById(R.id.radioSex);
            viewHolder.radioGroup.setTag(position);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.text.setText(list.get(position).getName());
        viewHolder.checkbox.setChecked(list.get(position).isSelected());
        viewHolder.checkbox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                CheckBox checkbox = (CheckBox) v;
                int getPosition = (Integer) checkbox.getTag();
                list.get(getPosition).setSelected(checkbox.isChecked());
            }
        });

        viewHolder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                boolean isCcOrIsTo = (checkedId == R.id.cc);
                int getPosition = (Integer) group.getTag();
                list.get(getPosition).setCcOrIsTo(isCcOrIsTo);
            }
        });

        return convertView;
    }
}
Model.java

public class Model {

    private String name;
    private boolean selected;
    private boolean isCcOrIsTo;

    public Model(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public boolean isCcOrIsTo() {
        return isCcOrIsTo;
    }

    public void setCcOrIsTo(boolean isCcOrIsTo) {
        this.isCcOrIsTo = isCcOrIsTo;
    }

    @Override
    public String toString() {
        String selectedString = selected ? "selected" : "not selected";
        String value = isCcOrIsTo ? "CC" : "To";
        return name+" -> "+selectedString+ " with value "+value;
    }
}
MainActivity.java

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.my_list);

    btn = (Button) findViewById(R.id.submit);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            for (Model m : list) {
                Log.i("Stack1", m.toString());
            }
        }
    });

    ArrayAdapter<Model> adapter = new MyAdapter(this, getModel());
    listView.setAdapter(adapter);
}



Get Checkbox states in array - Tkinter

I just started coding less than 3 weeks ago (took a class in Lynda) and now working on a GUI that enable user to tick/untick a lists. I manage to get it done but in inefficient workaround (someone gave me a heads up on this).

What i have done basically calling a variables for each checkbox and insert the checkbox states into it. So if I have 100 of checkboxes in the list, I will need to create 100 variables. Below is the working code that I wrote.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

var1t1 = tk.IntVar()
var2t1 = tk.IntVar()
var3t1 = tk.IntVar()

var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")

def boxstates_t1():
    var_name = [var1t1.get(), var2t1.get(), var3t1.get()]
    print(var_name)

# -----------------Checkbox-----------------
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)

check1_t1 = ttk.Checkbutton(root, text = "Mike", variable = var1t1)
check1_t1.pack(anchor = tk.W)

check2_t1 = ttk.Checkbutton(root, text = "Harry", variable = var2t1)
check2_t1.pack(anchor = tk.W)

check3_t1 = ttk.Checkbutton(root, text = "Siti", variable = var3t1)
check3_t1.pack(anchor = tk.W)

# -----------------Button-----------------

btn2 = ttk.Button(root, text="Show", command = boxstates_t1)
btn2.pack(side=tk.RIGHT)

root.mainloop()

Then i googled around and found few code that lead me to use for loop to print the list. I initialize the var_name = [] so that it will capture each checkbox state from the list.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
var1 = tk.IntVar()

var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")

def boxstates():
    var_name = var1.get()
    print(var_name)

# ------------------Chekbox-------------
name1 = ["Mike", "Harry", "Siti"]

labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)

for checkboxname in name1:
    check1_t1 = ttk.Checkbutton(root, text=checkboxname, variable=var1)
    check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)

root.mainloop()

But I was unable to tick the checkbox independently and the print out result also comes back as if it's in single variable. Am I doing the array var_name = [] wrongly? I'm currently lost and have no clue where to head next.

Any advise is greatly appreciate.




dimanche 22 décembre 2019

How can I make a complex checkboxes search system by making a SELECT based on checkboxes echoed as rows from a WHILE of another SELECT

I'm trying to make a checkboxes search system in which the user can filter the prayers by author, OR data, OR subjects, or that author AND that subject, etc., and then choose if the result will display only the titles, or titles + authors, etc., from the filter result.

The problem is that when I display the table authors, for example, as checkboxes, like this:

<?php

$sql = "SELECT DISTINCT autor_da_oracao FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_autor_da_oracao' name='chkfautor[]' value='".$row['autor_da_oracao']."'>
<label for='chk_filtrar_autor_da_oracao'><p>".$row['autor_da_oracao']."</p></label>
</div>

";

}}

?>

, I cannot read, in another php tag at the same document, that specific author from that specific row of the "while" command:

<?php
$sql = "SELECT * FROM oracoes WHERE autor_da_oracao = $row['autor_da_oracao'];";
(rest of php query).

It seems like with this code I cannot tell the DB that I want that specific author in that specific line turned into a checkbox.

The whole code is below (by the way, if there's an easier way to do what i'm trying, please indicate to me):

Obs.: I know the code "WHERE autor_da_oracao = $row['autor_da_oracao']" is not right, giving an error. Without it, i have working: when no checkboxes are displayed, show "título", "autor" and "oracao"; when "titulo", or "oracao", or something in the "Exibir" part of the filter menu is checked, PHP only displays what is checked; when checkbox "Tudo" is checked, it displays everything. What I cannot make work are the filters whose terms come from the database and when clicked on their respective checkboxes show all the prayers whose author is such, or whose date is such, etc.

<!--------------------MENU FILTROS-------------------->

<div class="menu_filtros" id="menu_filtros">


<!----------FILTRAR AUTOR---------->

<p2 style="margin-bottom:.5em;">Filtrar autor</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT autor_da_oracao FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_autor_da_oracao' name='chkfautor[]' 
value='".$row['autor_da_oracao']."'>
<label for='chk_filtrar_autor_da_oracao'><p>".$row['autor_da_oracao']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR DATA---------->

<p2 style="margin-bottom:.5em;">Filtrar data</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT data FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_data' name='chkfdata[]' value=''>
<label for='chk_filtrar_data'><p>".$row['data']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR TEMPO_LITURGICO---------->

<p2 style="margin-bottom:.5em;">Filtrar tempo litúrgico</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT tempo_liturgico FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_tempo_liturgico' name='chkftempoliturgico[]' value=''>
<label for='chk_filtrar_tempo_liturgico'><p>".$row['tempo_liturgico']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR SOLENID_FESTA_MEMORIA_MESES_TEMATICOS---------->

<p2 style="margin-bottom:.5em;">Filtrar Solenidade, festa, memória, meses temáticos</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT solenid_festa_memoria_meses_tematicos FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_solenid_festa_memoria_meses_tematicos' name='chkfsolenid[]' value=''>
<label for='chk_filtrar_solenid_festa_memoria_meses_tematicos' <p>".$row['solenid_festa_memoria_meses_tematicos']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR DIRIGIDA_A---------->

<p2 style="margin-bottom:.5em;">Filtrar dirigida a</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT dirigida_a FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_dirigida_a' name='chkfdirigidaa[]' value=''>
<label for='chk_filtrar_dirigida_a'><p>".$row['dirigida_a']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR NATUREZA---------->

<p2 style="margin-bottom:.5em;">Filtrar natureza</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT natureza FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_natureza' name='chkfnatureza[]' value=''>
<label for='chk_filtrar_natureza'><p>".$row['natureza']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR ORIGEM---------->

<p2 style="margin-bottom:.5em;">Filtrar origem</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT origem FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_origem' name='chkforigem[]' value=''>
<label for='chk_filtrar_origem'><p>".$row['origem']."</p></label>
</div>

";

}}

?>

</div>

</form>


<!----------FILTRAR ASSUNTO---------->

<p2 style="margin-bottom:.5em;">Filtrar assunto</p2>


<form method="post">

<div class="chks">

<?php

$sql = "SELECT DISTINCT assunto FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

$exp_assunto = explode(",", $row["assunto"]);


foreach($exp_assunto as $exp_assunto_itens) {


echo "

<div class='chk_class'>
<input type='checkbox' id='chk_filtrar_assunto' name='chkfassunto[]' value=''>
<label for='chk_filtrar_assunto'><p>".$exp_assunto_itens."</p></label>
</div>

";

}}}

?>

</div>

<!--</form>-->


<!----------EXIBIR---------->

<p2 style="margin-bottom:.5em;">Exibir</p2>


<!--<form method="post">-->

<div class="chks">

<div class="chk_class">
<input type="checkbox" id="chk_tudo" name="chk_tudo[]" value="tudo">
<label for="chk_tudo">Tudo</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_titulo" name="chk[]" value="titulo">
<label for="chk_titulo">Título</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_oracao_original" name="chk[]" value="oracao_original">
<label for="chk_oracao_original">Oração original</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_obra_oracao_original" name="chk[]" value="obra_da_oracao_original">
<label for="chk_obra_oracao_original">Obra da oração original</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_autor_oracao" name="chk[]" value="autor_da_oracao">
<label for="chk_autor_oracao">Autor da oração</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_data" name="chk[]" value="data">
<label for="chk_data">Data</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_local" name="chk[]" value="local">
<label for="chk_local">Local</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_oracao_traduzida_pt" name="chk[]" value="oracao_traduzida_pt">
<label for="chk_oracao_traduzida_pt">Oração traduzida pt</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_obra_traducao" name="chk[]" value="obra_da_traducao">
<label for="chk_obra_traducao">Obra da tradução</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_autor_traducao" name="chk[]" value="autor_da_traducao">
<label for="chk_autor_traducao">Autor da tradução</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_tempo_liturgico" name="chk[]" value="tempo_liturgico">
<label for="chk_tempo_liturgico">Tempo litúrgico</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_solenid_festa_memoria_meses_tematicos" name="chk[]" value="solenid_festa_memoria_meses_tematicos">
<label for="chk_solenid_festa_memoria_meses_tematicos">Solenid, festa, mem, meses tem</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_dirigida_a" name="chk[]" value="dirigida_a">
<label for="chk_dirigida_a">Dirigida a(à,ao)</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_natureza" name="chk[]" value="natureza">
<label for="chk_natureza">Natureza</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_origem" name="chk[]" value="origem">
<label for="chk_origem">Origem</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_assuntos" name="chk[]" value="assunto">
<label for="chk_assuntos">Assuntos</label>
</div>

<div class="chk_class">
<input type="checkbox" id="chk_comentario" name="chk[]" value="comentario">
<label for="chk_comentario">Comentário</label>
</div>

</div> <!--chks-->

<div class="chks">
<input type="submit" name="exibir" value="Filtrar/Exibir" style="cursor:pointer;">
</div> <!--chks-->

</form>


<!----------PESQUISAR CONTEÚDOS---------->

<p2 style="margin-bottom:.5em;">Pesquisar conteúdos das orações</p2>


<div class="chks">
Barra de pesquisa.
</div>


</div> <!--menu_filtros-->


<!----------MAIN_EXIBIÇÃO_FILTRADOS---------->

<div class="main_exibicao_filtrados" id="main_exibicao_filtrados">


<!----------MOSTRANDO ORAÇÕES---------->

<?php


if(isset($_POST['chk_tudo'])){


if (!isset($_POST['chkfautor'], $_POST['chkfdata'], $_POST['chkftempoliturgico'], $_POST['chkfsolenid'], 
$_POST['chkfdirigidaa'], $_POST['chkfnatureza'], $_POST['chkforigem'], $_POST['chkfassunto'])) {


$sql = "SELECT * FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='div_oracoes'>

<div class='div_cada_oracao_titulo' id='id_cada_oracao_titulo'>
<p2>Título</p2>
<p>".$row['titulo']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_oracao_original'>
<p2>Oração original</p2>
<p>".$row['oracao_original']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_obra_da_oracao_original'>
<p2>Obra da oração original</p2>
<p>".$row['obra_da_oracao_original']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_autor_da_oracao'>
<p2>Autor da oração</p2>
<p>".$row['autor_da_oracao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_data'>
<p2>Data provável da composição da oração</p2>
<p>".$row['data']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_local'>
<p2>Local provável da composição da oração</p2>
<p>".$row['local']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_oracao_traduzida_pt'>
<p2>Oração traduzida para o português</p2>
<p>".$row['oracao_traduzida_pt']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_obra_da_traducao'>
<p2>Obra em que se encontra a tradução</p2>
<p>".$row['obra_da_traducao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_autor_da_traducao'>
<p2>Autor da tradução</p2>
<p>".$row['autor_da_traducao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_tempo_liturgico'>
<p2>Tempo litúrgico mais oportuno para a utilização da oração</p2>
<p>".$row['tempo_liturgico']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_solenid_festa_memoria_meses_tematicos'>
<p2>Solenidade, festa, memória, meses temáticos em que a oração é cabível</p2>
<p>".$row['solenid_festa_memoria_meses_tematicos']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_dirigida_a'>
<p2>Dirigida a(à,ao)</p2>
<p>".$row['dirigida_a']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_natureza'>
<p2>Natureza (imprecação, louvor, etc.)</p2>
<p>".$row['natureza']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_origem'>
<p2>Origem (Bíblia, tradição, etc.)</p2>
<p>".$row['origem']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_assunto'>
<p2>Assuntos de que trata a oração (sofrimento, entrega total, etc.)</p2>
<p>".$row['assunto']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_comentario'>
<p2>Comentário à oração</p2>
<p>".$row['comentario']."</p>
</div>

</div>

";


}}} else {


$sql = "SELECT * FROM oracoes WHERE autor_da_oracao = $row['autor_da_oracao'];";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='div_oracoes'>

<div class='div_cada_oracao_titulo' id='id_cada_oracao_titulo'>
<p2>Título</p2>
<p>".$row['titulo']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_oracao_original'>
<p2>Oração original</p2>
<p>".$row['oracao_original']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_obra_da_oracao_original'>
<p2>Obra da oração original</p2>
<p>".$row['obra_da_oracao_original']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_autor_da_oracao'>
<p2>Autor da oração</p2>
<p>".$row['autor_da_oracao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_data'>
<p2>Data provável da composição da oração</p2>
<p>".$row['data']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_local'>
<p2>Local provável da composição da oração</p2>
<p>".$row['local']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_oracao_traduzida_pt'>
<p2>Oração traduzida para o português</p2>
<p>".$row['oracao_traduzida_pt']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_obra_da_traducao'>
<p2>Obra em que se encontra a tradução</p2>
<p>".$row['obra_da_traducao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_autor_da_traducao'>
<p2>Autor da tradução</p2>
<p>".$row['autor_da_traducao']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_tempo_liturgico'>
<p2>Tempo litúrgico mais oportuno para a utilização da oração</p2>
<p>".$row['tempo_liturgico']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_solenid_festa_memoria_meses_tematicos'>
<p2>Solenidade, festa, memória, meses temáticos em que a oração é cabível</p2>
<p>".$row['solenid_festa_memoria_meses_tematicos']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_dirigida_a'>
<p2>Dirigida a(à,ao)</p2>
<p>".$row['dirigida_a']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_natureza'>
<p2>Natureza (imprecação, louvor, etc.)</p2>
<p>".$row['natureza']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_origem'>
<p2>Origem (Bíblia, tradição, etc.)</p2>
<p>".$row['origem']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_assunto'>
<p2>Assuntos de que trata a oração (sofrimento, entrega total, etc.)</p2>
<p>".$row['assunto']."</p>
</div>
<div class='div_cada_oracao' id='id_cada_oracao_comentario'>
<p2>Comentário à oração</p2>
<p>".$row['comentario']."</p>
</div>

</div>

";

}}}

} else if(isset($_POST['chk'])){


$chk1 = $_POST['chk'];
$chk2 = implode(',',$chk1);

$sql = "SELECT $chk2 FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='div_oracoes'>

";

if (strpos($chk2, 'titulo') !== false) {

echo "

<div class='div_cada_oracao_titulo' id='id_cada_oracao_titulo'>
<p2>Título</p2>
<p>".$row['titulo']."</p>
</div>

";}

if (strpos($chk2, 'oracao_original') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_oracao_original'>
<p2>Oração original</p2>
<p>".$row['oracao_original']."</p>
</div>

";}

if (strpos($chk2, 'obra_da_oracao_original') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_obra_da_oracao_original'>
<p2>Obra da oração original</p2>
<p>".$row['obra_da_oracao_original']."</p>
</div>

";}


if (strpos($chk2, 'autor_da_oracao') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_autor_da_oracao'>
<p2>Autor da oração</p2>
<p>".$row['autor_da_oracao']."</p>
</div>

";}


if (strpos($chk2, 'data') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_data'>
<p2>Data provável da composição da oração</p2>
<p>".$row['data']."</p>
</div>

";}


if (strpos($chk2, 'local') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_local'>
<p2>Local provável da composição da oração</p2>
<p>".$row['local']."</p>
</div>

";}


if (strpos($chk2, 'oracao_traduzida_pt') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_oracao_traduzida_pt'>
<p2>Oração traduzida para o português</p2>
<p>".$row['oracao_traduzida_pt']."</p>
</div>

";}


if (strpos($chk2, 'obra_da_traducao') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_obra_da_traducao'>
<p2>Obra em que se encontra a tradução</p2>
<p>".$row['obra_da_traducao']."</p>
</div>

";}


if (strpos($chk2, 'autor_da_traducao') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_autor_da_traducao'>
<p2>Autor da tradução</p2>
<p>".$row['autor_da_traducao']."</p>
</div>

";}


if (strpos($chk2, 'tempo_liturgico') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_tempo_liturgico'>
<p2>Tempo litúrgico mais oportuno para a utilização da oração</p2>
<p>".$row['tempo_liturgico']."</p>
</div>

";}


if (strpos($chk2, 'solenid_festa_memoria_meses_tematicos') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_solenid_festa_memoria_meses_tematicos'>
<p2>Solenidade, festa, memória, meses temáticos em que a oração é cabível</p2>
<p>".$row['solenid_festa_memoria_meses_tematicos']."</p>
</div>

";}


if (strpos($chk2, 'dirigida_a') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_dirigida_a'>
<p2>Dirigida a(à,ao)</p2>
<p>".$row['dirigida_a']."</p>
</div>

";}


if (strpos($chk2, 'natureza') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_natureza'>
<p2>Natureza (imprecação, louvor, etc.)</p2>
<p>".$row['natureza']."</p>
</div>

";}


if (strpos($chk2, 'origem') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_origem'>
<p2>Origem (Bíblia, tradição, etc.)</p2>
<p>".$row['origem']."</p>
</div>

";}


if (strpos($chk2, 'assunto') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_assunto'>
<p2>Assuntos de que trata a oração (sofrimento, entrega total, etc.)</p2>
<p>".$row['assunto']."</p>
</div>

";}


if (strpos($chk2, 'comentario') !== false) {

echo "

<div class='div_cada_oracao' id='id_cada_oracao_comentario'>
<p2>Comentário à oração</p2>
<p>".$row['comentario']."</p>
</div>

";}

echo "
</div>
";

}}} else {

$sql = "SELECT titulo, autor_da_oracao, oracao_traduzida_pt FROM oracoes;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo "

<div class='div_oracoes'>

<div class='div_cada_oracao_titulo' id='id_cada_oracao_titulo'>
<p2>Título</p2>
<p>".$row['titulo']."</p>
</div>

<div class='div_cada_oracao' id='id_cada_oracao_autor_da_oracao'>
<p2>Autor da oração</p2>
<p>".$row['autor_da_oracao']."</p>
</div>

<div class='div_cada_oracao' id='id_cada_oracao_oracao_traduzida_pt'>
<p2>Oração traduzida para o português</p2>
<p>".$row['oracao_traduzida_pt']."</p>
</div>

</div>

";

}}}

?>


</div> <!--main_exibicao_filtrados-->

The filter menu is like the image attached, so it can help to get the idea.

Print from filter menu




how to invert string value from database to make the checkbox check/uncheck - VB.NET

I am creating a CRUD system on VB.Net, and I have converted my checkbox values to string upon adding to the database. Now, I wanted to invert the values. I want to make the checkbox state set to checked/unchecked based on the string value from the database whenever I select a row from datagrid.

This is the code I am trying to work on: CheckOne2One.Checked = Convert.ToBoolean(DataGridView1.CurrentRow.Cells("Class").Value)

thank you!




Updating array in react state, using concat

I have a component of checkbox, basically what im trying to do is to make array of the checked ones and send the information to an api. but im having trouble updating the state array without deleteing the last object inserted. im using concat and still same result. here is the code for the whole component:

import React, { Fragment, Component } from 'react';
import { Inputt, Checkbox } from './style';

interface Istate {
  checked: boolean;
  products?: any[];
}
interface Iprops {
  id: any;
  value: any;
  changeValue?: (checkBoxId: string, value: any) => void;
}
class CheckBoxComp extends Component<Iprops, Istate> {
  state = {
    checked: true,
    products: [] as any,
  };

  addOne = (id: any, checked: any) => {
    let { products } = this.state;
    const newObj = { id, checked };
    products = products.concat(newObj);
    this.setState({ products }, () => {
      console.log(products);
    });
  };

  isChecked = (id: any) => {
    const { checked, products } = this.state;
    const { changeValue } = this.props;
    this.setState({
      checked: !checked,
    });
    if (changeValue) {
      changeValue(id, checked);
    }
    this.addOne(id, checked);
  };

  render() {
    const { id, value } = this.props;
    const { checked, products } = this.state;
    return (
      <Fragment>
        <Checkbox>
          <span />{' '}
          <label className="checkbox-wrapper">
            <span className="display" />
            <Inputt
              type="checkbox"
              value={checked}
              onChange={() => {
                this.isChecked(id);
              }}
            />
            <span className="checkmark" />
          </label>
        </Checkbox>
      </Fragment>
    );
  }
}

export default CheckBoxComp;



samedi 21 décembre 2019

How can I avoid rendering check box numbers?

I'm trying to create a comma-separated list of dietary restrictions based on checked boxes in a form. I managed to make a comma-separated list, but I can’t find a way to keep the app from rendering a number when I click on a checkbox. Please see below:

class App extends Component {
    constructor() {
        super()
        this.state = {
            firstName: "",
            lastName: "",
            age: "",
            gender: "",
            destination: "",
            dietaryRestrictions: {
                isVegan: false,
                isKosher: false,
                isLactoseFree: false
            }
        }
        this.handleChange = this.handleChange.bind(this)
    }

{…more code..}

render() {
        const dietR = []
        return (
            <main>

{…more code..}

[Your dietary restrictions: 
                    {this.state.dietaryRestrictions.isKosher ? dietR.push("Kosher"):null}
                    {this.state.dietaryRestrictions.isLactoseFree ? dietR.push("Lactose-Free"):null}
                    {this.state.dietaryRestrictions.isVegan ? dietR.push("Vegan"):null}
                <p>{dietR.join(", ")}</p>
            </main>
        )

Note the “123” after “dietaryRestrictions" in the screenshot enter image description here




Im running intp a problem with my checkbox list in php, where the code is executed in php but not in my database?

Im trying to delete data from my dayabase , now i use the following code in my php as you can see below:

if(isset($_POST['label-delete-btn'])){

include 'conn.php';

$checkbox=$_POST['num'];

    while (list($key,$val)=@each($checkbox)) {
        $query="SELECT * FROM posts WHERE id='$val' ";
        if($result=mysqli_query($conn,$query)){
            echo 'selected data is deleted';
        }
    }

and my input element inside the form is as the following :

<input type="checkbox" name="num[]" value="<?php echo $post['id'];?>">

Now by submitting the button , the code exetues by itself, but ,y databse remains without changes




Android read Firebase CheckBox acting weird

I have the following in the project:

  1. MainActivity
  2. FirebaseHelper
  3. CustomAdapter
  4. Person
  5. one_line_list_item.xml

MainActivity Class

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;
        mListView = (ListView) findViewById(R.id.list_view);
        searchView = (SearchView) findViewById(R.id.search);
        //searchView.setIconifiedByDefault(true);
        searchView.setSubmitButtonEnabled(true);
        //initialize firebase database
        db = FirebaseDatabase.getInstance().getReference();
        helper = new FirebaseHelper(db, this, mListView);

        adapter = new CustomAdapter(context, helper.people);

FirebaseHelper Class

DatabaseReference db;
Boolean saved;
ArrayList<Person> people = new ArrayList<>();
ListView mListView;
Context c;
CustomAdapter adapter;

public FirebaseHelper(DatabaseReference db, Context context, ListView mListView) {
    this.db = db;
    this.c = context;
    this.mListView = mListView;
    this.retrieve();
}

public ArrayList<Person> retrieve() {
    db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            people.clear();
            if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    //Now get Person Objects and populate our arraylist.
                    Person person = ds.getValue(Person.class);
                    people.add(person);
                }
                adapter = new CustomAdapter(c, people);
                mListView.setAdapter(adapter);

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        mListView.smoothScrollToPosition(people.size());
                        mListView.smoothScrollToPosition(people.indexOf(0));
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("mTAG", databaseError.getMessage());
            Toast.makeText(c, "ERROR " + databaseError.getMessage(), Toast.LENGTH_LONG).show();

        }
    });

    return people;
}

CustomAdapter Class

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(c).inflate(R.layout.one_line_list_item, parent, false);
        }

        CheckBox cbId = convertView.findViewById(R.id.cbid);
        TextView nameTextView = convertView.findViewById(R.id.name);
        TextView dateTextView = convertView.findViewById(R.id.date);
        TextView descriptionTextView = convertView.findViewById(R.id.description);

        final Person s = (Person) this.getItem(position);

        Log.i(TAG, "" + s.get_id());

        nameTextView.setText(s.getName());
        descriptionTextView.setText(s.getDetails());
        dateTextView.setText(s.getDay() + " " + s.getMonth() + " " + s.getYear());

        if (cbId != null ) {
            cbId.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Toast.makeText(c, "" + s.get_id(), Toast.LENGTH_SHORT).show();
                }
            });

            cbId.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // update your model (or other business logic) based on isChecked
                    int selected_id = s.get_id();
                    if (selected.contains(selected_id) && !isChecked) {
                        selected.remove(selected.indexOf(selected_id));
                        Toast.makeText(c, "REMOVED: " + selected_id + " - " + isChecked, Toast.LENGTH_SHORT).show();
                    } else {
                        selected.add(selected_id);
                        Toast.makeText(c, "ADDED: " + selected_id + " - " + isChecked, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        //ONITECLICK
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(c, s.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        convertView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(c, " -- onLongClick -- " + s.get_id() + " - " + s.getName(), Toast.LENGTH_SHORT).show();
                return false;
            }
        });



        return convertView;
    }

Person Class

public class Person {

    private String name;
    private String day;
    private String month;
    private String year;
    private String details;
    private int _id;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDay() { return day; }
    public void setDay(String day) { this.day = day; }
    public String getMonth() { return month; }
    public void setMonth(String month) { this.month = month; }
    public String getYear() { return year; }
    public void setYear(String year) { this.year = year; }
    public String getDetails() { return details; }
    public void setDetails(String details) { this.details = details; }
    public int get_id() { return _id; }
    public void set_id(int _id) { this._id = _id; }
    public Person() { }
}

one_line_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="6dp"
    android:background="?android:attr/activatedBackgroundIndicator">

    <CheckBox
        android:id="@+id/cbid"
        android:layout_width="wrap_content"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="6dp"
        android:layout_marginLeft="26dp"
        android:layout_marginEnd="6dip"
        android:layout_marginRight="12dp"
        android:text="" />

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="26dp"
        android:layout_toStartOf="@id/cbid"
        android:layout_alignParentTop="true"
        android:lineHeight="18dp"
        android:maxLines="1"
        android:text="@string/name"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/date"
        android:layout_width="fill_parent"
        android:layout_height="18dp"
        android:layout_below="@+id/name"
        android:layout_toStartOf="@id/cbid"
        android:lineHeight="12dp"
        android:maxLines="1"
        android:text="@string/date"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/description"
        android:layout_width="fill_parent"
        android:layout_height="18dp"
        android:layout_below="@id/date"
        android:layout_toStartOf="@id/cbid"
        android:lineHeight="18dp"
        android:maxLines="1"
        android:text="@string/additional_description"
        android:textSize="16sp" />

</RelativeLayout>

Sorry for this long code, I put only the necessary parts of each Class to make it as clear as possible...

The issue is:
When clicking any checkbox on the list, it seems to be checking also others that are hidden from the view.
I tried to isolate the issue as possible but can't figure this out...
Any ideas why it would be checking also other items that are hidden from view??
They are checked in intervals of 8 and also unchecked when any of the is unchecked....




How do I sum between check boxes in google sheets?

I have a google sheet file that I'm using to collect data from boss drops in a game. Every once in awhile there is special loot. That special loot comes on average every 867,000 points. What I'm trying to do in the sheet is create a way to see how many points it has been since I received a special loot. A cell called "points dry".

The easy way is to just manually sum the points from the two checkboxes. =sum(B26:B48) or something like that. But I'd like to automate it so that it just sums between the last two checkboxes in column I. I'm pretty stumped on this and I don't know how to approach it.

Here are some screenshots from my spreadsheet.

enter image description here




vendredi 20 décembre 2019

Allow click on "row" or checkbox within "row" (polymer)

I have a polymer template that looks like this:

<paper-dropdown-menu id="myMenu" label="checkbox list" multi>
   <paper-listbox class="dropdown-content">
      <template is="dom-repeat" items="[[availableItems]]">
         <paper-item on-tap="menuCheckedChanged">
            <paper-checkbox id$="chkClass_" checked="">
              [[item]]
            </paper-checkbox>
         </paper-item>
      </template>
   </paper-listbox>
</paper-dropdown-menu>

As you can see, I'm trying to react to the on-tap event of the paper-item and not the only it's child paper-checkbox. I'd like the user to be able to check an item in the list when they click anywhere on the "row". Mainly because the paper-dropdown-menu closes when you click anywhere on the "row" (paper-item).

The menuCheckedChanged function looks like this:

menuCheckedChanged: function(e) {
      var index = e.model.index;
      var item = e.model.item;
      var checkbox;
      if(e.target.tagName == "PAPER-ITEM") {
        checkbox = e.target.firstChild;
        this.eventFire(checkbox, 'tap');
        return;
      } else {
        checkbox = document.getElementById("chkClass_" + index);
      }
      if (checkbox.checked) {
        this.push("myItems", item);
        this.notifySplices("myItems", this.myItems);
      } else {
        this.removeItem(item);
      }
      this._changed();
    },
    eventFire: function(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    },

As you can see, the strategy I'm trying is to inspect e.target to determine which element was "tapped" and mimic the "tap" event of the checkbox if it the target was the paper-item (row). I expect the new event to toggle the checked attribute of the checkbox I'm firing a tap for. But it doesn't (though it does invoke the menuCheckChanged function).

Any ideas how I can achieve the desired behavior?




Given two yes/no fields, how can I use JavaScript to make the field 2 value checked "Yes" whenever the field 1 value is checked "Yes"?

If Field 1 is checked "Yes" then Field 2 should be checked "Yes"

This is what I've been trying so far:

Field 1:

<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field1||Question15||ENDFIELDTAG||&nbsp;</label></div>
<div class="col9"><input type="radio" name="Field1" id="Question15yes" value="Yes" onclick="Check()">Yes&nbsp;<input type="radio" name="Field1" value="No" onclick="Check()">No</div>

Field 2:

<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field2||Question16||ENDFIELDTAG||&nbsp;</label></div>
<div class="col9"><input type="radio" name="Field2" id="Question16yes" value="Yes" onclick="Check()">Yes&nbsp;<input type="radio" name="Field2" value="No" onclick="Check()">No</div>

I was trying something as simple as this js below, but I'm definitely missing something. Any help would be greatly appreciated!

<script language="JavaScript">    
function Check()  {
$("#Question15yes").click(function(){
     if ($(this).is(':checked'))
     {
         $("#Question16yes").val("Yes");
     }
        }
      });
    }      
</script>



Loop through checkboxes and display checked if 'ID'=='ID'

I'm fairly new to PHP and need a bit of guidance. I have a page called createemployee.php that uses a for loop to display checkboxes used to define an employees skillset, the following code works:

<?php for($i = 0; $i < count($skills); $i++):?>
    <span class="description">
         <input  id="customCheck1" type="checkbox" name="skills[]" value="<?=$skills[$i]['skill_id'];?>">
         <label class=" badge badge-warning" for="customCheck1"><?=$skills[$i]["skill_name"]?></label>
    </span>
<?php endfor;?>

I'm trying to create a page for editemployee.php in which the details of a specific employee is loaded and editable by the user. I would like to display checked values if the checkbox was checked.

I am using a linking table to allow one employee to have multiple skills, like so:

CREATE TABLE emp_skill (
emp_skill_id INT PRIMARY KEY UNSIGNED AUTO_INCREMENT,
emp_id INT UNSIGNED,
skill_id INT UNSIGNED,
FOREIGN KEY emp_id REFERENCES employee(`emp_id`),
FOREIGN KEY skill_id REFERENCES skill(`skill_id`)
);

If I nest for loops like so (this is wrong, but testing=learning and it gave me an output similar to what I'm wanting), the output is printed with the correct checkboxes selected, but the data taken from skills is duplicated each time it is equal to emp_skill (due to nesting for loops).

 <?php for($j = 0; $j < count($emp_skill); $j++):?>
  <?php for($i = 0; $i < count($skills); $i++):?>
      <span class="description">
          <input  id="customCheck1" type="checkbox" name="skills[]" value="<?=$skills[$i]['skill_id'];?>" 
          <?php if ($skills[$i]["skill_id"]==$emp_skill[$j]['skill_id']) echo 'checked="checked"';?>>
          <label class=" badge badge-warning" for="customCheck1"><?=$skills[$i]["skill_name"]?></label>
     </span>
 <?php endfor;?>
<?php endfor;?>

I am looking for advice on how I can output checked values if $skill.skill_id is matching a row within the $emp_skill.skill_id without duplicating the output of $skill on the webpage?

I assume I will need to use a loop of some kind (maybe foreach or while, opposed to for), but as I said - I'm fairly new to PHP and I've been stuck on this part for a few hours! Any guidance would be appreciated. TIA




Checkbox remembered only on page refresh

I have a page with checkboxes. If I check some of them and go back, when I return to that page with a link the checkboxes are unchecked, if at that point I refresh the page, the checkboxes I previusly checked becomes cheked again. I have no javascript to manage this behavior, just Turbolinks enabled. Why is this and how can I restore checkboxes right from the start?

<!doctype html>
<html lang="en">

<head>
  <link rel='icon' href='favicon.ico' type='image/x-icon' />

  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="style/css/bootstrap.min.css">
  <link rel="stylesheet" href="style/css/style.css" type="text/css">

  <script src="https://kit.fontawesome.com/e5f3028323.js" crossorigin="anonymous"></script>

  <!-- JavaScript -->
  <script type="text/javascript" src="/js/turbolinks.js"></script>

  <script type="text/javascript" src="/js/js.cookie.js"></script>

  <title>App</title>
</head>

<body>

  <section id="setup-game" class="container">
    <div class="row">
      <div class="col text-center">
        <div class="list-checkbox list-group list-button mx-auto mt-2">
          <label class="list-group-item d-flex justify-content-between align-items-center pointer-cursor">
            <input class="checkbox-cw" type="checkbox">
          </label>
          <label class="list-group-item d-flex justify-content-between align-items-center pointer-cursor">
            <input class="checkbox-cw" type="checkbox">
          </label>
          <label class="list-group-item d-flex justify-content-between align-items-center pointer-cursor">
            <input class="checkbox-cw" type="checkbox">
          </label>
          <label class="list-group-item d-flex justify-content-between align-items-center pointer-cursor">
            <input class="checkbox-cw" type="checkbox">
          </label>
          <label class="list-group-item d-flex justify-content-between align-items-center pointer-cursor">
            <input class="checkbox-cw" type="checkbox">
          </label>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col text-center mb-3">
        <button type="button" class="btn-largo" onclick="keepTrack();">Track Game</button>
      </div>
    </div>
  </section>

  <!-- JavaScript -->
  <script type="text/javascript" src="js/bootstrap-native-v4.min.js"></script>
  <script type="text/javascript" src="js/script.js"></script>
</body>

</html>



Is there a way to get an array of ticked checkboxes from a form using the GET method? PHP

I am trying to get an array of all ticked values from the GET form in php. Currently the value that is returned by doing $_GET['cat'] is the last value ticked as a string.

<form method='get' action='/products.php'>
  <p class='rob-font my-0'>
     <input type='checkbox' name='cat' value='Spirits' class='mr-1'>Spirits
  </p>

  <p class='rob-font my-0'>
     <input type='checkbox' name='cat' value='Liqueurs' class='mr-1'>Liqueurs
  </p>

  <p class='rob-font my-0'>
     <input type='checkbox' name='cat' value='Wine' class='mr-1'>Wine
  </p>
</form>

I have found many solutions for this using a POST form, but I am trying to do it with a GET form.




Taking input in PHP from checkbox in loop

<?php

if(isset($_POST['submit'])){
    $field_Values_array = $_POST['field_name'];
    $pass_array = $_POST['class'];

    $sg = "";

    $len1 = count($field_Values_array);
    $class = implode(", ",$pass_array);

    $x=0;
    while($x<$len1){
        $sg = $sg."Book - ".$field_Values_array[$x]." Set - ".$class."<br>";
        $x++;
    }

    echo $sg;

    print '<pre>' ; print_r($field_Values_array); print '</pre>';
    print '<pre>' ; print_r($pass_array); print '</pre>';
}

?>


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var maxField = 10; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><input type="text" name="field_name[]" value=""/> <input type="checkbox" name="class[]" value="A" />A <input type="checkbox" name="class[]" value="B" />B <input type="checkbox" name="class[]" value="C" />C <input type="checkbox" name="class[]" value="1" />1 <input type="checkbox" name="class[]" value="2" />2 <input type="checkbox" name="class[]" value="3" />3 <input type="checkbox" name="class[]" value="4" />4 <input type="checkbox" name="class[]" value="5" />5 <input type="checkbox" name="class[]" value="6" />6 <input type="checkbox" name="class[]" value="7" />7 <input type="checkbox" name="class[]" value="8" />8 <a href="javascript:void(0);" class="remove_button"><img src="remove.png"/></a></div>'; //New input field html 
    var x = 1; //Initial field counter is 1

    //Once add button is clicked
    $(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
        }
    });

    //Once remove button is clicked
    $(wrapper).on('click', '.remove_button', function(e){
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>
</head>
<body>
<div class="container">
    <form action="index.php" method="post">
        <div class="field_wrapper">
            <div>
                <input type="text" readonly value="Book Name"/>
                <input type="text" readonly value="Book Set"/>
            </div>
            <div>
                <input type="text" name="field_name[]" value=""/>
                <input type="checkbox" name="class[]" value="A" />A
                <input type="checkbox" name="class[]" value="B" />B
                <input type="checkbox" name="class[]" value="C" />C
                <input type="checkbox" name="class[]" value="1" />1
                <input type="checkbox" name="class[]" value="2" />2
                <input type="checkbox" name="class[]" value="3" />3
                <input type="checkbox" name="class[]" value="4" />4
                <input type="checkbox" name="class[]" value="5" />5
                <input type="checkbox" name="class[]" value="6" />6
                <input type="checkbox" name="class[]" value="7" />7
                <input type="checkbox" name="class[]" value="8" />8
                <a href="javascript:void(0);" class="add_button" title="Add field"><img src="add.png"/></a>
            </div>
        </div><br><input type="submit" name="submit" value="Submit">
    </form>
</div>
</body>
</html>

enter image description here

I want my code to work as if in the first input field I write english and select A, B, C and then press plus sign and add another pair of same fields then I write Hindi and choose 1 to 8 and press submit. The output should be like Book - English and Set - A,B,C Book - Hindi and Set - 1,2,3,4,5,6,7,8

but I am not able to get this result.




jeudi 19 décembre 2019

How to make delete button to delete recyclerview items in kotlin?

I made selectDelete button on the main activity instead of recyclerview. When I click the delete button, I want to delete the recycler view item whose checkbox is checked. There is an error that checks the recycler view item checkbox and unchecks the item when scrolling. How can I solve this problem? Lets check my activity, data class, recyclerview adapter.

class CartViewActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {

    private val tag = this::class.java.simpleName

    lateinit var adapter: CartItemRecyclerAdapter

    var itemList: MutableList<CartItemDataVo> = arrayListOf()

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cart_view)

   selectDelete.setOnClickListener {

            if(checkBox.isChecked){


            }
        }

        swipeRefreshLo.setOnRefreshListener(this)

        itemList.add(CartItemDataVo("item1", 1, 16800, "cart_doll",false))
        itemList.add(CartItemDataVo("item2", 1, 16800, "cart_cup",false))
        itemList.add(CartItemDataVo("item3", 1, 30000, "cart_perfume",false))
        itemList.add(CartItemDataVo("item4", 1, 16800, "cart_fan",false))

        adapter = CartItemRecyclerAdapter(this, this , itemList)
        recycler_view.adapter = adapter
        recycler_view.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(applicationContext)

    }

    override fun onRefresh() {
        swipeRefreshLo.isRefreshing = false
    }
}
class CartItemDataVo(title: String, itemNumber: Int, pointValue: Int, imageView: String, CheckBox:Boolean) {
    var title: String = title
    var itemNumber: Int = itemNumber
    var pointValue: Int = pointValue
    var image: String = imageView
    var isChecked:Boolean = CheckBox

}


class CartItemRecyclerAdapter(val context: Context, private var activity : Activity, private var dataList : MutableList<CartItemDataVo>) : RecyclerView.Adapter<CartItemRecyclerAdapter.Holder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val view = LayoutInflater.from(context).inflate(R.layout.cart_item_list, parent, false)
        return Holder(view)
    }


    override fun onBindViewHolder(holder: Holder, position: Int) {
        holder?.bind(dataList[position], context)

    }


    override fun getItemCount(): Int = dataList.size

    fun toggleItems() {
        for (item: CartItemDataVo in dataList) {
            var state = item.isChecked
            item.isChecked = state.not()
        }
        notifyDataSetChanged()
    }

    inner class Holder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {

        var titleText = itemView?.findViewById(R.id.titleText) as TextView
        var temNumerTextt = itemView?.findViewById(R.id.textViewItemNumer) as TextView
        var pointValueText = itemView?.findViewById(R.id.pointValueText) as TextView
        var imageView = itemView?.findViewById(R.id.imageView) as ImageView
        var checkBox = itemView?.findViewById(R.id.checkBox) as CheckBox

        fun bind(data: CartItemDataVo, context: Context) {
            if (data.image != "") {
                val resourceId =
                    context.resources.getIdentifier(data.image, "drawable", context.packageName)
                imageView?.setImageResource(resourceId)
            } else {
                imageView.setImageResource(R.mipmap.ic_launcher)
            }
            titleText?.text = data.title
            temNumerTextt?.text = data.itemNumber.toString()
            pointValueText?.text = data.pointValue.toString() + "P"

            if (data.isChecked) {
                checkBox.buttonDrawable =
                    checkBox.context.getDrawable(R.drawable.check_box_active_cs)
                val layout = activity?.findViewById(R.id.layoutOrder) as LinearLayout
                layout.visibility = View.VISIBLE
            } else {
                checkBox.buttonDrawable = checkBox.context.getDrawable(R.drawable.check_box_no)
                val layout = activity?.findViewById(R.id.layoutOrder) as LinearLayout
                layout.visibility = View.GONE
            }


            checkBox?.setOnClickListener {
                if (checkBox.isChecked == data.isChecked) {
                    checkBox.buttonDrawable = it.context.getDrawable(R.drawable.check_box_active_cs)
                    val layout = activity?.findViewById(R.id.layoutOrder) as LinearLayout
                    layout.visibility = View.VISIBLE
                } else {
                    checkBox.buttonDrawable = it.context.getDrawable(R.drawable.check_box_no)
                    val layout = activity?.findViewById(R.id.layoutOrder) as LinearLayout
                    layout.visibility = View.GONE
                }


            }
        }
    }
}
```



DataGridView doesn't show actual value of checkboxcolumn

I read data from database and bind it to a List

private void SetDataSource
{
    List<Warehouse> list = ListWarehouse(idINV); // DB query.
    m_WarehouseBindingList = new BindingList<Warehouse>(list);
    m_WarehouseBindingSource.DataSource = m_WarehouseBindingList;
}

Bind it to the DataGridView

private void LoadDataGridView()
        {
            if (m_WarehouseBindingSource== null) { return; }
            if (dgWarehouse.DataSource != null)
            {
                dgWarehouse.DataSource = null;
                dgWarehouse.Rows.Clear();
                dgWarehouse.Columns.Clear();
            }
            dgWarehouse.AutoGenerateColumns = true;
            dgWarehouse.DataSource = m_WarehouseBindingSource;
}

And set DataBinding to Textbox (and Checkbox)

private void SetDataBinding()
        {

tbAmount.DataBindings.Clear();
            tbAmount.DataBindings.Add("Text", m_WarehouseBindingSource, "Amount", true, DataSourceUpdateMode.OnPropertyChanged);
 chkCounted.DataBindings.Clear();
            chkCounted.DataBindings.Add("Checked", m_WarehouseBindingList, "Counted", true, DataSourceUpdateMode.OnPropertyChanged);

            _warehouse = null; // Object of class Warehouse.
            _warehouse = (Warehouse)m_WarehouseBindingSource.Current;
        }

Now I enter a value in tbAmount and save the data.

private void tbAmount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                    if (sender is TextBox)
                    {
                        TextBox tb = (TextBox)sender;

                        var v = new DoubleValidator();
                        if (!v.IsValid(tb.Text.ToString()))
                        {
                            MessageBox.Show("Enter double value");
                            tb.Focus();
                        }
                        else
                        {
                            try
                            {
                                Cursor.Current = Cursors.WaitCursor;

                                if (_warehouse != null)
                                {
                                    SaveAmount(_warehouse.IdINV, _warehouse.Amount, true);
                                    m_BestandBindingSource.MoveNext();
                                }
                            }
                            finally
                            {
                                tbAmount.Focus();
                                tbAmount.Text = "";
                                SetDataBinding();
                                Cursor.Current = Cursors.Default;
                            }
                        }
                    }
                }

            }

Now I've got the problem that the "Counted" Column will not be updated. For the amount value everything works fine.

What is wrong? How to solve the problem?




How to checked angular material checkbox if value matched

How to compare 2 array of objects and when value is matched then checked angular material checkbox? eg: In this case operator object is matched so checkbox is checked for operator

app.ts

const arr1 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"2",
      "name":"admins"
   }
]
const arr2 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"3",
      "name":"client"
   }
]

this.arr1.forEach(a1Obj => {
    this.arr2.some(a2Obj => {
        if (a2Obj.id === a1Obj.id) {
            console.log(a1Obj);
        }
    })
});

app.html

<div class="col" *ngFor="let group of groups; let i = index">
    <mat-checkbox value="group.id" [labelPosition]="'after'" [checked]="true" (change)="assignGroups($event, group.id)">
        
    </mat-checkbox>
</div>



Java, JMesa checkbox

I want to create a JMesa checkbox by Java.

I have the following code

HtmlColumn activo =  new HtmlColumn("activo");
 activo.setCellEditor(new CheckboxWorksheetEditor());
 htmlRow.addColumn(activo)

;

This code return a null when I render the table in jsp.

How do I have to create a checkbox with Java and JMesa?




mercredi 18 décembre 2019

How to recyclerview all item drawable change, when click selectAll button.? [duplicate]

When I clicked SelectAll, just first item's checkbox drawable change. I want make all item's checkbox drawable will be change. How to make select all check box work in kotlin??

    SelectAll.setOnClickListener {

      if(SelectAll.isChecked){
         SelectAll.buttonDrawable=it.context.getDrawable(R.drawable.check_box_active_cs)
         checkBox.buttonDrawable=it.context.getDrawable(R.drawable.check_box_active_cs)

          else {
          SelectAll.buttonDrawable= it.context.getDrawable(R.drawable.check_box_no)
          checkBox.buttonDrawable= it.context.getDrawable(R.drawable.check_box_no)

        }

        }
       swipeRefreshLo.setOnRefreshListener(this)


        itemList.add(CartItemDataVo("item1", 1, 16800, "cart_doll"))
        itemList.add(CartItemDataVo("item2", 1, 16800, "cart_cup"))
        itemList.add(CartItemDataVo("item3", 1, 30000, "cart_perfume"))
        itemList.add(CartItemDataVo("item4", 1, 16800, "cart_fan"))
        itemList.add(CartItemDataVo("item5", 1, 16800, "cart_bear"))

        val itemRecyclerAdapter = CartItemRecyclerAdapter(this, this , itemList)

        recycler_view.adapter = itemRecyclerAdapter
        recycler_view.layoutManager = 
        androidx.recyclerview.widget.LinearLayoutManager(applicationContext)      
    }

    override fun onRefresh() {
        swipeRefreshLo.isRefreshing = false
    }
}



Collecting data from an Json array and filter with checkboxes

I'm being trained as a junior developer and my task is to filter a json array with three checkboxes. At the moment I have my HTML code with the checkboxes, they have onchange property, then in my javascript code I used

Array.from(document.querySelectorAll('input[name=party]:checked')).map(elt => elt.value)

to take the array with the value of the checkboxes, but I have no idea how to compare the checkbox value with the json array to filter what I need.

Here we've got the code at the moment

HTML:

<div class='row'> <b>Filter by Party:</b> <label for='Republican'>Republican</label> <input onchange="partyFilter" type='checkbox' name='party' id='Republican' value='R'> <label for='Democrat'>Democrat</label> <input onchange="partyFilter" type='checkbox' name='party' id='Democrat' value='D'> <label for='Independent'>Independent</label> <input onchange="partyFilter" type='checkbox' name='party' id='Independent' value='I'> </div>

JAVASCRIPT (taking checkboxes values)

`Array.from(document.querySelectorAll('input[name=party]:checked')).map(elt => elt.value)

JAVASCRIPT (filtering my array to take the "party" value miembros.filter(rep => rep.party === 'R') miembros.filter(dem => rep.party === 'D') miembros.filter(ind => rep.party === 'I')`

I've no idea how to connect the values received with mi javascript function to filter the array.