samedi 31 décembre 2022

Required for dynamically created checkbox using JavaScript not working

I have created a checkbox dynamically using vanilla JavaScript. What I am trying to do is, if no element is selected, it should return an HTML tooltip on the form submit button but it is not working.

Dynamically Generated HTML is:

<form>
    <div id="div_drager">
      <div id="cardDiv_1" class="card p-3 my-3">
        <div class="d-flex justify-content-between">
          <label class="question-input-label" placeholder="Question" id="Question_Input_1">please enter your email</label>
        </div>
        <div id="bodyWrapper_1" class="body-wrapper" required>
          <div class="d-flex justify-content-between py-2">
            <div class="d-flex align-item-center w-100" id="cardDiv_1_divCheckbox_0">
              <input id="cardDiv_1_divCheckbox_0_checkbox_0" placeholder="" type="checkbox" name="bodyWrapper_1"><label id="cardDiv_1_divCheckbox_0_checkboxOption_0" class="radio-label-label">Option 1</label>
            </div>
          </div>
          <div class="d-flex justify-content-between py-2">
            <div class="d-flex align-item-center w-100" id="cardDiv_1_divCheckbox_1">
              <input id="cardDiv_1_divCheckbox_1_checkbox_1" placeholder="" type="checkbox" name="bodyWrapper_1"><label id="cardDiv_1_divCheckbox_1_checkboxOption_1" class="radio-label-label">Option 2</label>
            </div>
          </div>
          <div class="d-flex justify-content-between py-2">
            <div class="d-flex align-item-center w-100" id="cardDiv_1_divCheckbox_2">
              <input id="cardDiv_1_divCheckbox_2_checkbox_2" placeholder="" type="checkbox" name="bodyWrapper_1"><label id="cardDiv_1_divCheckbox_2_checkboxOption_2" class="radio-label-label">Option 3</label>
            </div>
          </div>
          <div class="d-flex justify-content-between py-2">
            <div class="d-flex align-item-center w-100" id="bodyWrapper_1_divCheckbox_6">
              <input id="bodyWrapper_1_divCheckbox_6_checkbox_6" placeholder="" type="checkbox" name="bodyWrapper_1"><label id="bodyWrapper_1_divCheckbox_6_checkboxOption_6" class="radio-label-label">Option 6</label>
            </div>
          </div>
        </div>
      </div>
    </div>
    <input type="submit"/>
  </form>

Can anyone help me to identify what went wrong?

Thanks.




How to get filtered data from multiple checkboxes in react

I am fetching data from Api and based on api data I am filtering data when I click checkbox and the required data could be retrived i.e filtered data from one checkbox if I click and if I click another checkbox all of data disappears .I want to get all the filtered data which I clicked .Below is my code

import React, { useEffect, useState } from 'react'

const Filter = () => {
    const [posts, setPosts] = useState([])

    useEffect(() => {
        filterData()
    }, [])
    const filterData = async () => {
        const res = await fetch("https://jsonplaceholder.typicode.com/posts")
        const data = await res.json()
        setPosts(data)
        console.log("posts", posts)
    }

    const handleClick = (e, userId) => {
        const { value, checked } = e.target
        console.log(userId, "userId")
        console.log(value, "val")
        if (checked) {
            const filterData = posts.filter((item) => item.userId === userId)

            setPosts(filterData)
        }
        else {
            filterData()
            //  const filterDat = posts.filter((e) => e === value)
            // setPosts(filterDat)
        }
    }
    return (
        <div>
            <h2>Filter data</h2>
            <label>Userid1</label>
            <input type="checkbox" value='a' name='filter' onClick={(e) => handleClick(e, 1)} />
            <label>Userid2</label>
            <input type="checkbox" value='b' name='filter' onChange={(e) => handleClick(e, 2)} />
            <label>Userid3</label>
            <input type="checkbox" value='c' name='filter' onChange={(e) => handleClick(e, 3)} />
            <label>Userid4</label>
            <input type="checkbox" value='d' name='filter' onChange={(e) => handleClick(e, 4)} />
            <label>Userid5</label>
            <input type="checkbox" value='e' name='filter' onChange={(e) => handleClick(e, 5)} />
            <label>Userid6</label>
            <input type="checkbox" value='f' name='filter' onChange={(e) => handleClick(e, 6)} />
            <label>Userid7</label>
            <input type="checkbox" value='g' name='filter' onChange={(e) => handleClick(e, 7)} />
            <label>Userid8</label>
            <input type="checkbox" value='h' name='filter' onChange={(e) => handleClick(e, 8)} />
            <label>Userid9</label>
            <input type="checkbox" value='i' name='filter' onChange={(e) => handleClick(e, 9)} />
            <label>Userid10</label>
            <input type="checkbox" value='j' name='filter' onChange={(e) => handleClick(e, 10)} />

            {posts.map((item) => (

                <div key={item.id}>
                    <div>{item.userId} ---- {item.title}</div>
                    <hr />
                    <div>{item.body}</div>
                </div>
            ))}
            <hr />

        </div>
    )
}

export default Filter

I want get filtered data based on all checkboxes




vendredi 30 décembre 2022

Checkbox not returning value at all

I am in the process of creating my final year project for school and am doing a order system for my family company. The part I am having problems with is the product menu and basket.

The goal is to allow the user to select multiple products on screen using checkbuttons and the program would show what is in the basket in a new window.

It seems easy but for some reason, the StringVar() is not returning any value at all. Like it returns a null value or smthn which is just empty.

it should have returned with On when the first button was clicked and Off when it was left alone. I tried using the .pack() thing but it doesnt work with grid. I have also tried using the same window but the result is the same.

this is the sample of the code where the issues are happening.

enter image description here




Ajax call on checking checkbox, how to catch data? [duplicate]

I use the following code:

<script>
    $(document).ready(function() {
  $('.model').click(function() {
    var formData = $('#myForm').serialize();
    console.log('Posting the following: ', formData);
    
    $.ajax({
      url: 'av_check.php',
      data: formData,
      type: 'post',
      dataType: 'html',
      success: function(data) {
        $('#html-container').html(data);
      }
    });
  });
});
</script>

When I check a checkbox, it sends model=VALUE to av_check.php But when I select multiple checkboxes, it sends the data like this:

?model=VALUE&model=VALUE&model=VALUE

But when I return $_POST['model'] , it just returns the first value of MODEL. What can I do to read / use all the MODEL values.

See attachment for screenshot of the console log.

Console Log

I think it is more easy to use Json, but when I change dataType to Json, I don't get a response back to show in the DIV on the page that makes the call.




jeudi 29 décembre 2022

Checkbox list to a new line

enter image description here

I want to move the list of my choices in the checkbox to a new line without exceeding 100% of the form.

<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <legend class="form-label">Votre profession<i class="note-form">*</i></legend>
            <div class="form-check-inline" id="profession_emprunteur">
                <div class="form-check">
                    <input class="radio-special form-check-input" id="profession_emprunteur_0" name="profession_emprunteur" required="required" type="radio" value="employe"/>
                    <label class="form-check-label required font-normal label-special" for="profession_emprunteur_0">Employé</label>
                </div>
                <div class="form-check">
                    <input class="radio-special form-check-input" id="profession_emprunteur_1" name="profession_emprunteur" required="required" type="radio" value="fonctionnaire"/>
                    <label class="form-check-label required font-normal label-special" for="profession_emprunteur_1">Fonctionnaire</label>
                </div>
                <div class="form-check">
                    <input class="radio-special form-check-input" id="profession_emprunteur_2" name="profession_emprunteur" required="required" type="radio" value="cadre"/>
                    <label class="form-check-label required font-normal label-special" for="profession_emprunteur_2">Cadre</label>
                </div>
                
                
                .....
                
                
            </div>
        </div>
    </div>
</div>

Thenk's




v-checkbox weired behaviour when using with v-for in Vuetify

I am using Vue2 and Vuetify2.
I have some checkboxes in Vuetify created using a v-for loop. All checkboxes are inside a dialog component.

The Procedure-

  1. Before opening the dialog, I make an API request and fetch the items. Then, I open the dialog and select the checkboxes.
  2. Before closing the dialog, I empty the selected array, so I will have no items selected on opening the dialog again.

The issue-

  1. When I open the dialog a second time, all checkboxes are already selected even though the variable selected is set to an empty array [].
  2. Then if I try to unselect any item, all are unselecting together and after that only one at a time is selectable.

Here is the working demo of this issue-

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
  </head>
  <body>
    <div id="app">
      <v-app>
        <v-btn dark @click.stop="onBeforeOpen">
          Open Dialog
        </v-btn>
        <div class="mt-5"></div>
        <div class="mt-5">Selected items - </div>
        <v-dialog v-model="dialog" persistent>
          <v-card class="pa-5">
            <div><b>Select items and close dialog.</b></div>
            <v-checkbox
              v-for="item in items"
              :key="item.id"
              v-model="selected"
              :value="item"
              >
              <template v-slot:label>
                <v-card flat>
                  <div></div>
                  <div></div>
                </v-card>
              </template>
            </v-checkbox>
            <div align="center">
              <v-btn color="error" small @click="onBeforeClose"
                >Close Dialog</v-btn
                >
            </div>
          </v-card>
        </v-dialog>
      </v-app>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
    <script>
      new Vue({
        el: '#app',
        vuetify: new Vuetify(),
        data () {
          return {
            dialog: false,
            selected: [],
            items: null,
            msg: null,
          }
        }, 
        methods: {
          onBeforeOpen() {
             this.msg = "Fetching items from API....";
             $.ajax("https://gorest.co.in/public/v2/users", {
              success: (data, status, xhr) => {
                this.items = data.splice(0, 2);
                this.msg = null;
                this.dialog = true
              },
             });
          },
          onBeforeClose() {
            this.selected = [];
            this.dialog = false;
          }
        }
      })
    </script>
  </body>
</html>



mercredi 28 décembre 2022

What is the difference between and

I have been working on some custom checkboxes and ran into an unusual feature - the only way positioning stacks them up is if '.init' and '.hover' are assigned to imgs, and the only way the '.done' class is displayed is if it's assigned to Image.

JSX code

    <div  className={styles.container}>
      <input className={styles.ckb} type="checkbox" name="vt" id="ckb"/>
      <label htmlFor="ckb">
        <img src="VT/vt-.svg" height={88} width={88} className={styles.init}/>
        <img src="VT/vt.svg" height={88} width={88} className={styles.hover} />
        <Image src="VT/vtD.svg" height={88} width={88} className={styles.done} />
       <span className={styles.lab}>: VEGE :</span>
      </label>
    </div>

and CSS

`
.container {
    display: block;
    position: relative;
}

.init {
    position: absolute;
    top: 0; left: 0;
}
.hover {opacity: 0;
    position: absolute;
    top: 0; left: 0;
}

.done {opacity: 0;
    position: absolute;
    top: 0; left: 0;
}

input[type='checkbox'].ckb {
opacity: 1;
cursor: pointer;
position: absolute;
}

input[type='checkbox'].ckb:hover + label .hover {
    opacity: 1;
    display: inline;
    }

input[type='checkbox'].ckb:checked + label .done {
    opacity: 1;
    display: inline;
    }
`

This begs the question - how come?




I'm using C# in studio code, how to get content from checked column in listview?

I'm using C# in studio code, now I created a form with listview, I added columns and checkboxes in the listview, and I want to ask how to extract the content of the first column from the checked row.

I tried to search for ways online but none of them work I guess..




mardi 27 décembre 2022

Store multiple checked checkbox ids into local storage

I have a custom data table with pagination. In my data table I have some users. My objective is to check all / individual users and then store the selected users values into local storage. Also update the local storage if there is changes in checkboxes.

Here is my HTML code:

   <table id="usersTable">
    <thead>
      <tr>
        <th>
          <!------- Check / Uncheck All Checkboxes ------->
          <input type="checkbox" id="checkAll">
          <!-------/ Check / Uncheck All Checkboxes ------>
        </th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
        <tr>
          <td>
            <!----- Checkbox To Select Each User ----->
            <input type="checkbox" class="box" value="1">
            <!-----/ Checkbox To Select Each User ---->
            <td>User 1</td>
          </td>
          <td>
            <!----- Checkbox To Select Each User ----->
            <input type="checkbox" class="box" value="2">
            <!-----/ Checkbox To Select Each User ---->
            <td>User 2</td>
          </td>
          <td>
            <!----- Checkbox To Select Each User ----->
            <input type="checkbox" class="box" value="3">
            <!-----/ Checkbox To Select Each User ---->
            <td>User 3</td>
          </td>
        </tr>
    </tbody>
  </table>
</div>

    <!--
    Paginator: It will work from server side and refreshes on clicking on the pages.
    -->
    <nav aria-label="Page navigation example">
     <ul class="pagination">
      <li class="page-item"><a class="page-link" href="#">Previous</a></li>
      <li class="page-item"><a class="page-link" href="#">1</a></li>
      <li class="page-item"><a class="page-link" href="#">2</a></li>
      <li class="page-item"><a class="page-link" href="#">3</a></li>
      <li class="page-item"><a class="page-link" href="#">Next</a></li>
     </ul>
    </nav>

    <script>
    </script>

I followed several approaches but no one is fully fit for the scenario. Is it possible to help me to achieve it? It is noteworthy that checking all check boxes did not work properly with clicking on another pages of pagination.

So, I need these all together:

  • Check / Uncheck All Checkbox.
  • Store selected user values like [1,2,3] in local storage.
  • Persist checked status of checkboxes even refreshing pages.

Vanilla JavaScript / jQuery, any solution will be appreciated.




I am trying to filter array of objects (courses) with array of unique data (tag) using checkbox button using react hooks. Its not working

I am trying to filter array of objects (courses) with array of unique data (tag) using checkbox button using react hooks. Its not working. At start it shows all the list, but when I select tag one by one, it gets added below the list. You should see all the list first but after selecting tag it should show perticular tag data only. How can I achieve this? enter image description here

Please find my code below:

import React, { useState } from "react";

const courses = [
{ id: "1", course: "React Tutorial", tag: "react" },
{ id: "2", course: "Object-oriented programming (OOP)", tag: "oop" },
{ id: "3", course: "Java Programming", tag: "java" },
{ id: "4", course: "JavaScript Course", tag: "javascript" },
{ id: "5", course: "Spring Boot Tutorial", tag: "spring" },
{ id: "6", course: "Python Bootcamp", tag: "python" },
{ id: "7", course: "Spring Framework Course", tag: "spring" },
{ id: "8", course: "React with Redux", tag: "react" },
{ id: "9", course: "C#: Classes and OOP", tag: "oop" },
{ id: "10", course: "Java Masterclass", tag: "java" },
{ id: "11", course: "ES6 JavaScript Training", tag: "javascript" },
{ id: "12", course: "Learn Python Programming", tag: "python" },
];
const uniqueTags = [...new Set(courses.map((item) => item.tag))];

const App = () => {
const [checked, setChecked] = useState<any>([]);
const [filterData, setFilterData] = useState(courses);

const handleFilterItems = (event: any, tag: any) => {
setFilterData([]);
if (event.target.checked) {
  setChecked([...checked, tag]);
  const addedData = courses.filter((item) => item.tag === tag);
  setFilterData([...filterData, ...addedData]);
} else {
  const removedData = filterData.filter((item) => item.tag !== tag);
  setFilterData(removedData);
  setChecked(checked.filter((item: any) => item !== tag));
}
};

return (
<div style=>
  {uniqueTags.map((tag, index) => (
    <label key={index}>
      <input
        type="checkbox"
        checked={checked.includes(tag)}
        onChange={(event) => handleFilterItems(event, tag)}
      />
      {tag}
    </label>
  ))}
  <hr />
  {filterData.map((course) => (
    <li key={course.id}>
      {course.id}-{course.course}-{course.tag}
    </li>
  ))}
</div>
);
};

export default App;



Insert multiple HTML form checkbox values in single database column

I am making an HTML form using Bootstrap 4 that contains three multiple-choice questions, allowing the reader to choose more than one answer using checkboxes.

Here is an example of one question in the form.

<div class="container">
    <form action="/survey/insert.php" class="was-validated" method="post">
        <div class="form-group">
            <legend class="form-check-label" for="tmp-area"><b>Please select the nearest city, town, or area where you have detailed knowledge of roads, trails, and places on public land.</b></legend>

            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Black Canyon City, Bumblebee, Cortes Junction" />Black Canyon City, Bumblebee, Cortes Junction </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Bouse, Brenda, Parker" />Bouse, Brenda, Parker </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Kingman, Lake Havasu City" />Kingman, Lake Havasu City </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Littlefield, Masquite" />Littlefield, Masquite </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Arizona Strip, Parashant National Monument" />Arizona Strip, Parashant National Monument</label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Tuscon, Winkelman" />Tuscon, Winkelman </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Buckeye, Rainbow Valley" />Buckeye, Rainbow Valley </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Tonto National Forest " />Tonto National Forest </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Coconino National Forest" />Coconino National Forest </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"><input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Apache Sitgreaves National Forest" />Apache Sitgreaves National Forest </label>
            </div>
            <div class="form-check">
                <label class="form-check-label" for="tmp_area"> <input type="checkbox" class="form-check-input" id="tmp_area" name="tmp_area" value="Prescott National Forest" />Prescott National Forest </label>
            </div>
        </div>
    </form>
</div>

Here is an example of /survey/insert.php

<?php
        //Database connection
        $servername = "localhost";
        $username = "user";
        $password = "password";
        $dbname = "name";
        $conn = new mysqli($servername, $username, $password, $dbname);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        // Taking all values from the form data(input)
        $tmp_area = $_REQUEST['tmp_area'];
        

        //Insert form data into table. Set table and columns.
        $sql = "INSERT INTO Survey1 (tmp_area) VALUES ('$tmp_area')";

        if ($conn->query($sql) === true) {
            echo "Your survey has been submitted";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        ?>

The problem

When the user selects multiple checkboxes, only a single checkbox value is added to the database column.

I would prefer that ALL checkbox values, that are selected by the user, insert into the same database column.

All examples and tutorials I have found online require that each checkbox have its own column. Or do not go into much detail on how to accomplish this.

My knowledge of PHP is limited and any help would be greatly appreciated. :)




lundi 26 décembre 2022

Fiori List with Checkbox

With SAP Fiori, is it possible to create a list of items with checkbox preceding them? I’d like to be able to select items from the list and add them to a cart.

I only get checkboxes to select items IF I am using SAP Fiori Tiles.

If indeed possible to have checkboxes WITHOUT Fiori Tiles, then kindly also share some code snippets in any SAP friendly web-language.




Saving array data in table rows to mysql database using checkbox

I have an order table in my project. I am pulling the products from the database to this table using foreach. I show the quantity and unit price calculation information on the table instantly with jquery. I want to save the data in this table from the row selected with the checkbox to the database. I tried a few things with foreach but it looped so it created a new record for each row in the database. I want to print arrays with implode using commas between them. For example, the data in the rows entered in the quantity field in the table should be entered in the quantity field in the database as 1,2,3,4. If I have to explain briefly, I want to make an insert in one go.

Table:Table Image

Table & Form Code:

<form action="" method="POST">
<table class="table table-sm mb-3 text-center align-middle">
   <thead>
      <tr>
         <th>Choose</th>
         <th>Product Name</th>
         <th width="137px">Quantity</th>
         <th>Unit Price</th>
         <th>Total Price</th>
      </tr>
   </thead>
   <tbody>
      <?php foreach($ProductTbl as $product){ ?>
      <tr>
         <th scope="row">
            <div class="form-check form-check-success"><input class="form-check-input" name="check[]" type="checkbox" value="<?= $product-> productid"></div>
         </th>
         <td><?= $product->productname ?></td>
         <td><input class="w-25 text-center quantity" type="text" name="quantity[]" value="0"></td>
         <td><input class="w-25 text-center unitprice" type="text" name="unitprice[]" value="<?= $product->unitprice ?>" disabled="disabled"> €</td>
         <td><input class="w-25 text-center totalprice" type="text"  name="totalprice[]" value="" disabled="disabled"> €</td>
      </tr>
      <?php } ?>
   </tbody>
</table>

<div class="text-center">
   <button class="btn btn-success col-md-2" type="submit" name="add">Offer Preview</button>
   <button class="btn btn-warning col-md-1" type="reset">Reset</button>
   <a href="#"><button class="btn btn-danger col-md-1" type="button">Cancel</button></a>
</div>

</form>


//The code structure I tried

   if(isset($_POST['add'])){
        $check         = $_POST['check']; 
        $quantity      = implode(',', $_POST['quantity']);
        $totalprice    = implode(',', $_POST['totalprice']);

        if (!empty($check)) { 
            foreach ($check as $chk => $value){

                // I printed it for testing.
                echo $value.' - product id in the checked checkbox<br>';
                print_r($quantity);
                print_r($totalprice);
            }
    }
}

How does this code work the way I want?




How to checkbox All with different Id using ant with reactjs

I have a problem how to check all is correct with its id value

Get value from each checkbox i already did it but i don't know how to do with checkbox all

When i check all in "Principal" , i want the remaining 4 checkbox to be checked too, after that the result will be like this in function onChange

result:

   [
     {id:'1' ,  key: "view"  }, 
     {id:'1' ,  key: "add"  }, 
     {id:'1' ,  key: "edit"  }, 
     {id:'1' ,  key: "delete"  }, 
   ]

In the render() function you can edit it to suit other workarounds too

code (you could copy all the code to codesandbox to see exp)

 import React, { useState } from "react";
    import ReactDOM from "react-dom";
    import { Checkbox, Form, Row, Col } from "antd";
    const App = () => {
      const [form] = Form.useForm();

  const listMenu = [
    { id: "1", permission: "Principal" },
    { id: "2", permission: "Teacher" },
    { id: "3", permission: "Student" }
  ];

  const arr = [
    { key: "view" },
    { key: "add" },
    { key: "edit" },
    { key: "delete" }
  ];

  const [checkedList, setCheckedList] = useState(arr || []);

  // RENDE CHECKBOX
  const render = (id) => {
    const item = arr.map((item, index) => {
      const key = item.key;
      return (
        <Col span={6} key={key}>
          <Checkbox value= />
        </Col>
      );
    });
    return item;
  };

  const onChange = (checkedList) => {
    console.log(checkedList);
  };

  // CHECKALL
  const onCheckedAll = (e, id) => {
    setCheckedList(arr);
  };

  return (
    <div>
      <Form form={form}>
        <Form.Item name="permissions">
          <Row>
            <Col span={10} className="ant-col-header">
              <p>Permission:</p>
            </Col>
            <Col span={14} className="ant-col-header">
              <Row>
                <Col span={5}>
                  <p>View</p>
                </Col>
                <Col span={5}>
                  <p>Add</p>
                </Col>
                <Col span={5}>
                  <p>Edit</p>
                </Col>
                <Col span={5}>
                  <p>Delete</p>
                </Col>
                <Col span={4}>
                  <p>All</p>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            {listMenu.map((item, index) => {
              return (
                <React.Fragment key={item.id}>
                  <Col span={10}>
                    <p>{item.permission}</p>
                  </Col>
                  <Col span={14}>
                    <Row>
                      <Col span={20}>
                        <Checkbox.Group
                          onChange={onChange}
                          value={checkedList}
                          style=
                        >
                          {/* CHECKBOX ITEM */}
                          <Row style=>{render(item.id)}</Row>
                        </Checkbox.Group>
                      </Col>
                      <Col span={4}>
                        {/* CHECK ALL */}
                        <Checkbox
                          onChange={(e) => {
                            onCheckedAll(e, item.id);
                          }}
                        ></Checkbox>
                      </Col>
                    </Row>
                  </Col>
                </React.Fragment>
              );
            })}
          </Row>
        </Form.Item>
      </Form>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);



dimanche 25 décembre 2022

Select multiple checkbox in dropdown

When dropdown is clicked ,after clicking on single checkbox it revert backs to dropdown , i need to select multiple checkbox .

Beginner concept ```

i tried prevent default method but didn't work




How to stop calling function when user click on checkbox

I have on table row. In table row I have checkbox and many other information. Now, I am supposed to open another page while click on row. But need to perform another function while click on checkbox. Here checkbox is also part of the row hence if i am going to click on the checkbox it will open the another page assigned to on click of row.

<tr onclick="window.location='openticket.php';" class="cursor1">
        <td>
        <div class="classic">
             
        <div class="row ms-2" id="<?php echo $i['id']; ?>" onmouseover="display(<?php echo $i['id']; ?>)" onmouseleave="display2(<?php echo $i['id']; ?>)">
            
            <div class="col-1 mt-1 returnhide" id="hidecheckbox<?php echo $i['id']; ?>" style="display:none;">
            <div class="form-check">
            <input class="form-check-input checkboxcheckvalueofrow" type="checkbox" id="cb<?php echo $i['id']; ?>" name="ticketcheckbox[]" value="<?php echo $i['ticket_id']; ?>">
            </div>
            </div>
        </td>
        
        <td>Database issue</td>
</tr>   

This is my code. Openticket.php page should not open if i click on the checkbox. How to do it?




How to implement Multiple Checkbox in a pagination based table with Check/Uncheck All and then store all selected checkbox IDS into localstoarge

I am not JavaScript expert. I am trying to implement some features in my table where I have a list of patients. I tried many ways, but can't be able to implement all features together from different approaches. What I am trying to do in my table is:

  • Check/Uncheck Patients.
  • Check/Uncheck all should work on all paginated pages.
  • Store selected patients IDs into local storage.
  • Whenever clicking on Check/Uncheck checkbox and individual checkbox, it should update & save the updated selected patient IDs into local storage.
  • At the end, I just need the local storage Key. contains all selected patient IDs.

Here is the image of the patient table

HTML

<div class="table-responsive">
  <table class="table" id="table">
    <thead>
      <tr class="text-muted">
        <th scope="col">
          <!---------------- Check / Uncheck All Checkboxes ----------->
            <input type="checkbox">
          <!----------------/ Check / Uncheck All Checkboxes ----------->
          <span class="d-none d-md-inline d-lg-inline select_counter"></span>
        </th>
        <th class="col-2">Patient</th>
        <th class="col-1">Age</th>
        <th class="col-1">Gender</th>
        <th class="col-1">Diagnosis</th>
        <th class="col-1">Medication</th>
        <th class="col-1">Last Rx</th>
      </tr>
    </thead>
    <tbody>
      <% @list_users.each.with_index(1) do |patient, index| %>
        <tr>

          <td class="col-1">
          <!---------------- Checkbox To Select Each Patient ------------->
             <input type="checkbox" id="<%= patient.id %>">
          <!---------------/ Checkbox To Select Each Patient ------------->
          </td>

          <td>
          <%=link_to user_name(patient.id)&.strip&.upcase, centres_ebroadcasts_find_by_id_path(user_id: patient.id,source:'patient_table'), :class=>"text-dark", remote:true %>
          </td>
          <td><%= patient&.date_of_birth? ? Date.today.year - patient&.date_of_birth.year : " -- " %></td>
          <td><%= patient.gender? ? patient.gender : "--" %></td>
          <td class="col-2">
            <% diagnosis = patient.consultations.map(&:diagnosis)%>
              <% if diagnosis.compact.empty? %>
                <span class="text-danger">No Diagnosis</span>
              <% else %>
                <%= truncate_text(diagnosis.uniq.compact.join(", "),120).upcase %>
            <% end %>
          </td>
          <td class="col-2">
            <% if medicine = patient&.prescriptions&.completed_prescriptions.map(&:medicines).empty? %>
              <span class="text-danger">No Medicines</span>
            <% else %>
              <%= truncate_text(patient&.prescriptions&.completed_prescriptions.map(&:medicines).flatten.map(&:name).uniq.compact.join(", "), 120).upcase %>
            <% end %>
          </td>
          <td class="col-2"><%= patient&.prescriptions&.completed_prescriptions&.first&.created_at&.strftime("%d, %B, %Y")%></td>
        </tr>
      <% end %>
    </tbody>
  </table>
</div>

<!----------- Javascript --------->
<script>
</script>
<!----------/ Javascript --------->

Issues: When I was trying different approaches, I faced several issues in pagination. For example: checkboxes are only working on current paginated page. Check/Uncheck only works on current paginated page.

Could anyone please help me to implement this? Pure JavaScript or jQuery, any can be used.




samedi 24 décembre 2022

Call function in class State for checked Checkbox from subclass in one file .dart

How to call function with setState for checked Checkbox from sub class in one file dart, i has tried like this but still eror, this is error ' [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: setState() called in constructor: _CustomerWgtFormState#a6d60(lifecycle state: created, no widget, not mounted) E/flutter ( 3739): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created. '

eror ini line code //ERROOR //error in this line, while want to set Checkbox with true m.createState().changedWeek1(true);

these is my code

file class CustomerScreen.dart

import 'package:bubble_tab_indicator/bubble_tab_indicator.dart';
import 'package:flutter/material.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtForm.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtLV.dart';

void main() {
  runApp(CustomerScreen());
}
class CustomerScreen extends StatefulWidget {
  @override
  _CustomerScreenState createState() => _CustomerScreenState();
}

late TabController _tabController;

class _CustomerScreenState extends State<CustomerScreen> with TickerProviderStateMixin{

  late FocusNode myFocusNode;
  CustomerWgtForm _customerWgtForm=new CustomerWgtForm();
  CustomerWgtLV   _customerWgtLV =new CustomerWgtLV();


  @override
  void initState() {
    super.initState();
      _tabController = TabController(length: 2, vsync: this, initialIndex: 0,);
      _tabController.addListener(_handleTabSelection);
      myFocusNode = FocusNode();
      WidgetsBinding.instance.addPostFrameCallback((_) {
         FocusScope.of(context).requestFocus(myFocusNode);
      });
  }

  @override
  void dispose() {
    myFocusNode.dispose();
   _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: Text("Customer"),
              elevation: 0.0,
              titleSpacing: 10.0,
              centerTitle: true,
              leading: InkWell(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Icon(Icons.arrow_back_ios, color: Colors.black54,),
              ),
            ),
`
            body:Column(
               children:[
                   Container(
                     color: Colors.indigo, height: 50, width: 800,
                     margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                     child: TabBar(
                            controller: _tabController,
                         indicatorSize: TabBarIndicatorSize.tab,
                          isScrollable: true,
                  unselectedLabelColor: Colors.black,
                             indicator: BubbleTabIndicator(
                                    indicatorHeight: 48,
                                     indicatorColor: Colors.amber,
                tabBarIndicatorSize: TabBarIndicatorSize.tab,
                                    indicatorRadius: 5,
                             ),
                      tabs: [
                              Tab(icon :Image.asset("images/add_sign.png",),text:'Create Data'),
                              Tab(icon :Image.asset("images/list_go.png",),text:'List Data',)
                            ]
                            ),
                    ),
                    Expanded(
                      child: Container(
                               height: 900,
                               margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                                child: TabBarView(
                           controller: _tabController,
                             children: [
                                    _customerWgtForm,
                                    _customerWgtLV
                                 ]
                                )
                            )
                    )
                  ]
            )
            
        )
    );
  }
}
 //subclass
 class SelectedIndexTabbar{
    static setSelectedIndexTabbarCreateData(){
       _tabController.index=0;
    }
 }
`

file class CustomerWgtLV.dart
import 'package:flutter/material.dart';
import 'package:sfaf/database/entity/Customer.dart';
import 'package:sfaf/database/impl/CustomerImpl.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtForm.dart';

TextEditingController searchNameController = TextEditingController();

  List<Customer?>_getListCustomer=<Customer>[];
  Future _getListCustomerFromDB() async {
       Future<List<Customer?>>? listCustomer=null;
       if(searchNameController.text.isEmpty) {
            listCustomer = CustomerImpl().getListCustomerImpl();
       }
       else{
            listCustomer =   CustomerImpl().getListCustomerByCustNameImpl(searchNameController.text.toString());
       }
       List<Customer?> listnya = await listCustomer ;
       _getListCustomer=listnya;
  }

  class CustomerWgtLV extends StatefulWidget {
       @override
       _CustomerWgtLVState createState() => new _CustomerWgtLVState();
  }

class _CustomerWgtLVState extends State<CustomerWgtLV> {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =  GlobalKey<RefreshIndicatorState>();
  Future<void> refreshListCustomers() async {
    setState(() {
        _getListCustomerFromDB();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
             key: _refreshIndicatorKey,
       onRefresh: () async  {
              _refreshIndicatorKey.currentState?.show();
               refreshListCustomers();
        },
        child: Scaffold(
            backgroundColor:  Colors.blueAccent,
            appBar: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text("List Customers"),
                Expanded(
                  child: TextField(),
                ),
              ],
            ), 
          ),
        body: _buildCardDesign(),
      ),
    );

  }

  Widget _buildCardDesign() {
    return Container(
      margin: EdgeInsets.all(0),
      child: ListView.builder(
          itemCount: _getListCustomer.length,
          shrinkWrap: true,
          physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics()),
          scrollDirection: Axis.vertical,
          itemBuilder: (BuildContext context, int index) {
               var customer = _getListCustomer[index];
               return _buildCardView(customer);
          },
        ),
    );
  }

  Widget _buildCardView(Customer? customer) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Container(
        margin: EdgeInsets.all(7),
        height: 120,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(10))),
        padding: EdgeInsets.fromLTRB(10, 5, 2, 5),
        child: Stack(
          children: [
            Row(
              children: [
                ClipRRect(
                 borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('images/shop_on_ballon_36.png', height: 90.0 , width: 60.0, fit: BoxFit.cover,),
                ),
                Container(
                  padding: EdgeInsets.only(left: 10),
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                               Container(
                                  child: Text('${customer!.custCode} -  ${customer.custName}',
                                              style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 14), ),
                               ),
                            ]
                    ),
                ),
             ],
          ),
          Positioned(top: 80, left: 285,
           child:SizedBox( 
                  width: 80,height: 25,
                  child:ElevatedButton(
               style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(5),
                                    shape: RoundedRectangleBorder(
                             borderRadius: BorderRadius.circular(25),),
                elevation: 15.0,
                           ),
                           onPressed:() async {
                 //Call function getForUpdate in file CustomerWgtForm.dart 
                 //and this UpdateDataCust is Sub class from file CustomerWgtForm,
                             //getForUpdate this is static function
                 //when this execute/button Edit is clicked/tap error
                 UpdateDataCust.getForUpdate(customer!.custId);
                           },
                           child: Row(mainAxisSize: MainAxisSize.min,
                               children: const <Widget>[
                                           Text('Edit', style: TextStyle(fontSize: 14)),
                                ]
                                 ),
                )
               )
          ),

          ]
        ),
      ),

    );
  }

}


file class CustomerWgtForm.dart
import 'package:flutter/material.dart';
import 'package:sfaf/database/entity/Customer.dart';
import 'package:sfaf/database/impl/CustomerImpl.dart';
import 'package:sfaf/view/screen/master/CustomerScreen.dart';
import 'dart:async';

TextEditingController custCodeController = TextEditingController();
TextEditingController custNameController = TextEditingController();
FocusNode custNameFocusNode = new FocusNode();

bool valueW1 = false;
bool valueW2 = false;
ValueNotifier<bool>  valueNotifierWeek1 = ValueNotifier<bool>(false);
StreamController<bool> streamController = StreamController<bool>();

class CustomerWgtForm extends StatefulWidget {
  @override
  _CustomerWgtFormState createState() => new _CustomerWgtFormState();

 }

class _CustomerWgtFormState extends State<CustomerWgtForm> {
  late FocusNode myFocusNode;
  
  //Call this function in subclass, Erorr
  changedWeek1(bool val) async {
       setState(() {
         valueW1=val;
      });
  }
  changedWeek2(bool val){ setState(() { valueW2=val; }); }

  @override
  void initState() {
      super.initState();
      myFocusNode = FocusNode();
  }
  @override
  void dispose() {
    myFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
       return ListView(
       itemExtent: 700.0,
       shrinkWrap: true,
       scrollDirection: Axis.vertical,
       children: [
         Container(
           child: Stack( 
            alignment: AlignmentDirectional.center,
                     children: <Widget>[
                                 Positioned( top: 10, left: 5, child: 
                                           Text('Cust Code', textAlign: TextAlign.right,) ), 
                                 Positioned( top: 3, left: 90,
                                   child:SizedBox( 
                                     width: 100,height: 35,
                                             child: TextField(
                                                      controller: custCodeController,
                                                      decoration: InputDecoration(
                                                   enabledBorder: OutlineInputBorder(
                                                          borderSide: BorderSide(
                                                                    width: 1, 
                                                                    color: Colors.blueGrey),),
                                                    focusedBorder: OutlineInputBorder(
                                                          borderSide: BorderSide( 
                                                                    width: 1, 
                                                                    color: Colors.amber),),
                                                       ),
                                             ),
                                    )
                                 ),
                                 Positioned( 
                                     top:47, 
                                    left: 5,
                                   child: Text('Cust Name') ),
                                 Positioned( 
                                     top:44,
                                    left: 90,
                                   child:SizedBox(
                       width: 250,height: 35,
                                           child: TextField(
                                controller: custNameController,
                                                    decoration: InputDecoration( 
                                  enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(
                                                                      width: 1, 
                                                                      color: Colors.blueGrey),),
                                                          focusedBorder: OutlineInputBorder(
                                                                      borderSide: BorderSide(       
                                                                      width: 1, 
                                                                      color: Colors.amber),),
                                                     ),
                                                     focusNode: custNameFocusNode,
                                          ),
                                  )
                                 ),
                 
                    //WEEK VISITED use Checkbox widget
                    Positioned( 
            top:406, left: 0,
                      child:SizedBox(
                      width: 270,height: 250,
                          child: Padding(
            padding: const EdgeInsets.all(9.0),
                              child: InputDecorator(
                         decoration: InputDecoration(
                          labelText: 'Week Visited', 
                     labelStyle: TextStyle(
                                                  color: Colors.blue),
                                                 border: OutlineInputBorder( 
                                                         borderRadius: BorderRadius.circular(5.0),  
                                                ),
                                                                                                      
                                         contentPadding: EdgeInsets.all(10),
                                     ),
                                     child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                              SizedBox(
                           height: 24.0, width: 24.0,
                                                child: Checkbox(
                                                          value: valueW1!,
                                                      onChanged: (bool? val) {
                                                         changedWeek1(val!);
                                                      },
                                                 )
                                               ),
                                               SizedBox(width: 2.0),
                                               Text("W1"),
                                               SizedBox(width: 10.0),
                                               SizedBox(
                        height: 24.0, width: 24.0,
                                                 child: Checkbox( 
                                     value: valueW2,
                                                     onChanged: (bool? val) {
                                                        changedWeek2(val!);
                                                     },
                                                 )
                                               ),
                                               SizedBox(width: 2.0),
                           Text("W2"),
                           SizedBox(width: 10.0),
                                           ]
                                         ),
                                       ),
                                  ),
                         )
                  ),
              ]

  )
  ),
  ],
  );
  }


  }

  //function for reset widget TextField
 clear(){
     custCodeController.text="";
     custNameController.text="";
  }`

  //SUB CLASS
  //Sub class with static function will call in class CustomerWgtLV.dart 
  class UpdateDataCust with ChangeNotifier  {
     static getForUpdate(String? custId) async  {
       try {
             SelectedIndexTabbar.setSelectedIndexTabbarCreateData();

             clear();
             Customer? customer = await CustomerImpl().getCustomerById(custId!.toString());
             custCodeController.text = customer!.custCode.toString();
             custNameController.text = customer!.custName.toString();
             

             CustomerWgtForm m= new CustomerWgtForm();
                  
         //ERROOOOOOR
         //error in this line, while want to set Checkbox with true 
             m.createState().changedWeek1(true);
                  
       }
       catch (e) {
          print(e.toString());
       }
     }

 }

thanks



How can I select all the checkboxs automatically?

I want to start the page with all the checkboxs selected and also that the counting of checkboxs keeps working.

What is happening is that my button is counting the number of checkbox selected, but the checkboxs is starting empty (with 0 selected at the beginning), like in the image bellow: enter image description here

only after the user select manually which checkboxs they want, the button does the count, like that: enter image description here

I would like that it starts like that: enter image description here

Here is the Father Component (where does the counting):

import React, { useEffect, useState } from "react";
import "./popupOrcamentoSimultaneo.css";
import Card from "./Card";
import api from "../../../../api";

function PopupOrcamentoSimultaneo({ setOpenPopup }) {
  const [profissionais, setProfissionais] = useState([]);
  const [value, setValue] = useState(
    "Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
  );
  const [checkedState, setCheckedState] = useState({});

  /*   const [profissionalID, setProfissionalID] = useState([]); */

  useEffect(() => {
    api.get("profissionais/listarTodos/").then(({ data }) => {
      setProfissionais(data);
    });
  }, []);

  let urlParam = window.location.href.split("=");
  let idProfissionalURL = null;

  if (urlParam.length > 1) {
    idProfissionalURL = urlParam[1];
  }

  /*   useEffect(() => {
    api.get(`detalhesProfissional/${idProfissionalURL}`).then(({ data }) => {
      setProfissionalID(data);
    });
  }, []); */

  let cardsProfissionais = profissionais;
  let listaCardsProfissionais = [];
  const found = cardsProfissionais.find(
    (obj) => obj.idProfissional == idProfissionalURL
  );
  const foundSegmento = found?.segmento;
  const foundEstado = found?.estado;

  const handleOnChange = (e) => {
    setCheckedState((p) => ({ ...p, [e.target.name]: e.target.checked }));
    console.log(checkedState)
  };

  for (let i = 0; i < cardsProfissionais.length; i++) {
    if (
      cardsProfissionais[i].segmento == foundSegmento /* &&
      cardsProfissionais[i].estado == foundEstado */
    ) {
      listaCardsProfissionais.push(
        <Card
          key={i}
          dadosProfissionais={cardsProfissionais[i]}
          handleOnChange={handleOnChange}
        />
      );
      if (listaCardsProfissionais.length == 4) {
        break;
      }
    }
  }

  const changeValue = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className="popup">
      <div className="popup__container">
        <div className="close-container" onClick={() => setOpenPopup(false)}>
          <i className="fa-solid fa-xmark"></i>
        </div>
        <h2 className="popup__titulo">
          {`Profissionais desse segmento em ${foundEstado} recomendados para você.`}
        </h2>

        <div className="cards__profissionais">{listaCardsProfissionais}</div>
        <div className="input-button">
          <div className="input-box">
            <label for="input" className="input-label">
              Escreva sua mensagem
            </label>
            <div>
              <input
                type="text"
                id="input"
                className="input-text"
                placeholder="Olá! Vamos nos casar e gostaríamos de mais informações sobre seu serviço."
                value={value}
                onChange={changeValue}
              />
              <i className="fa-solid fa-pencil"></i>
            </div>
          </div>
          <button type="submit" className="botao-orcamento">
            Solicitar Orçamento (
            {Object.keys(checkedState).filter((i) => checkedState[i]).length})
          </button>
        </div>
      </div>
    </div>
  );
}

export default PopupOrcamentoSimultaneo;

Here is the Card Component:

import React, { useState, useEffect } from "react";
import "./card.css";
import semImagem from "../../../../../fileContents/imagensVitrineProfissional/no-image.png";

function Card(props) {
  let nomeEmpresa = props.dadosProfissionais.nomeEmpresa;
  let segmento = props.dadosProfissionais.segmento;
  let valorMinimo = props.dadosProfissionais.valorMinimo;
  let cidade = props.dadosProfissionais.cidade;
  let estado = props.dadosProfissionais.estado;
  let idProfissional = props.dadosProfissionais.idProfissional;
  let imagemVitrine = props.dadosProfissionais.imagemMarketplace;

  let imagemArquivo = imagemVitrine ? imagemVitrine : semImagem;

  const [check, setCheck] = useState(false)

  return (
    <>
      <div className="card__profissional" key={idProfissional}>
        <div className="card__header">
          <img
            className="card-imagem"
            src={imagemArquivo}
            alt={`${nomeEmpresa}`}
          />
        </div>
        <div className="card__body">
          <h2 className="card__titulo">{nomeEmpresa}</h2>
          <span className="tag">{cidade}</span>
          <div className="checkbox">
            <label className="checkbox-label">
              Solicitar Orçamento
              <input
                type="checkbox"
                className="checkbox-input"
                name={nomeEmpresa}
                value={nomeEmpresa}
                checked={check}
                onClick={() => setCheck(!check)}
                onChange={props.handleOnChange}
              />
              <span className="checkmark"></span>
            </label>
          </div>
        </div>
      </div>
      
    </>
  );
}

export default Card;

if necessary, that is the data from API: enter image description here

I appreciate all help, thanks!




vendredi 23 décembre 2022

Intersect lists of different functions only in relation to the selection of the checkboxes. Error with bool for set objects

I have a problem with 3 checkboxes intersecting when using list in checkbox functions. I would like to use intersection in relation to the quantity and combination of selected checkboxes.

I tried to insert the checkbox functions in a list and combine them with a condition if the checkboxes are only selected or deselected:

all_test = [(Button1_func()) if Checkbutton1.get() else not Checkbutton1.get(),
            (Button2_func()) if Checkbutton2.get() else not Checkbutton2.get(),
            (Button3_func()) if Checkbutton3.get() else not Checkbutton3.get()]

Next, I put the list in c = set.intersection(*all_test)

If I try to select one or more checkboxes, I get the error:

TypeError: descriptor 'intersection' for 'set' objects doesn't apply to a 'bool' object

Let me explain better with an example what I would like to achieve. For example if I select only checkbox1 I would like to print a, b, c, d, e. If I select all the checkboxes I would like to print only a, b, because the elements in common in the three lists are only a, b. How can I print what I said above without getting errors?

I'm looking for a solution that allows me to manage even 20 checkboxes if I need to extend the code in the future.

from tkinter import ttk
import tkinter as tk

root = tk.Tk()
root.geometry("300x300")

funclist = set()
Checkbutton1 = tk.IntVar()
Checkbutton2 = tk.IntVar()
Checkbutton3 = tk.IntVar()

#CHECKBOX'S FUNCTIONS
def Button1_func():
    test1 = ["a", "b", "c", "d", "e"]
    return test1
 
def Button2_func():
    test2 = ["a", "b", "c"]
    return test2

def Button3_func():
    test3 = ["a", "b"]
    return test3

def clicked(flag, func):
    if flag:
        funclist.add(func)
    else:
        funclist.remove(func)


#CHECKBOX
Button1 = tk.Checkbutton(root, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                         bg="#d9d9d9", foreground='black', activebackground="#d9d9d9",
                         command=lambda: clicked(Checkbutton1.get(), Button1_func))
Button1.place(x=10, y=36)

Button2 = tk.Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                         bg="#d9d9d9", foreground='black', activebackground="#d9d9d9",
                         command=lambda: clicked(Checkbutton2.get(), Button2_func))
Button2.place(x=10, y=66)

Button3 = tk.Checkbutton(root, text = "Checkbox 3", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                         bg="#d9d9d9", foreground='black', activebackground="#d9d9d9",
                         command=lambda: clicked(Checkbutton3.get(), Button3_func))
Button3.place(x=10, y=96)


all_test = [(Button1_func()) if Checkbutton1.get() else not Checkbutton1.get(),
            (Button2_func()) if Checkbutton2.get() else not Checkbutton2.get(),
            (Button3_func()) if Checkbutton3.get() else not Checkbutton3.get()]


def try_print():
    #if each checkbox is True:
    if funclist and all(func() for func in funclist): 
        c = set.intersection(*all_test)      
        print(c)

#PRINT BUTTON
button = tk.Button(root, text="Print", command= lambda: [try_print()])
button.place(x=10, y=140)

root.mainloop()



jeudi 22 décembre 2022

Hide div with checkbox value in localstorage

In my project i have a few div's which needs to be hidden when a checkbox is checked. For clarity: the checkbox is on page 1, the div is on page 2. I managed to save the checkbox value to the LocalStorage, now i want to hide the div when the checkbox is checked.

HTML of the checkbox:

<input type="checkbox" id="3" class="functiebox" checked>Nieuwbouw</input><br>

JS to save the value to LocalStorage:

                function saveValue(e) {
                var id = e.id;
                var val = e.value;
                localStorage.setItem(id, val);
            }
            function getSavedValue(v) {
                if (!localStorage.getItem(v)) {
                    return "";
                }
                return localStorage.getItem(v);
            }
            let boxes = document.getElementsByClassName('functiebox').length;

            function save() {
                for (let i = 1; i <= boxes; i++) {
                    var checkbox = document.getElementById(String(i));
                    localStorage.setItem("checkbox" + String(i), checkbox.checked);
                }
            }

            //for loading
            for (let i = 1; i <= boxes; i++) {
                if (localStorage.length > 0) {
                    var checked = JSON.parse(localStorage.getItem("checkbox" + String(i)));
                    document.getElementById(String(i)).checked = checked;
                }
            }
            window.addEventListener('change', save);

The HTML of the div i want to hide/unhide by checking the checkbox:

<div id="afd_bestaand">
    div that needs to be hidden when checkbox is checked.
</div>

I tried a lot of things but couldn't figure out what works. I hope you can help me out!

Thanks in advance!




onEdit in google sheets script is very slow. Making sure only one checkbox is selected per row

I have a google sheet workbook with four sheets that have surveys. Each survey has one question per row, with two to four choices that can be selected. Each choice has a corresponding checkbox. I need to make sure that if the user changes a selection in a row then the previously selected checkbox is unchecked. This works fine, but it's slow in unchecking the old choice. At it's very fastest it takes a couple of seconds but it can take 7 or 8 seconds sometimes. It seems to me it should take just a fraction of a second, there's not that much being done. Maybe I'm going about it the wrong way.

Here's my onEdit function and one of the functions it calls. All of the called functions are basically the same, with different numbers of rows, and they all behave about the same as far as slowness goes.

function onEdit(e) {
   
  // get event object data: sheet name, row number and column number
  const sheet = e.range.getSheet();
  const row = e.range.rowStart;
  const col = e.range.columnStart;
  const currentsheet = sheet.getSheetName()
   
  switch(currentsheet) {
    case "Adaptive Behavior":
      onEditADaptive(sheet, row, col)
    case "Social Communication":
      onEditSocComm(sheet, row, col)
    case "Behavior 6-18":
      onEditBehavior618(sheet, row, col)
    case "BRIEF-2 Parent Report":
      onEditBRIEF2(sheet, row, col)

  }
}


`
function onEditBehavior618(mySheet, myRow, myCol) {
  
  switch(myCol) {
    
        // case when column C is checked   C-E-G
        case 3:
          mySheet.getRangeList(["E" + myRow,"G" + myRow]).uncheck();
          break;
    
        // case when column E is checked
        case 5:
          mySheet.getRangeList(["C" + myRow,"G" + myRow]).uncheck();
          break;
    
        // case when column G is checked
        case 7:
          mySheet.getRangeList(["C" + myRow,"E" + myRow]).uncheck();
          break;
        
        // cell is outside of columns C, E or G
        default:
          return;
    
      }
}



I'm new to google sheets and scripts. this is the technique I found through a search, and it works fine other than being slow. I'm not sure how else to accomplish what I'm trying to do



how to set checkbox checked attribute in ejs

I want to set checked attribute of checkbox conditionally. When i don't use checked attribute, i can get the value attribute in the post method correctly. However when i add checked attribute to checkbox, the code sets the checked property but I cannot get the value attribute of the checkbox (it becomes undefined in post method). Please can someone explain to me.

When i use completed variable as checked attribute, i cannot get the value of checkbox.

<% newListItems.forEach(function(item) { %>
          <form action="/delete" method="post">
            <div class="item">  
              <% let completed = item.done ? "checked" : "" %>
              <input type="checkbox"  value="<%=item._id%>" <%=completed%> name="modified" onchange="this.form.submit()"> 
              <p><%=  item.name  %></p>
            </div>
          </form>
<% }) %>
"dependencies": {
    "body-parser": "^1.18.3",
    "ejs": "^3.1.8",
    "express": "^4.16.3",
    "mongoose": "^6.8.1"
  }



mercredi 21 décembre 2022

Create Check List Like iPhone Notes

Is this possible to make checklist like iPhone Notes? If user press delete/backspace button keyboard on empty textfield is also delete the checklist and if user press return button on keyboard that will add new checklist?

Checklist on Notes iOS

What I have done is still stuck in how to implement that. I have created class for textfield with checkbox and make an object from them to form class.

class SubTaskItem extends StatefulWidget {
  TextEditingController? textEditingController =
      TextEditingController(text: '');
  SubTaskItem({Key? key, this.textEditingController}) : super(key: key);

  @override
  _SubTaskItemState createState() => _SubTaskItemState();
}

class _SubTaskItemState extends State<SubTaskItem> {
  bool checkboxValue = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.textEditingController = TextEditingController(text: '');
  }

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      value: checkboxValue,
      onChanged: (val) {
        setState(() => checkboxValue = val!);
      },
      title: TextFormField(
        controller: widget.textEditingController,
        style: TextStyle(fontSize: 14.0),
      ),
      controlAffinity: ListTileControlAffinity.leading,
      activeColor: Colors.green,
    );
  }
}

on Class Form I add object for subTaskItem with this

List<SubTaskItem> listSubTaskItem = [];

  addSubTaskItem() {
    SubTaskItem subTaskItem = SubTaskItem();

    listSubTaskItem.add(subTaskItem);

    setState(() {});
  }

Do I need to implement getx for state management or is there any simply way to do that? Thanks




mardi 20 décembre 2022

Combining foreach and while in PHP

I need help, my code below does not show me all the rows that come from the database. I have 8 rows but they show me only 6 rows. if I try to change the break to put it a little lower, it displays all the rows except that it repeats the same file in the checkbox.

<?php
ob_start();
include('_TEMPLATE_/header.inc.php');
?>
<?php  

    if(isset($_POST['download'])){
        $file_to_remove = glob("downloads/*.zip");
        foreach ($file_to_remove as $file) {
            unlink($file);
        }

        if(!isset($_POST['theme-files'])){
            $error = "<div class='alert alert-danger' role='alert'>Attention, Vous devez au moins selectionner un fichier pour télécharger !!!</div>";
        }else{
            $themes = $_POST['theme-files'];

            $characters = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz";
            $string_length = 4;

            $random_characters = substr(str_shuffle($characters), 0, $string_length);
            $zip_name = "Cvs_{$random_characters}.zip";

            $zip_name = "Cvs.zip";
        
            $zip = new ZipArchive();
            $zip->open("downloads/{$zip_name}", ZipArchive::CREATE);
            foreach ($themes as $file) {
                $zip->addFile($file, basename($file));
            }
            $zip->close();
            if(! headers_sent()){
                header("location: downloads/$zip_name");
                ob_end_flush();
            }else{
                echo'<script type="text/javascript">window.location.href="downloads/'.$zip_name.'"</script>';
            }
            

            //echo'<script> location.replace("downloads/'.$zip_name.'"); </script>';
            echo'<script type="text/javascript">window.location.href="viviers"</script>';
        }
    }
?>
<!-- Loader -->
<div id="preloader">
    <div id="status">
        <div class="spinner">
            <i class="ri-loader-line spin-icon"></i>
        </div>
    </div>
</div>
<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
            <!-- start page title -->
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                        <h4 class="mb-sm-0"></h4>
                            <div class="page-title-right">
                            <ol class="breadcrumb m-0">
                                <li class="breadcrumb-item"><a href="javascript: void(0);">Nazox</a></li>
                                <li class="breadcrumb-item active">Viviers
                                </li>
                            </ol>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- end page title -->
            <!-- start page title -->
            <div class="row">
                <div class="col-lg-12">
                <div class="line__separator"></div>
                    <div class="card">
                    <h6 class="card-header"><?php echo $title; ?> | Viviers</h6>
                        <div class="card-body">
                            <div class="data__separator"></div>
                            <div class="dataTables_wrapper dt-bootstrap4 no-footer">
                            <form action="" method="post" enctype="multipart/form-data">
                                <table id="scroll-vertical-datatable" class="table dt-responsive nowrap w-100">
                                    <thead class="thead-light">
                                    <div>
                                    <button type="submit" class="btn btn-success" id="submit_prog" name="download"><i class="ri-download-fill mb-2"></i> Télécharger le CV</button>
                                    </div>
                                    <p class="error"></p>
                                        <?php echo @$error; ?>
                                        <tr>
                                            <th>
                                                Selectionner
                                            </th>
                                            <th>ID</th>
                                            <th>Date vivier</th>
                                            <th>Expérience</th>
                                            <th>Diplôme</th>
                                            <th>Prénom</th>
                                            <th>Nom</th>
                                            <th>Postnom</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $query = "SELECT `apply`.`id`, `apply`.`sexe`, `apply`.`prenom`, `apply`.`nom`, `apply`.`postnom`, `apply`.`tel`, `apply`.`email`, `apply`.`datetime`, `apply`.`cv`, `apply`.`lettre`, `apply`.`id_offre`, `apply`.`status`, `apply`.`years`, `apply`.`diplome`, `postes`.`title` FROM `apply` JOIN `postes` ON `apply`.`id_offre` = `postes`.`id` ORDER BY `apply`.`id` DESC";
                                        //$query = "SELECT * FROM `apply`";
                                        $run_query = mysqli_query($conn, $query);
                                        $count = mysqli_num_rows($run_query);
                                        if($count < 1){
                                            echo '<tr>';
                                            echo '<td></td>';
                                            echo '<td></td>';
                                            echo '<td></td>';
                                            echo '<td></td>';
                                            echo '<td>
                                            <div class="nothing">
                                            <div class="alert alert-danger" role="alert">
                                            <i class="mdi mdi-alert-outline me-2"></i> Votre vivier est encore vide, revenez plus tard !!!
                                            </div></div></td>
                                            ';
                                            echo '<td></td>';
                                            echo '<td></td>';
                                            echo '<td></td>';
                                            echo '</tr>'; 
                                        }else{
                                        $i = 1;                                       
                                        while ($row = mysqli_fetch_assoc($run_query)) {
                                            $files = glob("uploads/cvs/*");
                                            foreach ($files as $theme_file){
                                                $id = $row['id'];
                                                //$user_id = $row['id'];
                                                $sexe = ucfirst($row['sexe']);
                                                $datetime = $row['datetime'];
                                                $date = date("d/m/Y", strtotime($datetime));
                                                $prenom = ucfirst($row['prenom']);
                                                $nom = ucfirst($row['nom']);
                                                $postnom = ucfirst($row['postnom']);
                                                $cv = $row['cv'];
                                                $lettre = $row['lettre'];
                                                $poste = ucfirst($row['title']);
                                                $status = $row['status'];
                                                $years = $row['years'];
                                                $diplome = ucfirst($row['diplome']);
                                                
                                        ?>
                                            <tr>                                               
                                                <td>
                                                <input type="checkbox" name="theme-files[]" value="<?php echo $theme_file; ?>">                                          
                                                </td>                                 
                                                <td><?php echo $i; ?></td>
                                                <td><?php echo $date; ?></td>
                                                <td><?php echo $years; ?> an(s)</td>
                                                <td>
                                                <span class="badge bg-info">
                                                    <?php echo $diplome; ?>
                                                </span>
                                                </td>
                                                <td>
                                                    <?php
                                                    if ($status == '1') {

                                                        echo '<span class="badge bg-info float-end mt-1"><i class="ri-lock-2-line"></i></span>';
                                                    }
                                                    ?>
                                                    <?php echo $prenom; ?>
                                                </td>
                                                <td><?php echo $nom; ?></td>
                                                <td><?php echo $postnom; ?></td>
                                                <td>
                                                <a onclick="cvIinfo(<?php echo $id; ?>)" id="<?php echo $id; ?>" class="userinfo view_cv" href="javascript:void(0)"><i class="mdi mdi-magnify-scan font-size-18"></i></a>
                                                
                                                <?php
                                                if(!empty($lettre)){
                                                    echo '
                                                    <a href="uploads/lettres/'.$lettre.'" class="me-3 text-primary" data-bs-toggle="tooltip" data-bs-placement="top" title="Lettre de motivation">
                                                    <i class="mdi mdi-paperclip font-size-18"></i></a></td>';
                                                } ?>
                                                
                                                </td>
                                            </tr>
                                        </div> 
                                        <?php $i++; ?>
                                        <?php } ?>

                                        <?php } ?>   
                                        <?php break;?>                                  
                                        <?php } ?>                                       
                                    </tbody>
                                </table>
                            </form>
                            </div>
                        </div>
                    </div>
                </div> <!-- end col -->
            </div> <!-- end row -->
            <!-- end row -->
        </div>
    </div>
    <!-- End Page-content -->
    <footer class="footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-sm-6">
                    <script>
                        document.write(new Date().getFullYear())
                    </script> © <?php echo $copyright; ?>.
                </div>
                <div class="col-sm-6">
                    <div class="text-sm-end d-none d-sm-block">
                    Crafted with <i class="mdi mdi-heart text-danger"></i> | Version <?php echo $version; ?>
                    </div>
                </div>
            </div>
        </div>
    </footer>

</div>
<!-- end main content-->

</div>
<!-- END layout-wrapper -->

<!-- JAVASCRIPT -->
<script src="assets/libs/jquery/jquery.min.js"></script>
<script src="assets/js/timeout.js"></script>
<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/libs/metismenu/metisMenu.min.js"></script>
<script src="assets/libs/simplebar/simplebar.min.js"></script>
<script src="assets/libs/node-waves/waves.min.js"></script>

<!-- Required datatable js -->
<script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="assets/libs/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
<!-- Buttons examples -->
<script src="assets/libs/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="assets/libs/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
<script src="assets/libs/jszip/jszip.min.js"></script>
<script src="assets/libs/pdfmake/build/pdfmake.min.js"></script>
<script src="assets/libs/pdfmake/build/vfs_fonts.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.html5.min.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.print.min.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.colVis.min.js"></script>

<script src="assets/libs/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
<script src="assets/libs/datatables.net-select/js/dataTables.select.min.js"></script>

<!-- Responsive examples -->
<script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
<script src="assets/libs/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>

<!-- Datatable init js -->
<script src="assets/js/pages/datatables.init.js"></script>

<script src="assets/js/app.js"></script>


<script src="https://unpkg.com/pdfobject@2.2.8/pdfobject.min.js"></script>
</body>

</html>

<script>
    function cvIinfo(id){
        $.ajax({
            url: 'backend/view_modal.php',
            type: 'post',
            data: {userid: id},
            success: function(response){ 
                $('#show__modal').html(response); 
                $('#empModal').modal('show'); 
            }
        });
    }

    function save_note(id){
     
     var get_note = $('#get_note').val();
     $.ajax({
        url:'backend/update_note.php',
        type:'post',
        data:{get_note: get_note, id:id},
        success: function(response){
            if(response == 'success'){
                $('#result_note').css("color", "green").html('Mise à jour réussie...');
                return true;
            }else{
                $('#result_note').css("color", "red").html(response);
                return false;
            }
        }
     })
    }
    
</script>

<script>
$(document).ready(function() {

var $submit = $("#submit_prog").hide(),
    $cbs = $('input[name="theme-files[]"]').click(function() {
        $submit.toggle( $cbs.is(":checked") );
    });

});
</script>

<div id="show__modal"></div>

I would like each checbox to have its own file and on the other side to show me all the rows




lundi 19 décembre 2022

Is there a way to get a checkbox component out of a checkboxgroup component in Vaadin 23.3.0?

I need a single checkbox component to add a tool-tip on it. However, the component is of a CheckboxGroup type. Is there a way to get a Checkbox component out of a CheckboxGroup component?

I have tried to look up different type of methods on the CheckbocGroup class but I can get the Items back which are a Enum type. I need a class that is a child class of the Vaadin Component class. I was expecting something like:

CheckboxGroup<Enum> checkboxGroup = new CheckboxGroup();
checkboxGroup.setItems(Enum.values())

Checkbox checkbox = checkboxGroup.getCheckboxOfType(Enum.Type);
checkbox.setTooltipText("TEST");



Vue3: Controlling checkbox checked state by a component prop

This is the setup:

Parent component: Has a reactive Todo object with a checked state {checked: true and passes it to a Todo component.

Todo component: Accepts the Todo as a prop and binds the checked value to a checkbox. Upon toggling the checkbox, it emits an event to the parent, which then asynchronously updates the checked state of the Todo.

Parent:

<template>
  <Todo @update="handleUpdate" :todo="todo" />
</template>

<script setup>
import { reactive } from "vue";
import Todo from "./components/Todo.vue";

let todo = reactive({ checked: true });

let handleUpdate = (e) => {
  setTimeout(() => {
    // Always sets it to false for test purposes
    todo.checked = false;
  }, 1000);
};
</script>

Child:

<template>
  <input type="checkbox" v-model="checkboxProxy" />
</template>

<script setup>
const { computed, defineProps, defineEmits } = require("vue");

let props = defineProps(["todo"]);
let emit = defineEmits(["update"]);

let checkboxProxy = computed({
  get() {
    return props.todo.checked;
  },
  set(val) {
    emit("update", val);
  },
});
</script>

Question: I would expect the checkbox to get unchecked a second after it has been checked. But that doesn't happen. Why?

Codesandbox: https://codesandbox.io/s/crazy-snow-kdse27

I also tried this setup:

<input type="checkbox" :checked="todo.checked" @change="emit('update)" />

But it still not reflecting the todo state. I'm testing in Brave it that matters.




dimanche 18 décembre 2022

Oracle APEX looping through CheckBox Group elements

I need to make the function of inserting data into several tables at once in the ORACLE APEX App Builder. Interactive report displays information from the View collected from the tables "Book", "Autors_list", "Autor", where "Autors_list" is needed to reveal the many-to-many relationship between the author and the book.

So, on an automatically created form, when I click on the CREATE button, using a dynamic event, I try to add data to the "Book" and "Autors_list" tables.

The data I'm trying to add:

P15_ID_BOOK - book id - add to "Book" and to "Autors_list"

P15_BOOK_NAME - book name - add to "Book"

P15_AUTORS - authors - are represented using the Checkbox Group - I need to go through each of its elements and for each element add an entry to the "Autors_list" in the form (P15_BOOK_NAME, author id from P15_AUTORS)

P15_PUBLICATION_DATE - publication date - add to "Book"

P15_PRICE - book's price - add to "Book"

The CheckBox Group is set using the following List of Values

`

select "id_autor", (CONCAT(CONCAT(autor."Name", ' '),autor."Surname")) as "Autors" from "Autor" autor;

`

I wrote the following PL/SQL code to add the above values to the tables:

begin
insert into "Book"
("Name", "Publication_date", "Price")
values
(:P15_BOOK_NAME, :P15_PUBLICATION_DATE, :P15_PRICE);

FOR i IN (select * from table(apex_string.split(:P15_AUTORS, ',')))
LOOP
 insert into "Autors_list"
 values (:P15_ID_BOOK, i);
END LOOP;
end ;

However, it gives me an error

ORA-01008: not all variables bound

Please tell me how to cycle through the elements of the Checkbox Group correctly and get the values from there




samedi 17 décembre 2022

CheckboxGroupInput with Conditional panel for choices

I am trying to get an app in which user will choose from "Variables set no 1" and conditionally another set of variables will show up (e.g. if A and B chosen in set 1 then A1 in second set will show up) and if box ticked the input variables will show up. I have done it with checkboxGroupInput and then set of checkboxInput but would like to have the latter turn into another checkboxGroupInput for filtering. To do so the conditional panel (of if - else, although I tried it and its not working) needs to be allowed to create dynamically list of choices. Rudimentary version of the code is below.

library(shiny)

ui <- fluidPage(

  fluidRow(column(4, 
             checkboxGroupInput("variables", 
                                "Variables set 1",
                                choices  = c("A", "B", "C", "D"),
                                selected = NULL)), 

##########################################################
# How to change this section into checkboxGroupInput?????? 
##########################################################
           column(8,
             conditionalPanel(
               condition='input.variables.indexOf("A") > -1 &
                          input.variables.indexOf("B") > -1',
               checkboxInput(inputId = "a1", label = "A1", value = FALSE)),
             
             conditionalPanel(
               condition='input.variables.indexOf("B") > -1 &
                          input.variables.indexOf("D") > -1',
               checkboxInput(inputId = "a2", label = "A2", value = FALSE)),
             
             conditionalPanel(
               condition='input.variables.indexOf("B") > -1 &
                          input.variables.indexOf("C") > -1 &
                          input.variables.indexOf("D") > -1',
               checkboxInput(inputId = "a3", label = "A3", value = FALSE)))), 
########################################################## 


  fluidRow(column(6, 
      conditionalPanel(
        condition = "input.a1 == 1 || input.a2 == 1",
            radioButtons(inputId = "A11", 
                         label = "A blah",
                         choices = list("Bla" = 2, "Ble" = 3),
                         selected = 2)),

      conditionalPanel(
        condition = "input.a3 == 1",
            sliderInput(inputId = "B11", 
                        label = "B blah",
                        min = 1, max = 10, value = 5, step = 1)),
      conditionalPanel(
        condition = "input.a1 == 1 || input.a2 == 1 || input.a3 == 1",
            sliderInput(inputId = "C11", 
                        label = "C blah",
                        min = 1, max = 10, value = 5, step = 1))))
  
)

server <- function(input, output, session) {}

shinyApp(ui = ui, server = server)

Thank you in advance!




vendredi 16 décembre 2022

Check only a range of checkboxes

I have this code with works brilliantly for me. I just need a small alteration to be able to select a range of cells as well, meaning:

Either H15-H17 or H22 or H26 in the attached image.enter image description here

the code I have is the following:

var CHECKBOX_CELLS = ["H15", "H22", "H26"];

function onEdit(e) {
  var range = e.range;

  var checkboxIndex = CHECKBOX_CELLS.indexOf(range.getA1Notation());

  if (checkboxIndex > -1 && range.getValue() == true) {
    var sheet = range.getSheet();

    for (var i=0; i<CHECKBOX_CELLS.length; i++) {
      if (i==checkboxIndex) continue;

      sheet.getRange(CHECKBOX_CELLS[i]).setValue(false);
    }
  }
}




jeudi 15 décembre 2022

How can I filter and show an array with React?

I'm trying to filter some companies array -that is being shown in a table- using multiple checkboxes. These checkboxes returns an array of strings with some status. For example: ['accepted', 'pending', 'declined'];. The problem is that while the checkboxes returns the status OK, I cannot manage to filter the companies array with the checkboxes data.

Here is my main code:

function App() {

  const [filters, setFilters] = useState([]);
  const [companies, setCompanies] = useState([
    { id: 1, status: "accepted", name: "001", date: "01/01/2022" },
    { id: 2, status: "accepted", name: "001", date: "01/01/2022" },
    { id: 8, status: "accepted", name: "001", date: "10/04/2022" },
  ]);

  //HERE I TRY TO FILTER MY COMPANIES ARRAY WITH THE SELECTED CHECKBOXES
  const showFilteredCompanies = (filters) => {
    return [...companies].filter((company) => {
      return filters.includes(company.status);
    });
  }


  //Inside data I have my array of selected status like this: ['accepted', 'pending', 'declined']

  const handleFilters = (data) => {
    
    let newFilters = {...filters};
    newFilters = data;
    setFilters(newFilters);

    // THIS CONSOLE.LOG SHOWS THE FILTERED ARRAY OF COMPANIES JUST FINE
    console.log(showFilteredCompanies(newFilters));

    const filtered = showFilteredCompanies(newFilters);

    //BUT WHEN I TRY TO SAVE MY COMPANIES FILTERED ARRAY IN MY STATE THE FILTERING DOESN'T WORK AS IT SHOULD
    console.log(filtered);
    setCompanies(filtered);
  }

  return (
    <div className="App">

      <Checkbox 
        handleFilters={data => handleFilters(data)}
      />

      {/* companies list */}
      <div>
        {companies.length ? 
          (
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Estado</th>
                  <th>nombre</th>
                  <th>Fecha</th>
                </tr>
              </thead>
              <tbody>
                {companies.map((company, i) => (
                    <tr key={i}>
                      <td>{company.id}</td>
                      <td>{company.status}</td>
                      <td>{company.name}</td>
                      <td>{company.date}</td>
                    </tr>
                  )
                )}
              </tbody>
            </table>   
          ) : (
            <h2>No hay compañías para mostrar</h2>
          )
        }
      </div>

      {/* list length */}
      <div>
          <h3>Cantidad de compañías: {companies.length}</h3>
      </div>
    </div>
  );
}

export default App;

I was expecting to filter my companies array with all the strings of my checkboxes data array to show only the companies.status that matches the selected status of the checkboxes