lundi 31 mai 2021

How to retain checked value when filtering list

I have a filtering function 'filterUsers' working on the 'filteredUsers' array of objects. Each object is rendered as a list item with some data and a checkbox. The function is fired every time the user changes the text input value. If an item is checked when filtered out the checked value is lost. I need a solution to retain the checked value.

const UsersList = () => {
const { users } = useContext(UsersContext);
const [checkedUsersIds, setCheckedUsersIds] = useState([]);
const [filteredUsers, setFilteredUsers] = useState([]);

useEffect(() => setFilteredUsers(users), [users]);
useEffect(() => console.log(checkedUsersIds), [checkedUsersIds]);

const checkUsers = async e => {
    if (e.target.checked) {
        const checkedUser = users.find(user => user.id === Number(e.target.name));
        setCheckedUsersIds([...checkedUsersIds, checkedUser.id]);
    } else {
        setCheckedUsersIds(checkedUsersIds.filter(user => user !== Number(e.target.name)));
    }
};

const filterUsers = e => {
    setFilteredUsers(
        users.filter(
            user =>
                user.first_name.toLowerCase().includes(e.target.value.toLowerCase().trim()) ||
                user.last_name.toLowerCase().includes(e.target.value.toLowerCase().trim())
        )
    );
};

return (
    <>
        <input
            type="text"
            name="filter_users"
            className={classes.filter_input}
            onChange={e => filterUsers(e)}
            placeholder="search user..."
            autoComplete="off"
        />

        <ul>
            {filteredUsers.length ? (
                filteredUsers.map(user => {
                    return (
                        <label key={user.id} htmlFor={user.name}>
                            <li className={classes.user_container}>
                                <div className={classes.user_subcontainer}>
                                    <div
                                        className={`${classes.avatar_container} ${
                                            user.gender === 'Male' ? classes.male : classes.female
                                        }`}
                                    >
                                        {user.avatar ? (
                                            <img className={classes.avatar} src={user.avatar} alt="#" />
                                        ) : (
                                            <div className={classes.img_alt}>
                                                {user.first_name.slice(0, 1)}
                                                {user.last_name.slice(0, 1)}
                                            </div>
                                        )}
                                    </div>
                                    <h3
                                        className={user.gender === 'Male' ? classes.male_text : classes.female_text}
                                    >
                                        {user.first_name} {user.last_name}
                                    </h3>
                                </div>
                                <div className={classes.checkbox_container}>
                                    <input type="checkbox" name={user.id} onChange={e => checkUsers(e)} />
                                </div>
                            </li>
                        </label>
                    );
                })
            ) : (
                <h1 className={classes.list_loading}>List loading...</h1>
            )}
        </ul>
    </>
);

};




Flutter Multiple Checkbox From API

I have been able to display Json data from API in FutureBuilder Widget. However, the widget has checkbox for each list. Whenever I check on one list, the whole list get checked. I want a help on how to check each list individually and be able to use the data of the selected list.

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:bottom_navy_bar/bottom_navy_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mar/Components/mydrawer.dart';
import 'package:mar/Services/auth.dart';
import 'package:mar/sccreens/readRequirements.dart';
import 'package:mar/sccreens/scanAnalysis.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../constants.dart';
import 'infoAnalysis.dart';
import 'login_screen.dart';

class Know extends StatefulWidget {
  static String id = 'Know';
  @override
  _KnowState createState() => _KnowState();
}

class _KnowState extends State<Know> {
  List sympotms = [];
  int currentIndex = 2;
  bool valuefirst = false;
  int _bottomBarIndex = 0;
  Auth _auth;

  showdialogall(context, String mytitle, String mycontent) {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30),
            ),
            title: Text(
              mytitle,
              style: TextStyle(color: Colors.deepOrange),
            ),
            content: Text(mycontent),
            actions: [
              Center(
                child: RaisedButton(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15),
                    ),
                    color: kMainColor,
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => ReadReq()),
                      );
                    },
                    child: Text(
                      "Requirements",
                      style: TextStyle(color: Colors.black),
                    )),
              ),
            ],
          );
        });
  }

  Future fetchdata() async {
    var res = await http.get("http://10.0.2.2/medical/symptoms.php");
    if (res.statusCode == 200) {
      var obj = json.decode(res.body);
      return obj;
    }
  }

  bool isSearching = false;

  @override
  void initState() {
    fetchdata().then((data) {
      setState(() {
        sympotms = data;
      });
    });
    super.initState();
  }

  void _filterSymptoms(value) {
    setState(() {
      filteredsympotms = sympotms
          .where(
              (sym) => sym['name'].toLowerCase().contains(value.toLowerCase()))
          .toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: kMainColor,
        title: Text(
          "Know Your Analysis",
          style: TextStyle(
            fontFamily: 'Pacifico',
          ),
        ),
        actions: <Widget>[
          FlatButton(
            child: CircleAvatar(
              child: Image(
                image: AssetImage('images/icons/medical.png'),
              ),
              backgroundColor: Colors.black,
            ),
            onPressed: () {
              Navigator.pushNamed(context, Scan.id);
            },
          ),
        ],
        centerTitle: true,
      ),
      drawer: MyDrawer(),
      body: Column(
        children: [
          Expanded(
            child: sympotms.length > 0
                ? ListView.builder(
                    itemBuilder: (_, index) {
                      return Container(
                        child: Row(
                          children: [
                            SizedBox(width: 10),
                            Checkbox(
                              value: this.valuefirst,
                              onChanged: (bool value) {
                                setState(() {
                                  valuefirst = value;
                                });
                              },
                              checkColor: Colors.greenAccent,
                              activeColor: Colors.black,
                            ),
                            Text(
                              "${sympotms[index]['SymptomsName']}",
                              style: TextStyle(fontSize: 17.0),
                            ),
                          ],
                        ),
                      );
                    },
                    itemCount: sympotms.length,
                  )
                : Container(child: Center(child: Text("Loading..."))),
          ),
          RaisedButton(
            child: Text(
              " Submit ",
              style: TextStyle(fontSize: 20),
            ),
            onPressed: () {
              showdialogall(context, "Result !", "CBC Test");
            },
            // onPressed: showdialogall(context, "Result !", "CBC Test"),
            color: Colors.green,
            textColor: Colors.white,
            splashColor: Colors.grey,
            padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
          ),
        ],
      ),
      //Navigation
      bottomNavigationBar: BottomNavyBar(
        animationDuration: Duration(milliseconds: 800),
        curve: Curves.easeInOut,
        selectedIndex: currentIndex,
        onItemSelected: (index) async {
          if (index == 0) {
            Navigator.pushNamed(context, Scan.id);
          }
          if (index == 1) {
            Navigator.pushNamed(context, Information.id);
          }
          if (index == 2) {
            Navigator.pushNamed(context, Know.id);
          }
          if (index == 3) {
            SharedPreferences pref = await SharedPreferences.getInstance();
            pref.clear();
            await _auth.signOut();
            Navigator.popAndPushNamed(context, LoginScreen.id);
          }
          setState(() {
            currentIndex = index;
          });
        },
        items: <BottomNavyBarItem>[
          BottomNavyBarItem(
            icon: Icon(
              Icons.camera_alt,
            ),
            title: Text('Scan'),
            activeColor: Colors.black,
            inactiveColor: Colors.black,
          ),
          BottomNavyBarItem(
            icon: Icon(
              Icons.perm_device_information,
            ),
            title: Text('Information'),
            activeColor: Colors.black,
            inactiveColor: Colors.black,
          ),
          BottomNavyBarItem(
            icon: Icon(
              Icons.open_in_new_outlined,
            ),
            title: Text('Know analysis'),
            activeColor: Colors.black,
            inactiveColor: Colors.black,
          ),
        ],
      ),
    );
  }
}

I want a help on how to check each list individually and be able to use the data of the selected list.

this image display my problem




Get whole selected Column value in the HTML table

I have a problem getting the Checkbox and Company whole values from the HTML table column, below is a sample picture:

output1

Now I just can get the value in the first row only, the alert message shows Checkbox value is: true and Company value is: Alfreds Futterkiste.

May I know how I can get the whole values of Checkbox and Company in the table column like below what I want the expected result, the alert message will show Checkbox value is: true,false,true,false,true,false and Company value is: Alfreds Futterkiste,Centro comercial Moctezuma,Ernst Handel,Island Trading,Laughing Bacchus Winecellars,Magazzini Alimentari Riuniti:

output2

function show_value(){
    var checkbox_val = document.getElementById("checkbox_val");
    var company_name = document.getElementById("company_name").value;
    alert ("Checkbox value is: "  + checkbox_val.checked + " and Company value is: " + company_name);
    //alert ("Company Name value is: "  + company_name);
}
https://stackoverflow.com/questions/ask#
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Checkbox</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val" value="0"/>&nbsp;</td>
    <td><input type="text" id="company_name" name="company_name" value="Alfreds Futterkiste"/></td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0"/>&nbsp;</td>
    <td><input type="text" id="company_name"  name="company_name" value="Centro comercial Moctezuma"/></td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0"/>&nbsp;</td>
    <td><input type="text" id="company_name"  name="company_name" value="Ernst Handel"/></td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0"/>&nbsp;</td>
    <td><input type="text" id="company_name"  name="company_name" value="Island Trading"/></td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val"  value="0"/>&nbsp;</td>
    <td><input type="text" id="company_name"  name="company_name" value="Laughing Bacchus Winecellars"/></td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" id="company_name" name="company_name" value="Magazzini Alimentari Riuniti"/></td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>
<button type="button" id="updateBtn_5" class="btn btn-sm btn-primary" onclick="show_value()">Show checkbox and company value</button>   
</body>
</html>

Hope someone can guide me on how to solve it. Thanks.




How to change the color on checkmark on disabled checkbox

Here is example of my CSS:

.checkbox { 

input[type='checkbox'] {
&+label{
&:after {
content: '';
border: 2px solid white
}}

&:disabled{
&+label{
&+:before{
opacity: .7;
}}
}}
}

So the border: 2px solid white; is changing the color of the checkmark. But in both situations, when checkbox is disabled and enabled.

I need to change the color of the ckeckmark in black only if its disabled.

If i try to change here &:disabled{...} It is changing the color only on the border and not on the checkmark.

Does someone know how to change the color on checkmark in disabled checkbox?




dimanche 30 mai 2021

Filter array of objects through checkboxes

This is a React.js filter problem and I'm stuck here. The problem has static data of movies as an array of objects and we have to filter that data according to the checked state of different checkboxes.

Static Data:

export const data = [
    {
        id: 1,
        title: 'Batman',
        rating: 1,
        genre: 'Action'
    },
    {
        id: 2,
        title: 'Superman',
        rating: 5,
        genre: 'Comedy'
    },
    {
        id: 3,
        title: 'Spiderman',
        rating: 3,
        genre: 'Thriller'
    },
    {
        id: 4,
        title: 'BananaMan',
        rating: 2,
        genre: 'Action'
    },
    {
        id: 5,
        title: 'OrangeMan',
        rating: 4,
        genre: 'Drama'
    }
];

The abstract UI has the following picture that represents 2 types of filters.

  • Rating
  • Genre

Screenshot:

Filters screenshot

Both Filters are rendered on the UI as checkboxes. So, I've created a component called Checkboxes which will take a prop named list and it is an array of objects.

This list represents unique ids of checkboxes which will help us to track the checked or unchecked state of the checkbox. The different checkboxes id will save inside the state which is an array.

const [checkedArray, setCheckedArray] = useState([]);

Finally, I'm rendering this Checkboxes component twice inside the parent component called App.js. One for rating and the other for genre.

List:

export const listCheckboxesRating = [
    {
        id: 0,
        name: 'rating',
        label: 'Any Rating'
    },
    {
        id: 1,
        name: 'rating1',
        label: 'Rating 1'
    },
    {
        id: 2,
        name: 'rating2',
        label: 'Rating 2'
    },
    {
        id: 3,
        name: 'rating3',
        label: 'Rating 3'
    },
    {
        id: 4,
        name: 'rating4',
        label: 'Rating 4'
    },
    {
        id: 5,
        name: 'rating5',
        label: 'Rating 5'
    }
];

export const listCheckboxesGenre = [
    {
        id: 0,
        name: 'genre',
        label: 'Any Genre'
    },
    {
        id: 1,
        name: 'action',
        label: 'Action'
    },
    {
        id: 2,
        name: 'comedy',
        label: 'Comedy'
    },
    {
        id: 3,
        name: 'drama',
        label: 'Drama'
    },
    {
        id: 4,
        name: 'thriller',
        label: 'Thriller'
    }
];

Checkboxes component:

import {useState} from 'react';
import {handleToggle} from '../../utils';

const Checkboxes = ({list, handleFilters}) => {
    const [checkedArray, setCheckedArray] = useState([]);

    const onChangeHandler = (checkboxId) => {
        const newState = handleToggle(checkboxId, checkedArray);
        setCheckedArray(newState);
        // Update this checked information into Parent Component
        handleFilters(newState);
    };

    return list.map((item, index) => {
        return (
            <div key={index}>
                <input
                    type="checkbox"
                    id={item.name}
                    checked={checkedArray.indexOf(item.id) !== -1}
                    onChange={() => onChangeHandler(item.id)}
                />
                <label htmlFor={item.name}>{item.label}</label>
            </div>
        );
    });
};

export default Checkboxes;

I'm passing the whole state of these checkboxes through a function named handleFilters to parent component App.js. You can see this line of code.

handleFilters(newState);

The App.js component is saving states of these checkboxes with something like this:

 const [selected, setSelected] = useState({
        rating: [],
        genre: []
    });

App.js component:

import {useState} from 'react';
import Checkboxes from './Checkboxes';
import {data, listCheckboxesRating, listCheckboxesGenre} from '../data';

const App = () => {
    const [movies, setMovies] = useState(data);
    const [selected, setSelected] = useState({
        rating: [],
        genre: []
    });

    /**
     * This function will perform the filtration process based on the key value.
     *
     * @param {number[]} checkboxState - It will take the final state of checkboxes
     * @param {string} key - It will help us to determine the type of filtration
     */
    const handleFilters = (checkboxState, key) => {
        const newFilters = {...selected};
        newFilters[key] = checkboxState;
        // Filtration process
        for (let key in newFilters) {
            if (
                newFilters.hasOwnProperty(key) &&
                Array.isArray(newFilters[key]) &&
                newFilters[key].length > 0
            ) {
                if (key === 'rating') {
                } else if (key === 'genre') {
                }
            }
        }

        // Save the filtered movies and update the state.
        //  setMovies();
        setSelected(newFilters);
    };

    return (
        <div>
            {movies.map((movie) => (
                <div key={movie.id}>
                    <div>Name: {movie.title}</div>
                    <div>Genre :{movie.genre}</div>
                    <div>Rating: {movie.rating}</div>
                    <hr />
                </div>
            ))}

            <div className="row">
                <div className="col">
                    <h1>Filter by Rating</h1>
                    <Checkboxes
                        list={listCheckboxesRating}
                        handleFilters={(checkboxState) =>
                            handleFilters(checkboxState, 'rating')
                        }
                    />
                </div>

                <div className="col">
                    <h1>Filter by Genre</h1>
                    <Checkboxes
                        list={listCheckboxesGenre}
                        handleFilters={(checkboxState) =>
                            handleFilters(checkboxState, 'genre')
                        }
                    />
                </div>
            </div>
        </div>
    );
};

export default App;

The checkboxes checked or unchecked state of both filters are working fine and correctly updated with ids inside the parent selected state with something like this.

 const [selected, setSelected] = useState({
            rating: [1,2,3],
            genre: [2,4]
        });

But here is the confusing part where I'm stuck. How to map these checkboxes ids and filter the data according to these ids?

I've defined a function in the App.js component handleFilters(checkboxState, key) in which I wanted to iterate the selected state to perform the filtration process but my mind is not making logic and I need help.

WORKING DEMO:

Edit react-filter

repository link.




Buttons working with checkboxes. Content sliding in from behind

I have a problem with doing a nice menu based on photos, with hidden content behind them.

The RED and GREEN containers are buttons working with checkboxes. I want this code to work like this:

The content behind the button is a text referring to a button (photo), which will be shown to the user only after pressing it. I wish my flyout would push the rest of the page down.

At the moment, this is what is happening, but unfortunately the second GREEN button does not return to its position touching the RED one, but hides underneath it. It protrudes as much as the content from under the RED is high.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
* {
    margin: 0;
    padding: 0;
    font-family: Open Sans;
    font-size: 16px;
    box-sizing: border-box;
}

.container {
    width: 500px;
    margin: 0 auto;
    background-color: grey;
}

#firstButtonCheck {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    opacity: 0;
    visibility: hidden;
}

#firstButtonCheck ~ .firstContent {
    margin-top: -100%;
    width: 500px;
    display: block;
    transition: margin-top 1s ease-out, max-height 1s ease-out;
    margin-left: auto;
    margin-right: auto;
}

.firstButton {
    display: block;
    height: 400px;
    width: 100%;
    background-color: red;
    cursor: pointer;
    position: relative;
    z-index: 2;
    margin: 0 auto;
}

#firstButtonCheck:checked ~ .firstContent {
    margin-top: 0px;
    transition: margin-top 1s ease-out, max-height 1s ease-out;
}

#secondButtonCheck {
    position: absolute;
    opacity: 0;
    left: 50%;
    transform: translateX(-50%);
    visibility: hidden;
}

#secondButtonCheck ~ .secondContent {
    margin-top: -100%;
    margin-left: auto;
    margin-right: auto;
    width: 500px;
    display: block;
    transition: margin-top 1s ease-out, max-height 1s ease-out;
}

.secondButton {
    display: block;
    width: 500px;
    height: 500px;
    background-color: green;
    cursor: pointer;
    position: relative;
    z-index: 1;
    margin: 0 auto;
}

#secondButtonCheck:checked ~ .secondContent {
    margin-top: 0px;
    transition: margin-top 1s ease-out, max-height 1s ease-out;
}

.secondContent {
 
}
</style>
</head>
<body>
<div class="container">
<input type="checkbox" id="firstButtonCheck"/>
<label class="firstButton" for="firstButtonCheck"></label>
<div class="firstContent">
    <h1>923id92i3d93i</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
</div>

<input type="checkbox" id="secondButtonCheck"/>
<label class="secondButton" for="secondButtonCheck"></label>
<div class="secondContent">
    <h1>dasdasda</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
</div>
</div>

</body>
</html>



samedi 29 mai 2021

Using Checkbox To Select Row In VB

I am fairly new to VB.Net so please excuse the elementary question. I am using a DataGridView to display data that the user will select full rows of the data. I have added a checkbox column (first column) for the user to visually see the rows that were selected. I am trying to set that if the checkbox is selected then the row is selected and if the row is selected then the checkbox is selected. Consequently I am trying to get the opposite to be true for unselecting.

Private Sub DataGridView1_CbxRowSelect(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Dim CellChecked As DataGridViewCheckBoxCell = DataGridView1.Rows(e.RowIndex).Cells(0)
    Dim SelectedRow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)

    If CellChecked.Value = True Then
        SelectedRow.Selected = True
    End If
    If CellChecked.Value = False Then
        SelectedRow.Selected = False
    End If
    If SelectedRow.SelectedCell = True Then
        Checked.Value= True
    End If
End Sub

Any help would be appreciated, Thank you!




when calling a function including a checkbutton after a tkinter window is created the checkbutton value will always be 0

I'm trying to make a function to create a tkinter window holding a checkbutton. this function is called another Tkinter window is made. whenever i do this, the value of the checkbutton is always 0 even if i select it.

from tkinter import *
def go(value):
    print(value)
    value = value.get()
    print("value of checkbox",value)

def test2():
    tk = Tk()


    value = IntVar() 
    checkbutton = Checkbutton(tk, text = "value", onvalue = 1, offvalue = 0,variable =     value)
    checkbutton.pack()

    button = Button(tk,text = "go", command = lambda:[go(value)])
    button.pack()



window = Tk()

text = Label(window,text = "text")
text.pack()

test2()


window.mainloop()

if i do the same thing without the window, the checkbutton works:

from tkinter import *
def go(value):
    print(value)
    value = value.get()
    print("value of checkbox",value)

def test2():
    tk = Tk()


    value = IntVar() 
    checkbutton = Checkbutton(tk, text = "value", onvalue = 1, offvalue = 0,variable =         value)
    checkbutton.pack()

    button = Button(tk,text = "go", command = lambda:[go(value)])
    button.pack()



#window = Tk()

#text = Label(window,text = "text")
#text.pack()

test2()


#window.mainloop()

maybe the check button in Tkinter is a bit fussy with windows




how to update database using checkbox in flutter

I want to simply update table in database based on the checbox but its so difficult. Cant find a single answer. Very less material is available regarding flutter. I have a list of notes in listview which i get from note table in database. listview contains checkboxes. When I click on save button I want to update status columnn in note table for that particular note as "completed". Can anyone tell how do I do that. I have already posted the same question but I am not able to find my own question on stackoverflow.

note_info.dart

import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/screens/people_list.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:vers2cts/utils/form_helper.dart';

import 'new_note.dart';


class Note_Info extends StatefulWidget{
  final String appBarTitle;
  final CustomerModel customer;


  //Note_Info();
  Note_Info(this. customer, this.appBarTitle);

  @override
  State<StatefulWidget> createState() {
    //return Note_InfoState();
   return Note_InfoState(this. customer,this.appBarTitle);
  }

}

class Note_InfoState extends State<Note_Info> {
  DBService dbService = DBService();
  List<NoteModel> noteList;
  int count = 0;
  int nid;
  String status;
  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<
      ScaffoldState>();
  NoteModel note = NoteModel();
  String appBarTitle;
  CustomerModel customer = new CustomerModel();

  Note_InfoState(this.customer, this.appBarTitle);

  // Note_InfoState();

  bool rememberMe = false;
  DateTime _date = DateTime.now();
  TextEditingController custfNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    updateListView();
    if (noteList == null) {
      noteList = List<NoteModel>();
      updateListView();
    }

    TextStyle titleStyle = Theme
        .of(context)
        .textTheme
        .subhead;
    var height = MediaQuery
        .of(context)
        .size
        .height;
    var name = customer.first_name + " " + customer.last_name;
    custfNameController.text = name;

    return DefaultTabController(
        length: 4,
        child: Scaffold(
            appBar: AppBar(
              actions: [
                IconButton(
                  icon: Icon(
                    Icons.add,

                  ),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (BuildContext context) =>
                            NewNote(customer, note)));
                  },
                )
              ],
            ),
            body: Container(
              child: Column(
                  children: <Widget>[
                    TextField(controller: custfNameController,
                        style: TextStyle(
                            fontSize: 20.0, fontWeight: FontWeight.bold),

                        textAlign: TextAlign.center),
                    Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Row(children: [
                        ImageProfile(customer.cust_photo),
                        Padding(
                          padding: const EdgeInsets.only(left: 30.0),
                          child: IconButton(
                            icon: Icon(
                              Icons.call,
                              color: Colors.green,
                              size: 45,
                            ),
                            onPressed: () {

                            },
                          ),
                        ),

                      ],),
                    ),

                    SizedBox(
                      height: 50,
                      child: AppBar(
                        bottom: TabBar(
                          tabs: [
                            Tab(
                              text: "All",
                              //icon: Icon(Icons.directions_bike),
                            ),
                            Tab(
                              text: "Pending",
                              // icon: Icon(Icons.directions_car,),
                            ),
                            Tab(
                              text: "Cancelled",
                              //icon: Icon(Icons.directions_bike),
                            ),
                            Tab(
                              text: "Completed",
                              // icon: Icon(Icons.directions_car,),
                            ),
                          ],
                        ),
                      ),
                    ),

                    // create widgets for each tab bar here
                    Expanded(
                      child: TabBarView(
                        children: [
                          // first tab bar view widget
                          Container(
                              child: getNotecheckList()
                          ),

                          // second tab bar viiew widget
                          Container(

                          ),


                          Container(
                            child: Center(
                              child: Text(
                                'Cancelled',
                              ),
                            ),
                          ),
                          Container(

                            child: Center(
                              child: Text(
                                'Completed',
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        height: 55.0,
                        width: 200,
                        child: RaisedButton(
                          elevation: 2,

                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)),
                          color: Theme
                              .of(context)
                              .primaryColorDark,
                          textColor: Colors.white,
                          child: Text('Save', textScaleFactor: 1.5,),
                          onPressed: () {
                            setState(() {
                              _save();
                            });
                          },
                        ),
                      ),
                    ),
                  ]
              ),
            )
        ));
  }

  Widget ImageProfile(String fileName) {
    return Center(
      child: CircleAvatar(
          radius: 80.0,
          backgroundImage: fileName == null
              ? AssetImage('images/person_icon.jpg')
              : FileImage(File(customer.cust_photo))),

    );
  }


 

  Future<void> updateListView() {
    final Future<Database> dbFuture = DB.init();
    dbFuture.then((database) {
      int cid = customer.cust_id;

      Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
      noteListFuture.then((noteList) {
        setState(() {
          this.noteList = noteList;
          this.count = noteList.length;
        });
      });
    });
  }

  int _isChecked = -1;
  var selectedIndices = [];

  ListView getNotecheckList() {
    return ListView.builder(
      itemCount: count,
      itemBuilder: (BuildContext context, int position) {
        return Card(
          color: Colors.white,
          elevation: 2.0,
          child: CheckboxListTile(
            title: Text(this.noteList[position].note),
            subtitle: Text(this.noteList[position].actn_on),
            //secondary: const Icon(Icons.web),

            value: selectedIndices.contains(position),
            onChanged: (_) {
              if (selectedIndices.contains(position)) {
                selectedIndices.remove(position); // unselect
              } else {
                selectedIndices.add(position); // select
                

              }
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
        );
      },
    );
  }

  void _save() async {
    try {
      int result = await dbService.updateNote(note);
      if (result != 0) {
        FormHelper.showMessage(
          context,
          "SQFLITE CRUD",
          "Data updated Successfully",
          "Ok",
              () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => People_List(),
              ),
            );
          },
        );
      } else
        FormHelper.showAlertDialog(context, 'Status', 'Problem Saving Note');
    }
    catch(e)
    {
      print('exception');
      print(e);
    }

    /* int result;
    result = await dbService.updateNoteCompl(note,nid);

    if (result != 0) {  // Success
      FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
    } else {  // Failure
      FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');*/
  }


}

note_model.dart

import 'model.dart';

class NoteModel extends Model {
  static String table = 'note';
  bool isSelected=false;
  int note_id;
  int cust_id;
  String note;
  String actn_on;
  int rmnd_ind;
  double prty;
  String colr;
  String sts;

  int id;
  String cre_date;
  String cre_by;
  String mod_date;
  String mod_by;
  int txn_id;
  int delete_ind;

  NoteModel({
    this.note_id,
    this.cust_id,
    this.note,
    this.actn_on,
    this.rmnd_ind,
    this.prty,
    this.colr,
    this.sts,

    this.id,
    this.cre_date,
    this.cre_by,
    this.mod_date,
    this.mod_by,
    this.txn_id,
    this.delete_ind
  });

  static NoteModel fromMap(Map<String, dynamic> map) {
    return NoteModel(
      note_id: map["note_id"],
      cust_id: map['cust_id'],
      note: map['note'].toString(),
      actn_on: map['actn_on'].toString(),
      rmnd_ind: map['rmnd_ind'],
      prty: map['prty'],
      colr: map['colr'].toString(),
      sts: map['sts'].toString(),


      id: map['id'],
      cre_date: map['cre_date'].toString(),
      cre_by: map['cre_by'].toString(),
      mod_date: map['mod_date'].toString(),
      mod_by: map['mod_by'].toString(),
      txn_id: map['txn_id'],
      delete_ind: map['delete_ind'],
    );
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'note_id': note_id,
      'cust_id': cust_id,
      'note':note,
      'actn_on': actn_on,
      'rmnd_ind': rmnd_ind,
      'prty': prty,
      'colr': colr,
      'sts':sts,


      'id': id,
      'cre_date': cre_date,
      'cre_by': cre_by,
      'mod_date':mod_date,
      'mod_by':mod_by,
      'txn_id':txn_id,
      'delete_ind': delete_ind

    };

    if (note_id != null) {
      map['note_id'] = note_id;
    }
    return map;
  }
}

db_helper.dart

import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 1;

  static Future<Database> init() async {
    if (_db != null) {
      return _db;
    }

    try {
      var databasesPath = await getDatabasesPath();
      String _path = p.join(databasesPath, 'CTS.db');
      _db = await openDatabase(_path, version: _version, onCreate: onCreate);
      print('db location:'+_path);

    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db, int version) async {
    
    await db.execute(
        'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
            'note TEXT, '
            'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
            'sts TEXT,'
            'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');        
  }

  static Future<List<Map<String, dynamic>>> query(String table) async =>
      _db.query(table);

  static Future<int> insert(String table, Model model) async =>
      await _db.insert(table, model.toMap());

  static Future<int> update(String table, Model model) async => await _db
      .update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);

  static Future<int> updateNote(String table, Model model) async => await _db
      .update(table, model.toMap(), where: 'note_id = ?', whereArgs: [model.note_id]);


  static Future<int> delete(String table, Model model) async =>
      await _db.delete(table, where: 'id = ?', whereArgs: [model.id]);

  static Future<int> deleteCustomer(String table, Model model) async =>
      await _db.delete(table, where: 'custId = ?', whereArgs: [model.cust_id]);

  static Future<Batch> batch() async => _db.batch();

  static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
      _db.query(table);


}

db_service.dart

import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/utils/db_helper.dart';

class DBService {
Future<int> updateNote(NoteModel note) async {
    await DB.init();
    var result = await DB.updateNote(NoteModel.table, note);
    return result;
  }
}



How to increase size of Boolean type of Checkbox (the image) in a Jtable?

I am creating a maintenance list which requires a column full of checkboxes (Netbeans IDE). so when I added jtable, I went to table contents and changed the type to Boolean for a single column. I have set the row height to 40 and compared to that the checkboxes seems to be too small. Is there a way to increase the size of checkboxes in that particular column?




How to save value in a column for multiple records in table for selected checkboxes in flutter

I have a listview which displays notes from note table in database. this notes have checkboxes. When i click on checkboxes i.e various notes I want to update value as "completed" in 'sts' column of note when i click save button for all those notes. Each note has a note_id. How do I do that?

note_info.dart

import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:vers2cts/utils/form_helper.dart';

import 'new_note.dart';


class Note_Info extends StatefulWidget{
  final String appBarTitle;
  final CustomerModel customer;
  
  Note_Info(this. customer, this.appBarTitle);

  @override
  State<StatefulWidget> createState() {
    //return Note_InfoState();
   return Note_InfoState(this. customer,this.appBarTitle);
  }

}

class Note_InfoState extends State<Note_Info> {
  DBService dbService = DBService();
  List<NoteModel> noteList;
  int count = 0;

  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
  NoteModel note=NoteModel();
  String appBarTitle;
  CustomerModel customer=new CustomerModel();
  Note_InfoState(this.customer, this.appBarTitle);


  bool rememberMe = false;
  DateTime _date = DateTime.now();
  TextEditingController custfNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
  updateListView();
    if (noteList == null) {
      noteList = List<NoteModel>();
      updateListView();
    }

    TextStyle titleStyle = Theme.of(context).textTheme.subhead;
    var height = MediaQuery.of(context).size.height;
    var name=customer.first_name+" "+customer.last_name;
    custfNameController.text = name;

    return DefaultTabController(
        length: 4,
        child: Scaffold(
            appBar: AppBar(
              actions: [
                IconButton(
                  icon: Icon(
                    Icons.add,

                  ),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (BuildContext context) => NewNote(customer,note)));
                  },
                )
              ],
            ),
            body: Container(
              child: Column(
                  children: <Widget>[
                    TextField(controller: custfNameController,
                        style: TextStyle(
                            fontSize: 20.0, fontWeight: FontWeight.bold),

                        textAlign: TextAlign.center),
                    Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Row(children: [
                        ImageProfile(customer.cust_photo),
                        Padding(
                          padding: const EdgeInsets.only(left: 30.0),
                          child: IconButton(
                            icon: Icon(
                              Icons.call,
                              color: Colors.green,
                              size: 45,
                            ),
                            onPressed: () {

                            },
                          ),
                        ),

                      ],),
                    ),

                    SizedBox(
                      height: 50,
                      child: AppBar(
                        bottom: TabBar(
                          tabs: [
                            Tab(
                              text: "All",
                            ),
                            Tab(
                              text: "Pending",
                            ),
                            Tab(
                              text: "Cancelled",
                            ),
                            Tab(
                              text: "Completed",
                            ),
                          ],
                        ),
                      ),
                    ),

                    // create widgets for each tab bar here
                    Expanded(
                      child: TabBarView(
                        children: [
                          // first tab bar view widget
                          Container(
                              child: getNotecheckList()
                          ),

                          // second tab bar view widget
                          Container(

                          ),


                          Container(
                            child: Center(
                              child: Text(
                                'Cancelled',
                              ),
                            ),
                          ),
                          Container(

                            child: Center(
                              child: Text(
                                'Completed',
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        height: 55.0,
                        width: 200,
                        child: RaisedButton(
                          elevation: 2,

                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)),
                          color: Theme
                              .of(context)
                              .primaryColorDark,
                          textColor: Colors.white,
                          child: Text('Save', textScaleFactor: 1.5,),
                          onPressed: () {
                            setState(() {
                            _save();
                            });
                          },
                        ),
                      ),
                    ),
                  ]
              ),
            )
        ));
  }

  Widget ImageProfile(String fileName) {
    return Center(
      child: CircleAvatar(
          radius: 80.0,
          backgroundImage:  fileName == null
              ?AssetImage('images/person_icon.jpg')
              :FileImage(File(customer.cust_photo))),
    );
  }
  Future<void> updateListView() {
    final Future<Database> dbFuture = DB.init();
    dbFuture.then((database) {
      int cid=customer.cust_id;

      Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
      noteListFuture.then((noteList) {

        setState(() {
          this.noteList = noteList;
          this.count = noteList.length;
        });
      });
    });
  }

  int _isChecked=-1;
  var selectedIndices = [];
  ListView getNotecheckList() {

    return ListView.builder(
        itemCount: count,
        itemBuilder: (BuildContext context, int position) {



        return Card(
          color: Colors.white,
          elevation: 2.0,
          child: CheckboxListTile(
            title: Text(this.noteList[position].note),
            subtitle: Text(this.noteList[position].actn_on),
            value: selectedIndices.contains(position),
            onChanged: (_) {
              if (selectedIndices.contains(position)) {
                selectedIndices.remove(position);// unselect
              } else {
                selectedIndices.add(position);  // select
              }
            },
            controlAffinity: ListTileControlAffinity.leading,
                ),
            );
          },
         );
        }

  void _save() async {
    int result;
    result = await dbService.updateNote(note);

    if (result != 0) {  // Success
      FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
    } else {  // Failure
      FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
    }
  }
  }

note_model.dart

import 'model.dart';

class NoteModel extends Model {
  static String table = 'note';
  bool isSelected=false;
  int note_id;
  int cust_id;
  String note;
  String actn_on;
  int rmnd_ind;
  double prty;
  String colr;
  String sts;

  int id;
  String cre_date;
  String cre_by;
  String mod_date;
  String mod_by;
  int txn_id;
  int delete_ind;

  NoteModel({
    this.note_id,
    this.cust_id,
    this.note,
    this.actn_on,
    this.rmnd_ind,
    this.prty,
    this.colr,
    this.sts,

    this.id,
    this.cre_date,
    this.cre_by,
    this.mod_date,
    this.mod_by,
    this.txn_id,
    this.delete_ind
  });

  static NoteModel fromMap(Map<String, dynamic> map) {
    return NoteModel(
      note_id: map["note_id"],
      cust_id: map['cust_id'],
      note: map['note'].toString(),
      actn_on: map['actn_on'].toString(),
      rmnd_ind: map['rmnd_ind'],
      prty: map['prty'],
      colr: map['colr'].toString(),
      sts: map['sts'].toString(),


      id: map['id'],
      cre_date: map['cre_date'].toString(),
      cre_by: map['cre_by'].toString(),
      mod_date: map['mod_date'].toString(),
      mod_by: map['mod_by'].toString(),
      txn_id: map['txn_id'],
      delete_ind: map['delete_ind'],
    );
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'note_id': note_id,
      'cust_id': cust_id,
      'note':note,
      'actn_on': actn_on,
      'rmnd_ind': rmnd_ind,
      'prty': prty,
      'colr': colr,
      'sts':sts,


      'id': id,
      'cre_date': cre_date,
      'cre_by': cre_by,
      'mod_date':mod_date,
      'mod_by':mod_by,
      'txn_id':txn_id,
      'delete_ind': delete_ind

    };

    if (note_id != null) {
      map['note_id'] = note_id;
    }
    return map;
  }
}

db_helper.dart

import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 1;

  static Future<Database> init() async {
    if (_db != null) {
      return _db;
    }

    try {
      var databasesPath = await getDatabasesPath();
      String _path = p.join(databasesPath, 'CTS.db');
      _db = await openDatabase(_path, version: _version, onCreate: onCreate);
      print('db location:'+_path);

    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db, int version) async {
    await db.execute(
        'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
            'note TEXT, '
            'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
            'sts TEXT,'
            'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');}
static Future<List<Map<String, dynamic>>> query(String table) async =>
      _db.query(table);

  static Future<int> insert(String table, Model model) async =>
      await _db.insert(table, model.toMap());

  static Future<int> update(String table, Model model) async => await _db
      .update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);
  static Future<int> updateNote(String table, Model model) async => await _db
      .update(table, model.toMap(), where: 'note_id = ?', whereArgs: [model.note_id]);
static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
      _db.query(table);
}

db_service.dart

import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/utils/db_helper.dart';

class DBService {
Future<int> insertNote(NoteModel note) async {
    await DB.init();
    var result = await DB.insert(NoteModel.table, note);
    return result;
  }
Future<int> updateNote(NoteModel note) async {
    await DB.init();
    var result = await DB.update(NoteModel.table, note);
    return result;
  }
Future<List<NoteModel>> getCustomerNotes(int customer) async {
    await DB.init();
    var res = await DB.rawQuery("note WHERE cust_id = '$customer' ORDER BY actn_on ASC,prty DESC;");
    int count = res.length;
    List<NoteModel> notelist = List<NoteModel>();
    // For loop to create a 'Note List' from a 'Map List'
    for (int i = 0; i < count; i++) {
      notelist.add(NoteModel.fromMap(res[i]));
    }
    return notelist;
  }
}



select all Checkboxes by clicking on the top cell

Сode in three files. In setList () you need to pass an array of objects to allocate, but they are generated using map. What is the right thing to do? in general I am trying to adapt my code to this https://codesandbox.io/s/react-select-all-checkbox-jbub2 But there the array for the Checkbox is moved to a separate file, and mine is generated using map.

1-file)

 let Checkbox = () => {
      
        return (
            <div>
                <label className={s.checkbox}>
                    <input className={s.checkbox__input} type="checkbox"/>
                        <span className={s.checkbox__fake}></span>
                </label>
            </div>
        )
    }

2-file)

 const Tablehead = (handleSelectAll, isCheckAll ) => {
        return (
            <thead className = {s.header}>
            <tr className = {s.area}>
              <th ><Checkbox name="selectAll" id="selectAll" handleClick={handleSelectAll}  isChecked={isCheckAll}/>
</th>            
            </tr>   
          </thead>
        )
    }

3-file)

const TableBody = ({droplets}) => {
    
        const [isCheckAll, setIsCheckAll] = useState(false);
        const [isCheck, setIsCheck] = useState([]);
        const [list, setList] = useState([]);
      
        useEffect(() => {
          setList();
        }, [list]);
      
        const handleSelectAll = e => {
          setIsCheckAll(!isCheckAll);
          setIsCheck(list.map(li => li.id));
          if (isCheckAll) {
            setIsCheck([]);
          }
        };
      
        const handleClick = e => {
          const { id, checked } = e.target;
          setIsCheck([...isCheck, id]);
          if (!checked) {
            setIsCheck(isCheck.filter(item => item !== id));
          }
        };
    
        return (
            <>
                {droplets.map((droplet, index, id, name ) =>
    
                    <tr className={s.area} key={index}   >
                        <td ><Checkbox  key={id} name={name}  handleClick={handleClick}   isChecked={isCheck.includes(id)}/></td>
                        <td><button type="submit" className={s.button}><Edit /></button></td>
                        <td><button type="submit" className={s.button}><Trash /></button></td>
                    </tr>
                )
                }
            </>
        )
    }



vendredi 28 mai 2021

How do I add check box in Form to show payment date?

This is what I have in my Payment Form. I use a Combobox to pull the user info into the payments Form. The trouble I am having is it keeps showing TRUE in the Paid column. In another column to the right of Paid it shows 30 days out when next payment is due.

I've tried this code but it puts it in all the cells in the column


If CheckBox1.Value = True Then
    Range("I:I").Value = Date
    Else: Range("I:I").Value = ""
End If

End Sub```



'Dim xRg As Range
'Updated by Extendoffice 2018/1/30
Private Sub Userform_Initialize()
    Set xRg = Worksheets("Customer").Range("A2:F8")
    ComboBox1.List = xRg.Columns(1).Value
End Sub
Private Sub ComboBox1_Change()
    TextBox1.Text = Application.WorksheetFunction.VLookup(ComboBox1.Value, xRg, 2, False)
    TextBox2.Text = Application.WorksheetFunction.VLookup(ComboBox1.Value, xRg, 3, False)
    TextBox3.Text = Application.WorksheetFunction.VLookup(ComboBox1.Value, xRg, 4, False)
    TextBox4.Text = Application.WorksheetFunction.VLookup(ComboBox1.Value, xRg, 5, False)
    TextBox5.Text = Application.WorksheetFunction.VLookup(ComboBox1.Value, xRg, 6, False)
End Sub
Private Sub cbCancel_Click()
    Unload Me
End Sub

Private Sub cbAdd_Click()

'dimmin Var
    Dim Data As Worksheet

'Setting Var
    Set Data = ThisWorkbook.Sheets("Payments")
    NextRow = Data.Cells(Rows.Count, 1).End(xlUp).Row + 1
    
    Data.Cells(NextRow, 1) = Me.ComboBox1.Value
    Data.Cells(NextRow, 2) = Me.TextBox1.Value
    Data.Cells(NextRow, 3) = Me.TextBox2.Value
    Data.Cells(NextRow, 4) = Me.TextBox3.Value
    Data.Cells(NextRow, 5) = Me.TextBox4.Value
    Data.Cells(NextRow, 7) = Me.CheckBox1.Value
    
    Me.TextBox1.Value = ""
    Me.TextBox2.Value = ""
    Me.TextBox3.Value = ""
    Me.TextBox4.Value = ""
    Me.ComboBox1.Value = ""
    Me.CheckBox1.Value = ""
    
End Sub

Private Sub CommandButton2_Click()
Dim ctl As Control
For Each ctl In Me.Controls
If TypeName(ctl) = “TextBox” Or TypeName(ctl) = “ComboBox” Then
ctl.Value = “”
End If
Next ctl
End Sub```



How to make text of checkbox toggle as well

I have checkbox and text 'click me'. I did not use any external library for checkbox.

<TouchableOpacity
          onPress={onPress}
      >
        {isSelected && (
            <Icon
                color={Colors.darkPurple}
            />
        )}
      </TouchableOpacity>

And import this component into another one adding text (I mean title for checkbox)

        <View>
              <CheckBox
                style={styles.checkBox}
                touchableProps=
              />
              <Text>click me</Text>
            </View>

The issue is that the only checkbox icon is clickable. I need to make title of checkbox be clickable as well.

React Native.




How to filter a list based on multiple checkbox checked in react using useState

enter image description here

I am completely new in React Ecosystem.

  1. I wanna filter the list by selecting more then on checkbox.
  2. Example : If I select Audi and Mercedes it will fetch the data and show me the records for both the filters.



how to send checkbox checked value along with its specific question id in angular

I have a requirement in my project. I have a set of questions which has text, radio, check boxes as options to select and answer on Submit form. I am using below code in my template for checkbox:

<form #form="ngForm" (ngSubmit)="submit(form)">
...
<div *ngFor="let option of question.options">
                    <input type="checkbox" [(ngModel)]="option.Checked" [name]="question.id" value=""
                    (change)="change($event,option.name)">
                
</div>
...
</form>

in my ts file I have code :

 this.testForm = this.fb.group({
      answers : this.fb.array([])
})

now on submit I am calling:

submit(f) {
this.testForm.value.answers.push(f.value)
}

but I need to submit the form as :

answers :[{"questionId": "yes", "questionId2" : "checkbox1 value,checkbox2 value", "questionId3" : "no"}]

where questions id is respective questions id from json, "yes" is selected radio button value for questionId2, and so on.

I am able to get radio button, text box but stuck with check box logic.




Buttons working with checkboxes. Can't make them stick to each other in column

I have a problem with doing a nice menu based on photos, with hidden content behind them.

The RED and GREEN containers are buttons working with checkboxes. I want this code to work like this:

The content behind the button is a text referring to a button (photo), which will be shown to the user only after pressing it. I wish my fly-out would push the rest of the page down.

At the moment, this is what is happening, but unfortunately the second GREEN button does not return to its position touching the RED one, but hides underneath it. It protrudes as much as the content from under the RED is high.

* {
  margin: 0;
  padding: 0;
  font-family: Open Sans;
  font-size: 16px;
  box-sizing: border-box;
}

.container {
  width: 500px;
  margin: 0 auto;
  background-color: grey;
}

#firstButtonCheck {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  visibility: hidden;
}

#firstButtonCheck~.firstContent {
  margin-top: -100%;
  width: 500px;
  display: block;
  transition: margin-top 1s ease-out, max-height 1s ease-out;
  margin-left: auto;
  margin-right: auto;
}

.firstButton {
  display: block;
  height: 400px;
  width: 100%;
  background-color: red;
  cursor: pointer;
  position: relative;
  z-index: 2;
  margin: 0 auto;
}

#firstButtonCheck:checked~.firstContent {
  margin-top: 0px;
  transition: margin-top 1s ease-out, max-height 1s ease-out;
}

#secondButtonCheck {
  position: absolute;
  opacity: 0;
  left: 50%;
  transform: translateX(-50%);
  visibility: hidden;
}

#secondButtonCheck~.secondContent {
  margin-top: -100%;
  margin-left: auto;
  margin-right: auto;
  width: 500px;
  display: block;
  transition: margin-top 1s ease-out, max-height 1s ease-out;
}

.secondButton {
  display: block;
  width: 500px;
  height: 500px;
  background-color: green;
  cursor: pointer;
  position: relative;
  z-index: 1;
  margin: 0 auto;
}

#secondButtonCheck:checked~.secondContent {
  margin-top: 0px;
  transition: margin-top 1s ease-out, max-height 1s ease-out;
}

.secondContent {}
<div class="container">
  <input type="checkbox" id="firstButtonCheck" />
  <label class="firstButton" for="firstButtonCheck"></label>
  <div class="firstContent">
    <h1>923id92i3d93i</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  </div>

  <input type="checkbox" id="secondButtonCheck" />
  <label class="secondButton" for="secondButtonCheck"></label>
  <div class="secondContent">
    <h1>dasdasda</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  </div>
</div>



Excel Userform (VBA) - How to add value in Total if checkbox is checked

I have multiple checkboxes (1 to 8) in Userform (VBA) and their values are mentioned in Ride.Caption (1 to 8). If I check any checkbox, then its value mentioned in Ride should add in Total Value and If I uncheck any checkbox then the value should deduct from the Total Value

As per the below code, I have added all values in Total. But, Checkbox coding is still pending, and I do not know how I can make this code complete. Help me out with your expertise.

Private Sub TotalValue_Click()
Dim X As Double
X = 0
If Len(Ride1.Caption) > 0 Then X = X + Ride1.Caption
If Len(Ride2.Caption) > 0 Then X = X + Ride2.Caption
If Len(Ride3.Caption) > 0 Then X = X + Ride3.Caption
If Len(Ride4.Caption) > 0 Then X = X + Ride4.Caption
If Len(Ride5.Caption) > 0 Then X = X + Ride5.Caption
If Len(Ride6.Caption) > 0 Then X = X + Ride6.Caption
If Len(Ride7.Caption) > 0 Then X = X + Ride7.Caption
If Len(Ride8.Caption) > 0 Then X = X + Ride8.Caption
TotalValue.Caption = X
End Sub



Programmatically Unchecking a Checkbox in Vaadin

I've created a Context menu with a tree structure (added Menu items, then added Checkboxes within those menu items as sub-menu items). This works just fine in terms of adding/removing items manually. However, when it comes to programmatically resetting items there is a conflict in terms of a general Component vs. specific component (in this case, a Checkbox).

Component comp = contextMenu.getItems().get(x).getSubMenu().getItems().get(y);
if (comp instanceof Checkbox) {
    ((Checkbox) comp).setValue(false);
}

Note that comp is not in fact an instance of Checkbox; rather it is returning as com.vaadin.flow.component.contextmenu.MenuItem and that item cannot be cast to a Checkbox. So the question is, how would I uncheck a given Checkbox?




jeudi 27 mai 2021

Checkbox content to be changed while page loading in WPF

I am naïve to WPF .Designed a 50 checkboxes(5 columns and 10 rows like A1,A2,A3...B1,B2,B3..E10) in WPF Application. While page loading, I need to change the checkbox content based on database.(if database status is Enabled, checkbox content changed to Enabled and Color to green, Disabled means checkbox content to Disabled and color to Red ).

I don't know how to assign a content in a checkbox while loading and how to loop over the checkbox names. how to store all the checkbox names into array ?

>  <CheckBox Content="Empty" Foreground="#FFE8D6D6" Height="15"
> HorizontalAlignment="Left" Margin="21,489,0,0" Name="A1"
> VerticalAlignment="Top" Width="59" Click="CheckBox_Click" "/> . . .
>      <CheckBox Content="Empty" Foreground="#FFE8D6D6" Height="15" HorizontalAlignment="Left" Margin="21,489,0,0" Name="E10"
> VerticalAlignment="Top" Width="59" Click="CheckBox_Click" "/>

Any help/idea in appreciated.




Accessing MatCheckbox from AbstractControl

I have a MatCheckbox in a FormGroup that I want to be able to read the indeterminate value of. But the FormGroup only gives me AbstractControls, which do not seem be castable to, nor contain any reference to, the underlying control that I have been able to find.

How can I read the indeterminate value of the underlying MatCheckbox?




Vba autofilter problem on all sheets (with checkboxs and in one column)

I would like to adapt this code so that it works on all the worksheets of my excel. For the moment it only marks on the active sheet.

Thank you very much in advance, an answer would save me the day.

Benten667

PS: I am looking for the answer from several experts. Same question right here: link

Dim filterValues()
Dim counter As Long
Dim ct As MSForms.Control

For Each ct In Me.Controls
    If TypeName(ct) = "CheckBox" Then
        If ct.Value = True Then
            ReDim Preserve filterValues(counter)
            filterValues(counter) = ct.Caption
            counter = counter + 1
        End If
    End If
Next ct
If counter > 0 Then
    With ActiveSheet
        .AutoFilterMode = False
        With .Range("G1", .Cells(.Rows.Count, "G").End(xlUp))
        .AutoFilter
        .AutoFilter field:=1, Criteria1:=filterValues, Operator:=xlFilterValues
        End With
    End With
End If



Get list of all check checkboxes of recyclerview on button click of layout to next activity in android

I am beginner to android development and I want to create a small module which displays contact list along with checkbox. Select particular contact and display its respective sms only. I have populated the recyclerView with contact list and checkbox. Problem = Button is created on layout and not on recyclerView. How to get list of all check checkboxes data of recyclerview on button click (onClick = onContactSave()) which is part of ContactActivity to next activity ContactConfirmActivity. Got stuck onContactSave() to get checkbox data of recyclerView.

1.ContactModel

public class ContactModel {
    String name,number;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }


    private boolean isSelected;

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

2.item_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/ic_person"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintStart_toEndOf="@id/iv_image"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/purple_700"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"/>

        <TextView
            android:id="@+id/tv_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <CheckBox
            android:id="@+id/ch_contact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

3.activity_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContactActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/item_contact"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp">


        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:onClick="onContactSave"
            android:text="Save"
            android:textColor="@android:color/white"
            android:textStyle="bold" />
    </RelativeLayout>

</RelativeLayout>

4.ContactAdapter

package com.example.myapplication;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
    Activity activity;
    ArrayList<ContactModel> arrayList;

    public interface Listener {
        public void onClick(int index);
    }

    private final Listener listener;

    public ContactAdapter(Activity activity, ArrayList<ContactModel> arrayList,Listener listener) {
        this.activity = activity;
        this.arrayList = arrayList;
        this.listener = listener;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (arrayList != null) {
            holder.recycler_checkbox.setOnCheckedChangeListener(null);
            holder.tvName.setText(arrayList.get(position).getName());
            holder.tvNumber.setText(arrayList.get(position).getNumber());
            holder.recycler_checkbox.setChecked(arrayList.get(position).isSelected());
            holder.recycler_checkbox.setTag(arrayList.get(position));
            holder.recycler_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        arrayList.get(position).setSelected(true);
                        listener.onClick(position);
                        Toast.makeText(activity,
                                "Checked : " + arrayList.get(position).getName()
                                , Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.get(position).setSelected(false);
                        Toast.makeText(activity,
                                "Unchecked : " + arrayList.get(position).getName()
                                , Toast.LENGTH_LONG).show();

                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return (arrayList == null) ? 0 : arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName,tvNumber;
        public CheckBox recycler_checkbox;

        public ViewHolder(@NonNull  View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            tvNumber = itemView.findViewById(R.id.tv_number);
            recycler_checkbox = itemView.findViewById(R.id.ch_contact);

        }
    }
}

5.ContactActivity

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

public class ContactActivity extends AppCompatActivity implements ContactAdapter.Listener{

    RecyclerView recyclerView;
    ArrayList<ContactModel> arrayList = new ArrayList<ContactModel>();
    ContactAdapter adapter;


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

        recyclerView = findViewById(R.id.recycler_view);

        checkPermission();
    }

    private void checkPermission() {
        if(ContextCompat.checkSelfPermission(ContactActivity.this, Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(ContactActivity.this,new String[]{Manifest.permission.READ_CONTACTS},100);
        }else {
            getContactList();
        }
    }

    private void getContactList() {
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
        Cursor cursor = getContentResolver().query(uri,null,null,null,sort);
        if(cursor.getCount() > 0){
            while (cursor.moveToNext()){
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Uri uriPhone = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                String selection= ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" =?";
                Cursor phoneCursor = getContentResolver().query(uriPhone,null,selection,new String[]{id},null);
                if(phoneCursor.moveToNext()){
                    String number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    ContactModel model = new ContactModel();
                    model.setName(name);
                    model.setNumber(number);
                    arrayList.add(model);
                    phoneCursor.close();
                }
            }
            cursor.close();
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContactAdapter(this,arrayList, this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            getContactList();
        }else {
            Toast.makeText(ContactActivity.this, "Permission Denied.", Toast.LENGTH_SHORT).show();
            checkPermission();
        }
    }

    public void onContactSave(View view) {
        Intent contactConfirmIntent = new Intent(this,ContactConfirmActivity.class);
        //contactConfirmIntent.putExtra("Name",contactModel.getName());
        startActivity(contactConfirmIntent);

    }

    @Override
    public void onClick(int index) {

    }
}
  1. activity_contact_confirm.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContactConfirmActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text=""
        android:id="@+id/tv"/>

    <Button
        android:id="@+id/btnDisplaySMS"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display SMS"
        android:textAllCaps="false"
        android:layout_alignParentBottom="true"
        android:onClick="onDisplaySMS"/>

</RelativeLayout>

7.ContactConfirmActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ContactConfirmActivity extends AppCompatActivity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_confirm);

        Intent intent = getIntent();
        String message = intent.getStringExtra("Name");
        TextView textView = findViewById(R.id.tv);
        textView.setText(message);

    }

    public void onDisplaySMS(View view) {
        Intent displaySMSIntent = new Intent(this,ListViewSMSActivity.class);
        startActivity(displaySMSIntent);
    }
}



How to remove unnecessary blue outlines of focused checkbox in Mozilla Firefox 89

Focused checkbox in Firefox 89 looks like:

enter image description here

By using userContent.css file - input[type="checkbox"] {outline: none;} does not help. Are there any other ways? Perhaps at about:config?




mercredi 26 mai 2021

CheckBox value always returns true

The checkbox which I had set using a variable always returns the value of variable and the checkbox is always checked. If the value is true it returns true and vice versa

answerOption={isCorrect:true}
<input type="checkbox" checked={(!answerOption.isCorrect) ? false : true}  onChange={this.updateAnswerChecked.bind(this)}  style="cursor:pointer;" />
updateAnswerChecked(e){
   console.log(e.target.checked);
   answerOption.isCorrect = e.target.checked
}



how to create dataset with use checkbox dom javascript

please help me I don't know create dataset with use checkbox,, this is my source code:

const isCompleted    = document.querySelector('[data-input-Book-IsComplete]:checked');

how should it be...? Thank you




mardi 25 mai 2021

Add prices to total with checkbox select Django

I am building a feature to add different services to the checkout in my Django template, but I don't know how to add the total price when selecting checkboxes.

I put a change event on each checkbox and to this and when I check one it is supposed to add the service and its price in the card.

The card :

 <div class="col-4">
      <h4 class="d-flex justify-content-between align-items-center mb-3">
        <span class="text-muted">Votre commande</span>
      </h4>
      <ul class="list-group mb-3" id="panier">
        <li class="list-group-item d-flex justify-content-between lh-condensed">
          <div>
            <h6 class="my-0"></h6>
            <small class="text-muted"></small>
          </div>
          <span class="text-muted"> €</span>
        </li>

      </ul>
        <li class="list-group-item d-flex justify-content-between">
            <span>Total (€)</span>
            <strong><span id="total"></span> €</strong>
        </li>
    </div>

The checkboxes and the script :


and here is my view if needed :

def detail_annonce(request, pk):
myObject = Annonce.objects.get(id=pk)
image = ImageLogement.objects.all()
categorie_service = myObject.categorie_service.all()
services = Services.objects.all()
context = {'annonce': myObject, 'myImages': image, 'categorie_service': categorie_service, 'services':services}
return render(request, 'annonce/search/annonce_result.html', context)



React bind checkboxes with a single button

I'm trying to create a "Read button" for every checkbox that has been checked, this button simply has to change the color of the entire table row, but i'm unable to do it. These are my components:

import "./App.css";
let eventData = require("./data.json");

export class Events extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        read: false
      };
      this.HandleReadBtn = this.HandleReadBtn.bind(this);
    }
    HandleReadBtn = () => {
      console.log(`clicked ` + this.state.read)
      this.setState(state => ({
        read: !state.read
      }));
    }
    render() {
      return <>
        <HomePageHeader Read={this.HandleReadBtn}/>
          <table>
            <TableHeader />
              <tbody>
                {eventData.map((data, key) => {
                return (
                      <TableBody key={key}
                      dispositivo={data.dispositivo}
                      IMEI={data.IMEI} 
                      evento={data.evento}
                      timestamp= {data.timestamp}/>
                    )
                })}
              </tbody>
          </table>
      </>
    };
};

//my header
class HomePageHeader extends React.Component {
  Read = () =>{
    this.props.Read()
  }
  render() {
    return <header className="header">
    <h2>Events</h2>
    <button onClick={this.Read}>Read</button>
    <button>Assign</button>
  </header>
  };
};

class TableBody extends React.Component {
  checked(event) {
    console.log(event.target.checked, event.target.name);
  }
  render () {
    return <tr>
    <td>
      <input type="checkbox" onChange={this.checked} defaultChecked={false}></input>
    </td>
    <td>
    {/* Owner*/}
    </td>
    <td>
      <h5>{this.props.dispositivo}</h5>
    </td>
    <td>
      <h5>{this.props.IMEI}</h5>
    </td>
    <td>
      <h5>{this.props.evento}</h5>
    </td>
    <td>
      <p>{this.props.timestamp}</p>
    </td>
  </tr>
  };
};

As you can see my checkboxes are dinamically created with {eventData.map((data, key) => {

Thank you in advance to anyone that can help me with that, i searched for something similar but i didn't find anything.




How to make a list attached to Data Base in React

I'm preparing a small project for university and I need help The project is an app for Corona accessible high school students. As part of the app, I have the option to be a "teacher user" and I need to enter grades for students. This is where the problem comes in. I want when I go to the "Enter Grades" page, I get a list of all the names of the students(currently checking it on teachers) that appear in the data base, and when I click on one of them I can change their grade.

I can get the list of all users in Checkbox but I can't manage to make Checkbox display them as checked or unchecked. (I working with FireBase) ** I already did tests with console log to check values and everything look fine

class EnterGrades extends React.Component {
state= {
    students: null,
    isLoaded: false,
    checked: false
}

getStudentsOnQeueu = async () => {
    let students = await this.studentsRef.orderByChild("fullname")
    return students
  }
componentDidMount(){
    console.log('mounted')
    db.collection('Teacher').get().then( snapshot =>{
        const students = []
        snapshot.forEach( doc =>{
            KEY = Object.keys(doc.data());
            console.log("KEYS is :"+KEY);
            KEY.forEach( (key_id) => {
                if(key_id=='fullname'){
                    const data = doc.data()
                    console.log(data)
                    students.push(data)
                    console.log('name is:'+doc.data().fullname)
                }
                else{

                }
            })
        })
        this.setState({ students: students})
        this.setState({isLoaded:true})
        getStudentsOnQeueu();
    })
    .catch( error => Alert.alert('Error',error))
}
renderStudentList(){
    if(this.state.isLoaded!=false)
    return this.state.students.map((item,key)=> {
        return(
            <TouchableOpacity style= key={key} onPress={()=> {this.value=!this.value}}>
                <CheckBox value={false}/>
                <Text style=>{item.fullname}</Text>
            </TouchableOpacity>
        )
    })
}

onChecked(id){
    const data = this.state.students
    const index = data.findIndex(x => x.id === id);
    console.log('id is '+ id)
    console.log('index is '+index)
    const isInList = false;
    const checked = []
    if(checked.length > 0){
        console.log('checked length wasnt 0')
        for(let i=0;i<checked.length;i++){
            if(checked[i]==data[index])
                isInList = true;
        }
        if(isInList== false)
            checked.push(data[index]);
    }
    else{
        console.log('checked length was 0')
        console.log('data is' + data[index])
        checked.push(data[index]);
    }
    this.setState({ checked: checked})
    
}

render(){
    if(this.state.isLoaded!=false){
    return (
        <View style={styles.InputContainer}>
            <Text>Enter Grades</Text>
            <FlatList 
            data = {this.state.students}
            renderItem ={({item}) =>
            <Text>
                {`Student name: ${item.fullname}\n`}
                {`Email is: ${item.email}`}
            </Text>
            }
            />
            <RadioForm
                radio_props={this.dataList}
                
                onPress={(value) => {this.setState({value:value})}}
            />
        {this.renderStudentList()}
        <Button
                title="Update Students "
                onPress={() => {
                {this.getSelectedStudents}}
                }
            />
        </View>
    )
    }
}

each teacher has uid,email,checked(false/true) etc.




Checking to see if a checkbox is selected before searching

I am having some trouble with my checkboxes. I am trying to get a returned true or false value out of event listeners on checkboxes and then passing it through an event listener on a button to confirm that at least one checkbox is selected. I'm sorry if this sounds confusing and I feel like there is an easier way to do this. I would like to solve this with pure JavaScript. Really appreciate the help. Below is the code.

<body>
    <script src="racquetObjects.js"></script>
    <div class="mainContainer">
      <div class="selectors">
        <form action="">
          <div class="checkboxes">
            <input type="checkbox" id="babolat" value="Babolat" />
            <label for="babolat">Babolat</label>
            <input type="checkbox" id="wilson" value="Wilson" />
            <label for="wilson">Wilson</label>
            <input type="checkbox" id="power" value="Power" />
            <label for="power">Power</label>
            <input type="checkbox" id="control" value="Control" />
            <label for="control">Control</label>
            <input type="checkbox" id="popular" value="Popular" />
            <label for="popular">Popular</label>
          </div>
          <button type="button" id="find">Find</button>
        </form>
      </div>
      <div class="racquetContainer"></div>
      <div class="bench"></div>
    </div>
    <script src="racquetFinderCB.js"></script>
    <script src="racquetFinder.js"></script>
  </body>

const findButton = document.querySelector("#find");
const checkboxes = document.querySelectorAll(
  ".checkboxes input[type=checkbox]"
);

const checkboxesAreChecked = checkboxes.forEach((el) => {
  el.addEventListener("click", (e) => {
    if (e.target.checked) {
      return true;
    } else {
      return false;
    }
  });
});

const beforeSubmit = () => {
  if (checkboxesAreChecked === true) {
    console.log("Time to search!");
  } else {`enter code here`
    console.log("You need to select an option");
  }
};



lundi 24 mai 2021

how to get id of particular item in list of items in flatlist when user check the checkbox of item

I have wishlist screen, User put products into wishlist screen, but how we get id of item when user check the particular product. because remove item and add to cart button is on header. so how we get id,so checked item we will detete the item and add to cart item.

                     <FlatList 
                        data={wishlist}
                        keyExtractor={(item, index) => {
                            return `${item[0].itemWishlistId}product`;
                        }}

                        // keyExtractor={item => item[0].itemWishlistId}
                        renderItem={itemData =>    
                            <View style={styles.mainContainer}>
                                <View style=>
                                    <View style={styles.checkBoxContainer}>
                                        <Checkbox 
                                            color="#192341"
                                            uncheckedColor="#A9A9A9"
                                            status={checked ? 'checked' : 'unchecked'}
                                            onPress={() => handleClick(itemData.item[0].itemWishlistId)}
                                        />
                                    </View>  
                        
                                    <View style=>
                                            <Text style=>{itemData.item[0].itemWishlistTitle}</Text>
                                    </View>
                                    
                                    <View style=>
                                        <TouchableOpacity 
                                            onPress={() => {
                                                onTapRemoveFromWishlist(wishlistItems)
                                            }}>         
                                            <SvgXml xml={xml.rightArrow}  marginTop={26} width={18} height={18}/> 
                                        </TouchableOpacity>
                                    </View>
                            </View> 
                                <Image source={require('../assets/images/VectorLine.png')} style=/>
                            </View>
                         }
                    />

Here is handleClick funtion of checkbox

let productId;
const handleClick = (itemId) => {
    // setChecked(!checked)
    productId = itemId;
};

this is flatlist of items. and this sample image. How it be done??

deenter image description here




i face the problem on display the result on the selected option and checked box? i am using html and pure javascript

i face the problem on display the result on the selected option and checked box? i am using html and pure javascript I want to display the selected data in the table when one checkbox is checked and one agency is selected. I try to do but cannot. I am new to the programming.

Here is the example data agdropdown: [{ag_id: "690", ad_id: "410", agency_short_name: "HQ", agency_full_name:'HQ', ag_id: "690", ad_id: "411", agency_short_name: "HR", agency_full_name: "HR"

  fyafyidropdown: [{label: "FYA", value: "fya"}, {label: "FYI", value: "fyi"}]
   
    listing: 
    agadgroup_690_410_fya: {
    0: {mail_serial_no: "(To Be Generated After Filing)", mail_subject: "Test Outgoing Mail 
    20/04/2021",…}
    mail_serial_no: "(To Be Generated After Filing)"
    mail_subject: "Test Outgoing Mail 20/04/2021"
    mail_type_value: "Outgoing Mail"
    mail_url: "https:/scs_dashboard=1"
    pending_count: 1}
   Below is my code.
       <div>
 <script type="text/x-handlebars-template" id="proactus1-source">
 <div class="mb-1 m-h-4 flex justify-end items-center">

 <input type="checkbox" id="fyafyi_select"class="fyafyi-checkbox cursor-pointer" name="checkbox 
 " onchange="proactus_update(this)" value="" ><label class="fyafyi-label mr-4 ml-2 
  self- 
  center text-md" value=""></label>
  
  <select id="agency_select" onchange="proactus_update()" class="rounded-md shadow-md border p-2 w- 
    64" style="width: 50%;">
   
   <option value="_" >
  
   </option>
    </select> </div>

    <div class="my-table">
    <table class="tbl  mt-5 w-full border-collapse" id="proactus_table_contents">
    <thead class="text-white border border-gray-400 bg-gray-400">
    <tr class=" flex-1 text-center">
    <th class="align-middle w-40 py-4">Mail Type</th>
     <th class=" text-left align-middle w-60 py-4">Mail</th>
     <th class=" text-left align-middle w-48 py-4">Subject</th>
     <th class=" text-left align-middle min-w-6 w-9 py-4">#</th>
      </tr>
    </thead>
    </table>
    <table class="tbl w-full p-0 border-collapse" id="proactus_table_contents">
    <tbody class=" divide-black divide-y-2 divide-opacity-25">
     <tr id="mail-spinner" class="hidden"><td colspan="4" style="text-center"> 
     <i class="fas fa-circle-notch fa-spin text-blue-600"></i> Loading...</td></tr> 
    
    
    <tr agad_group="" class="cursor-pointer" >
    <td><span     
    class="mail_type  text-sm py-4 px-0 rounded-md"> 
    </span></td>
    <td class="text-sm align-middle w-60 py-4 px-0"></td>
    <td class="text-sm py-4 px-0"></td>
    <td class=" text-sm text-left py-4 px-0 align-middle min-w-6 w-9"><a href="" 
    target="_blank"></a></td>
    </tr>
    
    
    </tbody>
    </table>
 <div class="mb-1 m-h-4 flex justify-end items-center">

 <input type="checkbox" id="fyafyi_select"class="fyafyi-checkbox cursor-pointer" name="checkbox 
 " onchange="proactus_update(this)" value="" ><label class="fyafyi-label mr-4 ml-2 
self-center text-md" value=""></label>
  
  </div>  
 
    </script>
    <div id="proactus1-contents"></div></div>