lundi 31 juillet 2023

How to validate an user selection of multiple checkboxes on VB.net using a button?

everyone!

I'm learning VB.net language and I'm creating a simple app, which the user can select up to 5 numbers using checkboxes, and the button on windows form app will check if the user has marked up to 5 numbers. Otherwise, a dialog message will appear returning that user can only check up to 5 numbers, and the exceded choice is unchecked, keeping the 5 options checked. On some tests, I could do that setting the CheckBox1.CheckBoxChanged with the following code:

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged

Dim check As CheckBox = TryCast(sender, Object)
If check.Checked Then
    counter += 1
Else
    counter -= 1
End If
If counter > 5 Then
    MessageBox.Show("You can only pick up to 5 numbers!")
    check.Checked = False
End If

End Sub

On this way the program has worked perfectly. But it's failed when I've tried to implement on the button1.click. I even tried some another methods, like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

For Each check As CheckBox In Me.grpMega.Controls.OfType(Of CheckBox)()
    If check.Checked Then
        counter += 1
    Else
        counter -= 1
    End If
    If counter > 5 Then
        MessageBox.Show("You can only pick up to 5 numbers!")
        check.Checked = False
    End If
Next

End Sub

I've beend making some searches over the internet to find up a solution, but with no success. If anybody could help me, I'll be so grateful. Thanks so much for your attention. Any help is very welcome.




store selected checkbox value. where the checkbox is inside an accordion class.This value need to be calculated for every item of accordion

isChecked(name){
    let tempI = this.chekcbOxValueArray.findIndex((x)=> x == name)
    return tempI>=0 ?true :false;
}

selectedWorker(name, checked){
    if(checked == true){
        this.a.push(name)
    }
}

onClickOkay(){
    item.workerNamesSelected = a.toString()
}
<div class="accordion-content">

    <div *ngFor="let item of accordianFields; let i = index">

        <!-- This is 1st item of accordian (chekcbox input) -->
        <div>
            worker Names
            <ng-template #checkBoxPopup>
                <div *ngFor="let worker of workerdataList">

                    <input type="chekcbox" [checked]="isChecked(worker.name)"
                        (click)="selectedWorker(worker.name, $event.target.checked)"
                        [(ngModel)]="item.workerNamesSelected" />
                </div>
                <div>
                    <button (click)="onClickOkay"></button>
                </div>
            </ng-template>
            <span ngbPopover="checkBoxPopup"></span>

        </div>\


        <!-- 2nd item  -->
        <!-- nth -->

    </div>
</div>

I am unable to get value for each item of accordion. The value remains same for all the accordion item -worker name.

Expected result:

for 1st item : some selected worker

for second accordion item : some other selected worker




How checkbox multi datagridview from form2 to form1 di vb.net

How checkbox multi datagridview from form2 to form1 di vb.net ?

If I do with a single checkbox for each then the result is appropriate but if I do a multi checkbox at once then the result does not match as below screenshot is there anything wrong with my code .

Please Guide me

Thanks

CODE IN FORM1

Public Class Form1
    Private table1 As New DataTable
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        table1.Columns.Add(New DataColumn("Column1", GetType(String)))
        table1.Columns.Add(New DataColumn("Column2", GetType(String)))
        table1.Columns.Add(New DataColumn("Column3", GetType(String)))
        table1.Columns.Add(New DataColumn("Column4", GetType(String)))
        table1.Columns.Add(New DataColumn("Qty", GetType(Integer)))
        DataGridView1.DataSource = table1
    End Sub
  Private Sub BTNAdd_Click(sender As Object, e As EventArgs) Handles BTNAdd.Click
        Dim Column2 As String = TextBox2.Text.Trim()
        Dim Column1 = TextBox1.Text.Trim()
        Using frm = New Form2(Column2)

            If frm.ShowDialog() = DialogResult.OK Then
                Dim datarow As DataRow = Nothing
                Dim Column3 = frm.DataGridView1.CurrentRow.Cells(3).Value?.ToString()
                Dim Column4 = frm.DataGridView1.CurrentRow.Cells(4).Value?.ToString()
                If table1.Rows.Cast(Of DataRow).Any() Then
  datarow = table1.Select($"Column1 = '{Column1}' AND Column2 = '{Column2}' AND Column3 = '{Column3}' AND Column4 = '{Column4}'").FirstOrDefault()
                End If
                If datarow IsNot Nothing Then
                    Dim qty = If(datarow("Qty") Is Nothing, 0, datarow.Field(Of Integer)("Qty"))
                    datarow.SetField("Qty", qty + 1)
                    Return
                Else
                End If
                Try
                    For Each row2 As DataGridViewRow In frm.DataGridView1.Rows
                        Dim isselect As Boolean = Convert.ToBoolean(row2.Cells("checkboxcolumn").Value)
                        If isselect Then
                            table1.Rows.Add(Column1, Column2, Column3, Column4, 1)
                            TextBox1.Clear()
                            TextBox2.Clear()
                        End If
                    Next
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                End Try
            Else

                Return
            End If
        End Using
    End Sub
End Class

CODE IN FORM2

Public Class Form2
    Sub New()
        InitializeComponent()
    End Sub
    Public Function ConvertToList(Of T)(ByVal dt As DataTable) As List(Of T)
        Dim columnNames = dt.Columns.Cast(Of DataColumn)().Select(Function(c) c.ColumnName).ToList()
        Dim properties = GetType(T).GetProperties()
        Return dt.AsEnumerable().Select(Function(row)
                                            Dim objT = Activator.CreateInstance(Of T)()
                                            For Each pro In properties
                                                If columnNames.Contains(pro.Name) Then
                                                    Dim pI As PropertyInfo = objT.GetType().GetProperty(pro.Name)
                                                    pro.SetValue(objT, If(row(pro.Name) Is DBNull.Value, Nothing, Convert.ChangeType(row(pro.Name), pI.PropertyType)))
                                                End If
                                            Next pro
                                            Return objT
                                        End Function).ToList()
    End Function

    Public Sub New(Column2 As String)
        Me.New
        Dim table2 As New DataTable("Players")
        table2.Columns.Add(New DataColumn("Column1", GetType(String)))
        table2.Columns.Add(New DataColumn("Column2", GetType(String)))
        table2.Columns.Add(New DataColumn("Column3", GetType(String)))
        table2.Columns.Add(New DataColumn("Column4", GetType(String)))
        table2.Rows.Add("001", "TEST1", "TEST1", "TEST1")
        table2.Rows.Add("001", "TEST1", "TEST1", "")
        table2.Rows.Add("001", "TEST1", "", "")
        table2.Rows.Add("001", "TEST1", "", "TEST1")
        table2.Rows.Add("002", "TEST2", "", "TEST2")
        DataGridView1.DataSource = ConvertToList(Of Table2)(table2)
        Dim CheckedBoxColumn As New DataGridViewCheckBoxColumn
        CheckedBoxColumn.Width = 40
        CheckedBoxColumn.Name = "checkboxcolumn"
        CheckedBoxColumn.HeaderText = "Check"
        DataGridView1.Columns.Insert(0, CheckedBoxColumn)
    End Sub

    Private Sub BtnOK_Click(sender As Object, e As EventArgs) Handles BtnOK.Click
        DialogResult = DialogResult.OK
    End Sub
End Class
Public Class Table2

    Public Property Column1() As String
    Public Property Column2() As String
    Public Property Column3() As String
    Public Property Column4() As String

End Class

the result does not match

RESULT IN DATAGRIDVEW FORM1

DESIRED RESULT

Column1 Column2 Column3 Column4
001 TEST1 TEST1 TEST1
001 TEST1 TEST1
001 TEST1
001 TEST1 TEST1
002 TEST2 TEST2



dimanche 30 juillet 2023

Focus checkbox mdb5?

I used mdb 5 class: mdbCheckbox, It's creates a circle around the checkbox when I click on it (or the text next to it) and it leaves the circle around it until after I click on the screen to take the focus off. I want it to show the circle only at the moment of the mouse click

.name class:focus:hover { display: none !important; } This is the best case I could come up with but it's not good enough




How to use javascript or jquery to toggle select all checkbox to check if all are selected and uncheck if one of them is unchecked?

I want to use javascript or jquery to check the checkbox on accordian when below all of the input checkboxes are selected and uncheck it when one of the checkbox is deselected.

<div class="card w-100">
                            <div class="card-body">
                                <div class="mb-4">
                                    <h5 class="mb-0">Permissions</h5>
                                </div>
                                <div class="accordion accordion-flush" id="accordionFlushExample">
                                    <div class="accordion-item">
                                        <h2 class="accordion-header" id="flush-headingOne">
                                            <button class="accordion-button collapsed gap-3" type="button"
                                                data-bs-toggle="collapse" data-bs-target="#flush-collapseOne"
                                                aria-expanded="false" aria-controls="flush-collapseOne">
                                                <input class="form-check-input" type="checkbox" value=""
                                                    id="selectAllList1" onclick="toggleProjects(this)" />
                                                Projects
                                            </button>
                                        </h2>
                                        <div id="flush-collapseOne" class="accordion-collapse collapse"
                                            aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
                                            <ul class="list-group">
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" value=""
                                                            id="list1" name="projects" />
                                                        <label class="form-check-label" for="list1">
                                                            Add New Project
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" value=""
                                                            id="list2" name="projects" />
                                                        <label class="form-check-label" for="list2">
                                                            View Project
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" value=""
                                                            id="list3" name="projects" />
                                                        <label class="form-check-label" for="list3">
                                                            Edit Project
                                                        </label>
                                                    </div>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="accordion-item">
                                        <h2 class="accordion-header" id="flush-headingTwo">
                                            <button class="accordion-button collapsed gap-3" type="button"
                                                data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo"
                                                aria-expanded="false" aria-controls="flush-collapseTwo">
                                                <input class="form-check-input" type="checkbox" value=""
                                                    id="selectAllList2" onclick="toggleProjectCategory(this)" />
                                                Project Category
                                            </button>
                                        </h2>
                                        <div id="flush-collapseTwo" class="accordion-collapse collapse"
                                            aria-labelledby="flush-headingTwo"
                                            data-bs-parent="#accordionFlushExample">
                                            <ul class="list-group">
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list1" name="projectCategory" />
                                                        <label class="form-check-label" for="list1">
                                                            Add New Project Category
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list2" name="projectCategory" />
                                                        <label class="form-check-label" for="list2">
                                                            View Project Category
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list3" name="projectCategory" />
                                                        <label class="form-check-label" for="list3">
                                                            Edit Project Category
                                                        </label>
                                                    </div>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="accordion-item">
                                        <h2 class="accordion-header" id="flush-headingThree">
                                            <button class="accordion-button collapsed gap-3" type="button"
                                                data-bs-toggle="collapse" data-bs-target="#flush-collapseThree"
                                                aria-expanded="false" aria-controls="flush-collapseThree">
                                                <input class="form-check-input" type="checkbox" value=""
                                                    id="selectAllList3" onclick="toggleProjectType(this)" />
                                                Project Type
                                            </button>
                                        </h2>
                                        <div id="flush-collapseThree" class="accordion-collapse collapse"
                                            aria-labelledby="flush-headingThree"
                                            data-bs-parent="#accordionFlushExample">
                                            <ul class="list-group">
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list1" name="projectType" />
                                                        <label class="form-check-label" for="list1">
                                                            Add New Project Type
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list2" name="projectType" />
                                                        <label class="form-check-label" for="list2">
                                                            View Project Type
                                                        </label>
                                                    </div>
                                                </li>
                                                <li class="list-group-item">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            value="" id="list3" name="projectType" />
                                                        <label class="form-check-label" for="list3">
                                                            Edit Project Type
                                                        </label>
                                                    </div>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
<script>
            function toggleProjects(source) {
                var checkboxes = document.getElementsByName('projects');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].checked = source.checked;
                }

                // Check/uncheck the "Select All" checkbox based on the state of individual checkboxes
                var selectAllCheckbox = document.getElementById('selectAllList1');
                selectAllCheckbox.checked = Array.from(checkboxes).every(checkbox => checkbox.checked);
            }

            function toggleProjectCategory(source) {
                var checkboxes = document.getElementsByName('projectCategory');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].checked = source.checked;
                }
            }

            function toggleProjectType(source) {
                var checkboxes = document.getElementsByName('projectType');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].checked = source.checked;
                }
            }
        </script>

right now it select and deselect all but doesnt work when i uncheck one of the item the checkbox input on the accordian still remains the same.




vendredi 28 juillet 2023

Flutter Provider - Checkbox not getting checked

Below is my ViewModel class :

class SignInViewModel extends ChangeNotifier {
  var isRememberMeChecked = false;
  final TextEditingController emailC = TextEditingController();
  final TextEditingController passwordC = TextEditingController();

  Future<bool> signIn({
    required String email,
    required String password,
  }) async {
    /// Implement Api Call Here
    return true;
  }
}

You can see the class is extending ChangeNotifier & Please not the variable named isRememberMeChecked which is by default 'false'.

Now, In my Widget class, which is StateFulWidget, I am trying to change the value of CheckBox as below:

child: Checkbox(
          fillColor: theme.checkboxTheme.fillColor,
          value: widget.viewModel.isRememberMeChecked,
          onChanged: (bool? value) {
            widget.viewModel.isRememberMeChecked=value!;
          },
         ), 

You can notice this line:

widget.viewModel.isRememberMeChecked=value!;

EDIT:

I have also tried it with set as below:

widget.viewModel.setRememberMe = value

In ViewModel class :

set setRememberMe(bool value) {
    isRememberMeChecked = value;
    notifyListeners();
  }

But with this also Checkbox UI not getting checked to unchecked. Means the Checkbox UI is not reflecting for true or false values.

What might be the issue?




jeudi 27 juillet 2023

The argument Type 'Color' can't be assigned to the parameter type MaterialStateProperty

Hello I am trying to create a custom Checkbox widget to support dark and light themes in app. For that I am trying as below:

   static final CheckboxThemeData primaryLight =CheckboxThemeData(
    fillColor:AppColor.primary 
  );

But At the line AppColor.primary, its giving me compile time error as

"The argument Type 'Color' can't be assigned to the parameter type MaterialStateProperty<Color?>?"

What might be the issue? Or How can I resolve this to make the common custom Checkbox for two different themes?




mercredi 26 juillet 2023

Checkbox and Text not showing in same horizontal line inside WRAP widget in Flutter

I have created 'Rememnber Password' UI in my login screen with below code which is inside Row() widget :

                 Wrap(
                      alignment: WrapAlignment.center,
                      children: [
                        Checkbox(
                          checkColor: Colors.white,
                          value: isChecked,
                          onChanged: (bool? value) {
                            setState(() {
                              isChecked = value!;
                            });
                          },
                        ),
                        Text(
                          "remember_me",
                          style: theme.textTheme.bodySmall,
                        ).tr()
                      ],
                    ),

But the issue is Checkbox looks good in center, but the Text to the right side of the checkbox has some space below it and it looks little up and not vertically in center.

What might be the issue or how can I make the 'Remember Me' text vertically in center?




why JavaScript code i wrote is not working

Its my code in html :

subscribe
<label for="visaBtn">Visa</label>
<input type="radio" name ="card" id="visaBtn">
<label for="mastercardBtn">MasterCard</label>
<input type="radio" name="card" id="mastercardBtn">
<label for="paypalBtn">Paypal</label>
<input type="radio" name="card" id="paypalBtn"><br>
<button id="myCheckBox">submit</button>
<script src="index.js"></script>

body>

Then I wrote this function on JavaScript but when I am trying it on the browser it isn't working.

document.getElementById("myButton").onclick=function(){

const myCheckBox =document.getElementById("myCheckBox");
const visaBtn = document.getElementById("visaBtn");
const mastercardBtn = document.getElementById("mastercardBtn");
const paypalBtn = document.getElementById("paypalBtn");

if(myCheckBox.checked){
    console.log("You are subscribed");
}
else{
    console.log("You are NOT subscribed!");
}
 if(visaBtn.checked){
    console.log("You are paying with a Visa!");
 }
 else if(mastercardBtn.checked){
    console.log("You are paying with a Mastercard!");
 }
 else if(paypalBtn.checked){
    console.log("You are paying with a Paypal!");
 }
 else{
    console.log("You must select a payment type!");
 }

I want to know what's wrong with my code?




How to uncheck all checkboxes except those where value is 4 or 5 using jQuery?

How to uncheck all checkboxes except those where value is 4 or 5 using jQuery?

//My code which is working for value is equal to 4
onchange="$('#cf_1682897_div input[type=checkbox]:checked').each(function(){if($(this).val() == 4 || $(this).val() == 5){$('#cf_1682897_div input[type=checkbox][value!=4]').prop('checked', false);alert('Selecting N/A in combination with any other options is not permitted. All other checked options are unchecked.');}})"



mardi 25 juillet 2023

Multiple check box options

I am looking to have check boxes in a Word document that when clicked multiple times, the contents of the box will change from a check, to X, to star or other characters as I need. I have googled around and only can find how to change the check box from an X to a check, but nothing about multiple values.

Thanks, Larry.




lundi 24 juillet 2023

checkboxinput overlaid on the label

I am working with a form in django with crispy form and it has many fields, and the checkboxinput field does not render well in the html, it is overlapped in the label and very big. previously i was using another template style but when i changed the html, the checks were broken

form.py
class TestForm(forms.ModelForm):
    class Meta:
        model = Test

fields = [
            'test1',
            'test2'
         ]

        labels = {
            'test1':'Test 1',
            'test2':'Test 2',}

widgets = {
            'test1':forms.CheckboxInput(attrs={'class':'form-check-label'}),
            'test2':forms.CheckboxInput(attrs={'class':'form-check-label'}),
form.html
  <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2">
                             
  </div>
  <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2">
                            
  </div>

This is how the checkboxes and the labels look




Can someone make this Angular 16 checkbox input code more efficient and cleaner?

I have a simple boolean in my angular 16 ts component uploadEnabled. What I want is the checkbox to be checked if uploadEnabled is true and vice versa. When I click on the checkbox I want uploadEnabled to toggle accordingly with the state of the checkbox. I have a label element showing the current state of uploadEnabled.

The following code does what I want but it is clearly clumsy as I am using two input elements and *ngIf to either have the checked attribute present or absent. (I have removed class attributes for readability.)

      <form >
        <input type="checkbox" (click)="uploadEnabled = !uploadEnabled" *ngIf="!uploadEnabled" />
        <input type="checkbox" (click)="uploadEnabled = !uploadEnabled" *ngIf="uploadEnabled" checked />
        <label >Allow PHG to perform FHIR/PCD01 uploads:
          </label>
      </form>

The variant below does half the job. The checkbox will be checked or unchecked when first viewed depending upon the boolean, but clicking on the checkbox sets the checkbox to checked if not checked otherwise it just remains checked. The boolean value, however, toggles as desired:

        <input type="checkbox"
          (click)="uploadEnabled = !uploadEnabled" [checked] = "uploadEnabled" />
        <label >Allow PHG to perform FHIR/PCD01 uploads:
          </label>

I have tried other variants with '[(ngModel)]' and '(change)' but either I have gotten compile errors (I am using Angular 16 with strict mode) or I could not get consistency between the check box state and the variable. In the end all I am trying to do it eliminate the checked attribute when uploadEnabled is false and to have it present when uploadEnabled is true.




vendredi 21 juillet 2023

How/can you style the background color of an un-checked checkbox/ (radio?) button with CSS?

With the accent-color https://developer.mozilla.org/en-US/docs/Web/CSS/accent-color (in all browsers except IE) we can change the color of the fill of the checkbox element when checked, however it isn't obvious if it is possible to style the background color when un-checked.

The default 'white' color is fine in most cases, but in trying to support a dark mode theme, without the OS being set to dark mode... setting this background color seem elusive.

Have tried various versions of setting the background-color, with transparent, !important etc. with no luck. Is there a magic setting/trick for this (without resorting to custom elements instead of the default HTML checkbox/radio)?

*{
  font-family:sans-serif;
}
label{
  cursor:pointer;
  user-select:none;
}
input[type="checkbox"]{
  accent-color:purple;
}
input[type="raido"]{
  accent-color:red;
}
<label><input type="checkbox"/> Unchecked</label><br/>
<label><input type="checkbox" checked="checked"/> Checked</label><br/>
<label><input type="checkbox" disabled="disabled"/> Disabled</label><br/>

<hr/>

<label><input type="radio" name="related"/> Unchecked A</label><br/>
<label><input type="radio" name="related"/> Unchecked B</label><br/>
<label><input type="radio" name="related"/> Unchecked C</label><br/>
<label><input type="radio" name="related" checked="checked"/> Checked D</label><br/>
<label><input type="radio" name="related" disabled="disabled"/> Disabled</label><br/>

accent-color on caniuse.com: https://caniuse.com/mdn-css_properties_accent-color




jeudi 20 juillet 2023

How to unmark checkbox input while editing

im on a Laravel/Nextjs project.

Im retrieving data so the user can edit if he wish.

After several tries, i've managed to show the data on the form, and i can edit the input name, and select different degrees.

The problem is with the checkbox input, when i try to deselect it does it in order and not by the one i've clicked on it. + I can't select more than 1 checkbox.

I will show you the component, the form component and the data i get from the backend.

Any information would help me a lot. Thanks !

"use client";
import { useEffect, useState } from "react";
import axios from "axios";
import { useSnackbar } from "notistack";
import { useParams, useRouter } from "next/navigation";
import Form from "@/app/form";
import Header from "@/app/Admin/header";

export default function EditYear() {
  const { enqueueSnackbar } = useSnackbar();
  const router = useRouter();
  const { id } = useParams();

  const backendURL = process.env.NEXT_PUBLIC_BACKEND_URL;
  const token =
    typeof window !== "undefined" ? localStorage.getItem("auth_token") : null;
  const type =
    typeof window !== "undefined" ? localStorage.getItem("type") : null;

  const [yearData, setYearData] = useState({});
  const [degrees, setDegrees] = useState([]);
  const [selectedDegree, setSelectedDegree] = useState("");
  const [selectedSubjects, setSelectedSubjects] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(
          `${backendURL}/api/year/edit/${id}`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
              "X-Type": type,
            },
          }
        );

        if (response.status === 200) {
          const data = response.data;
          setYearData(data.year_data);
          setDegrees(data.degrees);
          setSelectedDegree(data.year_data.degree_id);
          setSelectedSubjects(data.year_data.subjects.map((subject) => subject.id));
        } else {
          console.error("Error: Unable to fetch data");
        }
      } catch (error) {
        console.error("Error: ", error.message);
      }
    };

    fetchData();
  }, []);

  const handleFormSubmit = async (e) => {
    e.preventDefault();
    // Your form submission logic here
  };

  const handleInputChange = (e) => {
    // Update the form field value based on the input name
    const { name, value } = e.target;
    setYearData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleDegreeChange = (e) => {
    // Update the selected degree value
    const selectedDegreeId = parseInt(e.target.value);
    setSelectedDegree(selectedDegreeId);
    // Filter and update the selected subjects based on the selected degree
    const selectedDegree = degrees.find((degree) => degree.id === selectedDegreeId);
    setSelectedSubjects(selectedDegree ? selectedDegree.subjects.map((subject) => subject.id) : []);
  };

  const handleSubjectChange = (e) => {
    // Update the selected subjects array
    const selectedSubjectId = parseInt(e.target.value);
    setSelectedSubjects((prevSubjects) =>
      prevSubjects.includes(selectedSubjectId)
        ? prevSubjects.filter((id) => id !== selectedSubjectId)
        : [...prevSubjects, selectedSubjectId]
    );
  };
  

  const fields = [
    {
      label: "Name",
      type: "text",
      name: "year_name",
      value: yearData.year_name || "",
      onChange: handleInputChange,
    },
    {
      label: "Degree",
      type: "select",
      name: "degree_id",
      value: selectedDegree,
      options: degrees.map((degree) => ({
        label: degree.name,
        value: degree.id,
      })),
      onChange: handleDegreeChange,
    },
    {
      label: "Subjects",
      type: "checkbox",
      name: "subjects",
      options: degrees
        .find((degree) => degree.id === selectedDegree)
        ?.subjects.map((subject) => ({
          label: subject.name,
          value: subject.id,
        })) || [],
      value: selectedSubjects,
      onChange: handleSubjectChange,
    },

  ];

  return (
    <>
      <Header title="Create Year" />

      <Form
        onSubmit={handleFormSubmit}
        fields={fields}
        type="Create Year"
        send="Add a Year"
      />
    </>
  );
}

Here is the form.

export default function Form({ onSubmit, fields, type, send, initialValue }) {
  const handleCheckboxChange = (e, field) => {
    const { value, checked } = e.target;
    field.onChange({
      target: {
        name: field.name,
        value: checked
          ? [...field.value, value]
          : field.value.filter((item) => item !== value),
      },
    });
  };

  return (
    <div className="flex flex-col w-4/5 h-auto p-4 mx-auto my-0 lg:shadow-none gap-y-4 lg:w-2/3">
      <div className="text-lg font-semibold uppercase lg:text-xl">
        <h1>{type}</h1>
      </div>

      <form className="flex flex-col lg:gap-y-4 gap-y-6" onSubmit={onSubmit}>
        {fields.map((field) => (
          <div key={field.name} className="flex flex-col gap-y-2">
            <label className="text-sm lg:text-base">{field.label}</label>
            {field.type === "checkbox" ? (
              field.options.map((option) => (
                <div key={option.value} className="flex items-center">
                  <input
                    className="mr-2"
                    type="checkbox"
                    name={field.name}
                    value={option.value}
                    checked={field.value.includes(option.value)}
                    onChange={(e) => handleCheckboxChange(e, field)}
                  />
                  <label>{option.label}</label>
                </div>
              ))
            ) : field.type === "select" ? (
              <select
                className="h-8 pl-4 border-2 border-gray-500 border-solid rounded-md outline-none focus:border-verde lg:h-12"
                name={field.name}
                value={field.value}
                onChange={field.onChange}
              >
                <option value="">{initialValue}</option>
                {field.options.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            ) : (
              <input
                className="h-8 pl-4 border-2 border-gray-500 border-solid rounded-md outline-none focus:border-verde lg:h-12"
                placeholder={field.placeholder}
                type={field.type}
                name={field.name}
                value={field.value}
                onChange={field.onChange}
              />
            )}
          </div>
        ))}

        <button
          type="submit"
          className="flex items-center justify-center w-1/2 h-10 mx-auto my-0 text-sm font-medium text-white transition-colors duration-300 rounded-lg lg:w-1/4 bg-verde hover:bg-green-500 focus:outline-none focus:ring-2 focus:ring-green-500 active:bg-green-700"
        >
          {send}
        </button>
      </form>
    </div>
  );
}

And the data in json.

{
    "year_data": {
        "year_id": 2,
        "year_name": "Medicina-2",
        "degree_id": 1,
        "degree_name": "Medicinal",
        "subjects": []
    },
    "degrees": [
        {
            "id": 1,
            "branch_id": 1,
            "name": "Medicinal",
            "created_at": "2023-06-25T16:43:51.000000Z",
            "updated_at": "2023-07-10T09:28:42.000000Z",
            "subjects": [
                {
                    "id": 6,
                    "degree_id": 1,
                    "name": "Aniouno",
                    "created_at": "2023-07-20T22:06:08.000000Z",
                    "updated_at": "2023-07-20T22:06:08.000000Z"
                },
                {
                    "id": 7,
                    "degree_id": 1,
                    "name": "anio2",
                    "created_at": "2023-07-20T22:06:08.000000Z",
                    "updated_at": "2023-07-20T22:06:08.000000Z"
                },
                {
                    "id": 8,
                    "degree_id": 1,
                    "name": "mok",
                    "created_at": "2023-07-20T22:06:08.000000Z",
                    "updated_at": "2023-07-20T22:06:08.000000Z"
                },
                {
                    "id": 9,
                    "degree_id": 1,
                    "name": "bok",
                    "created_at": "2023-07-20T22:06:08.000000Z",
                    "updated_at": "2023-07-20T22:06:08.000000Z"
                }
            ]
        },
        {
            "id": 8,
            "branch_id": 1,
            "name": "Anatomias",
            "created_at": "2023-07-10T05:52:52.000000Z",
            "updated_at": "2023-07-10T05:52:52.000000Z",
            "subjects": [
                {
                    "id": 2,
                    "degree_id": 8,
                    "name": "Dentistas",
                    "created_at": "2023-06-25T16:50:45.000000Z",
                    "updated_at": "2023-07-11T11:04:44.000000Z"
                }
            ]
        },
        {
            "id": 9,
            "branch_id": 1,
            "name": "Aeroplanes",
            "created_at": "2023-07-10T05:52:52.000000Z",
            "updated_at": "2023-07-10T05:52:52.000000Z",
            "subjects": []
        },
        {
            "id": 10,
            "branch_id": 1,
            "name": "Arquitectura",
            "created_at": "2023-07-10T05:52:52.000000Z",
            "updated_at": "2023-07-10T05:52:52.000000Z",
            "subjects": [
                {
                    "id": 4,
                    "degree_id": 10,
                    "name": "Ahorasi",
                    "created_at": "2023-06-25T16:50:45.000000Z",
                    "updated_at": "2023-07-11T11:04:32.000000Z"
                }
            ]
        }
    ]
}



Kendo React TreeView CheckBox not working

Checking CheckBox inside TreeView is not working.

enter image description here

This is the code. Treeview with CheckBox nodes inside expansion panel.

<ExpansionPanel
          className='item-body-dropDownList'
          title={"Expension panel"}
          expanded={expanded === item.id}
          tabIndex={0}
          key={item.id}
          onAction={(event) => {
            setExpanded(event.expanded ? "" : item.id);
          }}
        >
          <Reveal>
            {expanded === item.id && (
              <ExpansionPanelContent>
                <TreeView
                data={processTreeViewItems(tree, {
                  check: check,
                })}
                checkboxes={true}
                onCheckChange={onCheckChange}
              />
              </ExpansionPanelContent>
            )}
          </Reveal>
        </ExpansionPanel>

Tree data

const tree = [
    
    {
      text: "Item1",
    },
    {
      text: "Item2",
    },
  ];

I tried to implement TreeView from this web cite https://www.telerik.com/kendo-react-ui/components/treeview/checkboxes/ but its not working.

Any help please?




How to uncheck all checkboxes in a single click?

I have made this program in javascript for select checkboxes using shift key? Now I want to deselct it by single click?

HTML

<div class="inbox">
      <div class="item">
        <input type="checkbox" />
        <p>This is an inbox layout.</p>
      </div>
      <div class="item">
        <input type="checkbox" />
        <p>Check one item</p>
      </div>
      <div class="item">
        <input type="checkbox" />
        <p>Hold down your Shift key</p>
      </div>
      <div class="item">
        <input type="checkbox" />
        <p>Check a lower item</p>
      </div>
      <div class="item">
        <input type="checkbox" />
        <p>Everything in between should also be set to checked</p>
      </div>
      <div class="item">
        <input type="checkbox" />
        <p>Try do it without any libraries</p>
      </div>
    </div>

javascript for select the checkbox

 const checkboxes = document.querySelectorAll(
        '.inbox input[type="checkbox"]'
      );

      let lastChecked;

      function handleCheck(e) {
        //for selecting the checkboxes
        let inBetween = false;
        // Check if they had the shift key down
        // AND check that they are checking it
        
        if (e.shiftKey && this.checked) {
          // go ahead and do what we please
          // loop over every single checkbox
          checkboxes.forEach(checkbox => {
            console.log(checkbox);
            if (checkbox === this || checkbox === lastChecked) {
              inBetween = !inBetween;
              console.log('Starting to check them in between!');
            }

            if (inBetween) {
              checkbox.checked = true;
            }
          });
        }

        lastChecked = this;
      }

      checkboxes.forEach(checkbox =>
        checkbox.addEventListener('click', handleCheck)
      );

Now I want after selecting with shift key when I click on a selected checkbox then the selected checkboxes which comes after that should be unchecked in a single click?




mercredi 19 juillet 2023

Angular (change) fires twice on checkbox

I have a parent + child components to pick tags from a checkbox list

ngFor does not work because a change event is attributed to this.tagList

the (change) is firing twice: one with the checkbox component, one with the change event

screenshot with console.log at checkbox click

enter image description here

I wanted the parent this.tagList populated with the tagList from (change)="onChange($event)" in child component

parent component

tagList: string[] = [];

 onTagChange(event: string[]) {

    this.error = '';

    this.tagList = event;

    console.log(event);

  }
<p>
        <span><button class="link" (click)="onPreviousClicked(3)">Back</button></span>
        &nbsp;<span><button class="link" (click)="onNextClicked(5)">Next</button></span>
    </p>

child component

@Output()
  change: EventEmitter<string[]> = new EventEmitter<string[]>();

  @Output()
  previous: EventEmitter<any> = new EventEmitter();

  @Output()
  next: EventEmitter<any> = new EventEmitter();

  tagList: string[] = [];

  tagListForm!: FormGroup;

  onChange(event: any) {

    const selectedTags = this.tagListForm.controls['tagList'] as FormArray;

    if (event.target.checked) {

      selectedTags.push(new FormControl(event.target.value));

    } else {

      const index = selectedTags.controls.findIndex(x => x.value === event.target.value);

      selectedTags.removeAt(index);

    }

    this.change.emit(this.tagListForm.value.tagList);

  }

  ngOnInit() {

    this.tagList = ['pix', 'nubank', 'uber', '99', 'super'];

    this.tagListForm = this.formBuilder.group({

      tagList: new FormArray([])

    });

  }
<form [formGroup]="tagListForm">

    <div *ngFor="let tag of tagList">

        <input [id]="tag" type="checkbox" formArrayName="tagList" [value]="tag" (change)="onChange($event)">
        <label [for]="tag"></label>

    </div>

</form>



Python - Printing Black Squares to Complete Lottery Ticket

I am asking where to get started. Using Python, I would like to load my printer with a blank PowerBall lottery ticket and have it blacken in my selected numbers that I selected.

I would need to supply the coordinates of the checkboxes and the size of the checkboxes to whatever code I create. I'll read up on how to connect to a printer.

I know how to get data from an MS Access table or an Excel spreadsheet. I don't know how to take the data and transform it into printing a small black square on a very specific location on a form.

In short, I need to understand how to print many small black squares in very specific locations on a form.

Can anyone get me started by pointing me to some helpful documentation?

Thank you for your assistance,

Tom Huff




mardi 18 juillet 2023

Excel Macro Enabled Worksheet - How to clear grouped checkboxes in a specific row and column without clearing all checkboxes in worksheet?

Current Issue: I need help understanding how I can clear a specific row and columns in that row, that contain grouped form control checkboxes. I want to be able to clear those checkboxes so that a user sees a copy of the row above, but all the inputs/text are cleared to let them add a new entry in the row - see below for more detail...

Please Note: I've looked online at a number of different bits of code that kind of do something similar, but most seem to uncheck all the checkboxes on a worksheet and I don't have the coding knowledge to write/repurpose that code to suit what I need.

I repurposed someone elses code I found here.

How the code is currently working: The below code is tied to the button 'Add a New Row', when this button is clicked it presents a user prompt asking the user to enter the row number of the new row to add - example of user entering a new row number, to copy row 14 down into row 15

In the newly copied row, columns A, B and D are cleared of text - ready for a user to add a new entry, which is currently working well: showing new row copied from row 14 into row 15 and clearing columns A, B and D

I also want columns C and E in this new row to have all the checkboxes cleared...they are currently just being copied from row 14 down as is with the checkboxes ticked that are selected in row 14. These checkboxes are grouped, e.g. column C checkboxes grouped as one group, column E checkboxes grouped as another group.

Is there a way I can target a specific row/column and clear the checkboxes, and do this without clearing all the checkboxes in other rows?

Important:

  1. I want to try and add this to the code I already have under the Add a New Row button code below.

  2. Row 14 is already populated (as this will be a template), so the user should add from row 15 onward. This may not be the case in other worksheets, so hopefully I can just update the row that I want to use as the template row in other worksheets.

  3. Ideally, if there was a way to update my code to throw an error if a user tries to copy rows 14 or above, that would be better. Currently, if a user selects row 14, it copies my headings row and inserts this again, which I don't want to happen:

showing headings copied again if the user tries to copy row 14

Add a New Row Button code:

Private Sub CommandButton1_Click()

    Dim rowNum As Long
    On Error Resume Next
    rowNum = Application.InputBox(Prompt:="Enter Row Number of New Row to Add:", _
        Title:="Add New Row", Type:=1)
    Rows(rowNum).Insert Shift:=xlDown
    If Err.Number > 0 Then GoTo errH
    
    Range("A" & rowNum - 1).Resize(, 1).Copy Range("A" & rowNum)
    Range("B" & rowNum - 1).Resize(, 1).Copy Range("B" & rowNum)
    Range("C" & rowNum - 1).Resize(, 1).Copy Range("C" & rowNum)
    Range("D" & rowNum - 1).Resize(, 1).Copy Range("D" & rowNum)
    Range("E" & rowNum - 1).Resize(, 1).Copy Range("E" & rowNum)
    Range("F" & rowNum - 1).Resize(, 1).Copy Range("F" & rowNum)
        
    Range("A" & rowNum - 0).ClearContents
    Range("B" & rowNum - 0).ClearContents
    Range("D" & rowNum - 0).ClearContents

errH:
End Sub

Any help would be greatly appreciated. Thanks

ClearContents doesn't work to target the form control checkboxes, and Clear removes the underlying formatting of a column/row, which I don't want.

I had a look online but kept getting confused with how other's code was working.




lundi 17 juillet 2023

Update database table row value when an checkbox is checked in the gridview

I have a asp.net gridview page and I've added checkbox column to it. I am using JavaScript to select multiple checkboxes at once if the row values are similar. Now I want to update my database row value to '1' when I select the checkbox in the gridview. Can you please help me to write the logic?

I tired few logics but it is not working and I am getting error

$(document).ready(function() {
  // Function to handle checkbox click event 
  function handleCheckboxClick() {
    var invNumber = $(this).val();
    var isChecked = $(this).prop('checked');
    var checkboxes = $('input[type="checkbox"][value="' + invNumber + '"]');
    checkboxes.prop('checked', isChecked);
  }
  // Function to handle "Select All" checkbox click event 
  function handleSelectAllClick() {
    var isChecked = $(this).prop('checked');
    $('input[type="checkbox"][name="invoice"]').prop('checked', isChecked);
  }
  // Attach event handlers to checkboxes 
  $(document).on('click', 'input[type="checkbox"][name="inv"]', handleCheckboxClick);
  $(document).on('click', 'input[type="checkbox"][name="selectAll"]', handleSelectAllClick);
});



dimanche 16 juillet 2023

JS Change style attributes in databable-checkbox

I use datatable to display data send by JSON. true/false information is displayed by checkbox using the render function:

'render': function(data, type, full, meta) {
    
    var checkbox = $("<input/>", {"type": "checkbox" }, {"color": "red"} );
    
    if (data == "1") {
        checkbox.attr("checked", "checked");
        // checkbox.addClass("checkbox_checked");
                                
    } else {
        checkbox.removeAttr("checked");
        // checkbox.addClass("checkbox_unchecked");                         
    }
    
    return checkbox.prop("outerHTML")

}

So, due to only display the data and not change, I set attr to disabled. Doing so, the checkbox is greyed out, and not very visible. So I'm looking for an solution to change the color of the checkbox to red/green for more visibility.

But I cant find a solution to change the style attributes. If I remove the 'disabled' attr the checkbox is displayed with blue background and white hook. But now, the user is able to change it.

Please provide a hint for the best solution

  • overwrite the style (color) for disabled checkboxes
  • other idea to display the checkbox more significant



samedi 15 juillet 2023

JQuery Deselect Checkbox once greater than max limit

So we have a group of checkboxes. There is a max limit of 3 that can be selected which is great. This is for a product designer I am working on so I can make custom orders for people. I have noticed when testing that people get frustrated when they want to go and click another checkbox but since the three have been picked they have to go back and uncheck a checkbox before making another selection. Its not the biggest deal but I would like for that flow to not be broken.

Here is a quick example of some checkboxes and a jquery max limit.

$('input[type=checkbox]').change(function(e) {
  if ($('input[type=checkbox]:checked').length > 3) {
    $(this).prop('checked', false)
    alert("allowed only 3");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="pricing-levels-3">
  <p><strong>(Select 3 Checkboxes)</strong></p>
  <input class="single-checkbox" type="checkbox">1<br>
  <input class="single-checkbox" type="checkbox">2<br>
  <input class="single-checkbox" type="checkbox">3<br>
  <input class="single-checkbox" type="checkbox">4<br>
  <input class="single-checkbox" type="checkbox">5<br>
</div>

Would I need to make an array that logs each chosen checkbox so when we go over our max, say over three into the fourth choice it unchecks the checkbox at the bottom of the array and then unloads it before loading the next one in?

In some other words, I sort of want this to work like a radio button but with the advantages of checkboxes where the user can check and uncheck multiple options but if they go over it just unloads one of their previous choices.

Any suggestions or examples would be greatly appreciated. I have only been able to find examples of limiting the amount of checkboxes that can be selected. Nothing for this particular case.




jeudi 13 juillet 2023

Deleting selected rows with checkboxes not working properly when deselecting some rows after selecting all

I am working on a web application that allows the user to select multiple rows using checkboxes and delete them using an AJAX call. The code works fine when I select all checkboxes and delete them, but if I select all checkboxes and then deselect some before deletion, it does not delete any of the rows It just gives a success message. The issue seems to be with the way the code is handling deselected rows after selecting all checkboxes.

function delete() {
    deleteClicked = true;

    event.preventDefault();
    $("#eMsg").html("");
    $("#sMsg").html("");

    $("#dDS").val("");

    if (!validateSelection()) {
        $("eMsg").html("Please select at least one checkbox");
        return false;
    }

    let agree = confirm("Are you sure");
    if (agree) {
        let pkS = "";
        let lpS = "";
        let cBox = document.getElementsByName("ListofChkBox");
        let rL = cBox.length;
        for (let i = 0; i < rL; i++) {
            if (cBox[i].checked) {
                pkS = pkS + ":" + document.getElementById("lItem[" + i + "].lePk").value;
                lpS = lpS + ":" + document.getElementById("lItem[" + i + "].luPk").value;
            }
        }
        $("#dDS").val(pkS);
        $("#dLS").val(lpS);

        document.getElementById("dLS").value = lpS;
        let url = `e/l`;

        let fdata = {};
        $("#lFB").serializeArray().map(function(x) {
            fdata[x.name] = x.value;
        });
        fdata.lid = $("#lPK").val().split("=")[0];
        fdata.cPk = $("#cPk").val().split("=")[0];
        fdata.lDlist = cGlobal;
        fdata.dDS = $("#dDS").val();
        fdata.dLS = $("#dLS").val();

        
        $.ajax({
            type: "DELETE",
            url: dataurl,
            data: JSON.stringify(fdata),
            contentType: 'application/json;charset=UTF-8',
            success: () => {
                populateTable();
                $("#all")[0].checked = false;

                $("#sMsg").html("Success");
            },
            error: function(jqXHR, response) {
                if (!vB(jqXHR, event)) {
                    return false;
                } else {
                    $("eMsg").html("Failed");
                }
            },
        });
        return false;
    }
}



Angular 15 mat-checkbox, use own logic to check

I am using Angular 15 and also with it the Material Components. I wanted to use the material checkbox and implement my own function (the click function) where I set the checkItem.start to true/false and where I would expect that the checkbox should be getting checked or unchecked, depending on my flag value. I don't want to use the two-way binding, as it updates my values automatically when checking the checkbox, which I want to change inside in my click function myself and update it.

The problem is my checkbox will always get checked before I even enter the function in my "click" property and even if my flag is getting updated with another value, the component is not getting updated. I also tried to use the ChangeDetectorRef.detectChanges() function for the updating, but unfortunately it is not working.

It's also important to mention that I am using customized provider, which looks like this:

providers: [
      { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: {} as MatCheckboxDefaultOptions }
   ]

The HTML for then Angular Component:

<mat-checkbox
        [disabled]="isReadOnly(checkItem) || checkItem.finished"
        [checked]="checkItem.start"
        (click)="doCheck(checkItem, $event)"
</mat-checkbox>

Am I maybe using the wrong component properties?




mercredi 12 juillet 2023

Checked all checkbox when header cell is clicked

I need for all checkbox to be checked or unchecked when either checkbox in header or the checkbox header cell is clicked. My checkbox right now is inverted when header cell is clicked.

$('td').click(function(event) {

  if (!$(event.target).is('input')) {

    $('input:checkbox', this).prop('checked', function(i, value) {

      console.log('i', i)
      console.log('value', value)
      console.log('this', this)

      $(':checkbox').prop('checked', this.checked); // disable this line for working checkedbox when cell is clicked.
      //$(':checkbox[class="check_all"]').prop("checked", $(this).prop("checked"));

      return !value;
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>Header. Nothing should happen when clicking a cell in this column</td>
    <td><input id="header" type="checkbox" /></td>
  </tr>
  <tr>
    <td>Row 1</td>
    <td><input class="check_all" type="checkbox" /></td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td><input class="check_all" type="checkbox" /></td>
  </tr>
</table>

jsFiddle : https://jsfiddle.net/3vn51hor/

Please assist me. Thanks in advance.




mardi 11 juillet 2023

How to uncheck checkbox in angular on button click

I have three check boxes (parent 1, parent 2, parent 3) and in those three two by default checked (parent 1, parent 3)and one unchecked (parent 2) and when I checked the unchecked checkbox (parent 2) and click on clear button only those by default check boxes are unchecking(parent 1, parent 3) other one is remaining checked. here is the code :

         <li *ngFor="let child of nestedjson; let i = index">
            <input type="checkbox" [checked]="child.checked">
             
         </li>

        <div><button (click)="clear()" type="submit">clear</button></div> 

in ts

  nestedjson = [
             { name: 'parent1', value: ['child11', 'child12'], checked: true },
             { name: 'parent2', value: ['child2'], checked: false },
             { name: 'parent3', value: ['child3'], checked: true },
               ];
                      
    clear() {
          this.nestedjson.forEach((child) => {
              child.checked = false;
                });
             }



lundi 10 juillet 2023

Bootstrap table cell element not detecting event BootstrapTable from "react-bootstrap-table-next"

I have react bootsTrap table for displaying cafe/accessory/kitchen items. In the first column of each row, i have checkbox to select that item and tranfer that item to another bootstrap table. now the problem is that the onClick event on the checkbox element, only detects the boolean change in checkbox state for the first click. then from second click there is no console.log in the browser console and neither does the item adds again to the new table. I think the onClick is not getting detected after the first time, but i cant figure out why? and how to solve this issue.

CODE:


 const [checkboxState, setCheckboxState] = useState(false);

useEffect(() => {

    if (selectedRow) {
      console.log(selectedRow, "selected row")

      // console.log(checkboxState,"checkbox state")

      let isPresentFlag = false;
      let isPresent = selectedItems.filter((item) => item._id === selectedRow._id);
      isPresent.length > 0 ? isPresentFlag = true : isPresentFlag = false;

      if (isPresentFlag) {

        let newPayload = selectedItems.filter((item) => isPresent._id !== item._id)

        setSelectedItems(newPayload);
      } else {

        setSelectedItems([...selectedItems, selectedRow])
      }

    } else {

      function getAllSuppliers(token) {

        axios.post(`url`, {}, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }).then(res => { setAllSuppliers(res.data.data) }).catch(err => console.log(err))


      }
      getAllSuppliers(userToken);

    }

   
  }, [selectedRow])

 // function to select the row/rows with checkbox
  function checkboxFormatter(cell, row) {
   
    return (

      <FormGroup check>

        <Label check>
          <Input
            // id="checkbox1"
            // ref={checkboxRef}
            style=
            type="checkbox"
            onClick={() => { setSelectedRow(row); setCheckboxState(!checkboxState) }}
          />

        </Label>
      </FormGroup>
    )
  }

//bootstrap table columns definition:

const columnsAccessoryItems = [

    {
      dataField: "_id",
      hidden: true
    },
    {
      text: props.t(""),
      dataField: "checkbox",
      formatter: checkboxFormatter,
      sort: true,
      headerStyle: (colum, colIndex) => {
        return { width: "2%" }
      },
    },
    {
      text: props.t("#"),
      formatter: (cell, row, rowIndex) => {
        return rowIndex + 1
      },
      // dataField: "_id",
      sort: true,
      headerStyle: (colum, colIndex) => {
        return { width: "2%" }
      },
    },
    {
      text: props.t("Item id"),
      //formatter: employeeFormatter,
      dataField: "_id",
      sort: true,
      hidden: true,
      headerStyle: (colum, colIndex) => {
        return { width: "8%" }
      },
    },
    {
      text: props.t("Image"),
      formatter: (cell, row) => {
        return (
          <img className="avatar-md rounded-circle img-thumbnail" src={row.image_url} alt={row.name + "image"} />
        )
      },
      // dataField: "image_url",
      sort: true,
      headerStyle: (colum, colIndex) => {
        return { width: "8%" }
      },
    },
    {
      text: props.t("Item"),
      //formatter: employeeFormatter,
      dataField: "name",
      sort: true,
      headerStyle: (colum, colIndex) => {
        return { width: "8%" }
      },
    },
    {
      text: props.t("Available QTY"),
      formatter: (cell, row) => {
        return (
          <p>{`0 ${row.unit} ${row.sub_unit ? 0 : ""} ${row.sub_unit || ""}`}</p>
        )
      },
      dataField: "formula",
      sort: true,
      headerStyle: (colum, colIndex) => {
        return { width: "8%" }
      },
    },

  ]



Dynamic checkboxGroupInput In R Shiny

I am trying to create 2 checkbox input group based on the user input, so that I can run a logic to plot it against each other. Now Ideally IF the user selects 2 options in group 1 it shouldn't appear in group 2 of the checkboxgroup. How do I implement this?

The Column names, when created by user is appearing properly in the checkbox group as expected, but it is not being dynamic. That is when One option is selected it is not disappearing from the second group

enter image description here

So when 2 options are selected in the first group, It should disappear from the second option

Providing the UI part

 uiOutput("ui_costs_choices"),
 uiOutput("ui_benefits_choices")

Providing the server part

#Defining the ui_costs_choices
  output$ui_costs_choices <- renderUI({
    req(rv$df)
    checkboxGroupInput("Costs", "Select the cost criteria:", choices = names(rv$df))
  })
  #Defining the ui_benefits_choices
  output$ui_benefits_choices <- renderUI({
    req(rv$df)
    checkboxGroupInput("Benefits", "Select the Benefits criteria:", choices = names(rv$df))
  })
  observeEvent(input$Costs, {
    req(rv$df)
    # Get the names of the columns in rv$df
    all_choices <- names(rv$df)
    # Remove the ones that are already selected as costs
    benefit_choices <- setdiff(all_choices, input$costs)
    # Update the benefit checkboxGroupInput with the remaining choices
    updateCheckboxGroupInput(session, "Benefits", choices = benefit_choices)
  })
  observeEvent(input$Benefits, {
    req(rv$df)
    # Get the names of the columns in rv$df
    all_choices <- names(rv$df)
    # Remove the ones that are already selected as benefits
    cost_choices <- setdiff(all_choices, input$benefits)
    # Update the cost checkboxGroupInput with the remaining choices
    updateCheckboxGroupInput(session, "Costs", choices = cost_choices)
  })

rv is a reactive object which contains the user entered values in the table in rv$df




problem save with checkboxes on devise registration user

Screenshot servor error [[[[enter image description here](https://i.stack.imgur.com/iVruu.png)](https://i.stack.imgur.com/4lvVr.png)](https://i.stack.imgur.com/edF6v.png)](https://i.stack.imgur.com/Vv59n.png) When I am in local /users/sign_up, I added a checkboxes type field so that the user can select game categories. When I am in my console, the creation of a user is done correctly by selecting my categories in my "favorites_games" array. When I'm on my sign_up page locally, when I select my categories by clicking on my checkboxes, it doesn't save. It tells me "favorites games can't be blank" and I see that an empty string is inserted before my category selections and that causes a rollback in my server.

I tried to insert in the create and new method in the users controller, a method to delete the first index of the favorites_games array. I also tried in my strong params, to write in two ways the argument favorites_games ==>:favorites_games and favorites_games: []. In my User model, I tried to insert in my validations: validates:favorites_games, allow_blank, inclusion {in:Event::CATEGORIES}. In my html.erb file, I tried to put "mulitple: true" as well as include_hidden: true but it doesn't work.




samedi 8 juillet 2023

how to show shiny groupcheckbox choices into specific number of rows and columns

I want the choices of this groupcheckbox to be shown into 4 columns. Like 1,2 in one column- 3,4 in the 2nd column and so on. I am new to shiny dashboard, so any hint is highly appreciated.

checkboxGroupInput("myGroup",
 label ="",
 width="100px",
 inline=TRUE,
 choices = c(1,2,3,4,5,6,7,8),
 selected = c(1,8))



Google sheets script if checkbox is checked than copy rows from one sheet to another

I have a small problem. I want to copy data from Sheet1 to Sheet2 with a button provided the checkbox is checked. In Sheet2, find the last row and then use the next one. After the data has been transferred, the cell content in Sheet1 should be deleted and the checkbox should be reset.

Can anyone help me with this?

Here is a screenshot from my sheet

I found this Code:

function button1() {
  var ss=SpreadsheetApp.getActive();
  var sht=ss.getSheetByName('tab1');
  var sht=ss.getSheetByName('tab2');
  var lastRow=sht.getLastRow();
  var rng=sht.getRange(1,1,lastRow,6);
  var rngA=rng.getValues();
  for(var i=0;i<rngA.length;i++)
  {
    if(rngA[i][2]==true)
    {
      sht.getRange(i+1,4).setValue(rngA[i][0]);
      sht.getRange(i+1,5).setValue(rngA[i][1]);
    }
  }
  SpreadsheetApp.flush();
}

But this code writes the data right next to the row. I would have to modify the code so that Sheet2 writes row by row starting with the last free row.




vendredi 7 juillet 2023

How can I hide different sets of ActiveX checkboxes in Excel based on two variables?

I'm really new at VBA, so I apologize. Hopefully I can describe well enough. I recently changed a section of my spreadsheet from an area I can completely white out with conditional formatting to an area that is text (which I can white out), but also a row of 13 Active X checkboxes. This pick shows a setup where box 13 should not be shown. example

Bear with my sudden thought change. This was what I originally wanted: When I white out now, obviously the checkboxes will not do the same. The main problem lies in that I need certain checkboxes shown based on the value in cell K12 and the value in Z77. If Z77="N", then all the boxes need to be hidden, no matter what K12 is. If Z77="Y" and K12="B", then checkboxes 5-13 need to hide. If Z77="Y" and K12="D", then only box 13 needs to hide. If Z77="Y" and K12="P", then checkboxes 8-12 need to hide.

But now I'm thinking more towards the end user that my selection boxes might be easier if I changed Z77 from a Y/N option to a checkbox. I would have to change K12 to three checkboxes to select from. How much more complicated would that make my life? So fun to have a sudden mindshift when almost complete with a project... can you help?

And as long as I have you, what would recommend as the best way to learn VBA to be?

I couldn't find anything that suited my needs.




Handling unchecked checkboxes when the element name uses array notation

I have a form that is displayed in a table. This table has some elements and javascript which allows the template row to be duplicated to allow the user to add/remove rows as they want.

Here is a simplified version of the template

<tr data-being_removed="false" data-type="pickup" id="stop_table_row_template" style="display: none;">
    <td>
        <div class="input-group" style="margin: 0px;">
            <input type="text" placeholder="Pickup Number" class="form-control form-control-sm" name="stops[stop_number][]">
            <div class="input-group-text">
                <input class="form-check-input mt-0" name="stops[require_appointment][]" type="checkbox" value="1">
                &nbsp;Req. Appt.
            </div>
        </div>
        <select placeholder="Location" class="form-select ship_to_selector form-control-sm mt-1" name="stops[location_id][]">
            <option value="">Location</option>
        </select>
    </td>
</tr>

However, checkboxes are not sent to the server if they are not checked. Usually to get around this I would create a hidden input with an identical name. However, in this case, that would cause the actual checkbox to be associated to the wrong row because the hidden input will ALWAYS be sent but the checkboxes will also SOMETIMES be sent, throwing off the implied indexes.

In the current code, it does not work for the opposite reason. For example, if the user has 3 rows, but the checkbox is only checked on the 2nd row, the form thinks the checkbox belongs to the first row because there is no matching name attribute sent to the server from the first row.

I would like to avoid having to specify indexes in the name attributes themselves. Is there any way I can send a "0" value for the name of the checkbox if the one with "1" value is not checked?




jeudi 6 juillet 2023

How to make a custom FlutterFlow checkBox

i am trying to build a custom check box like this: enter image description here

which is simply a round container containing an icon inside, clicking on it will change the container background color and the icon color,

i tried to build a custom widget in flutter flow using custom checkbox flutter packages but they all need me to pass a function to the custom but i have the following error:

Unknown error compiling custom code. A common cause is a custom widget or action whose name in the code does not match the name provided in the editor.

that happened again when i tried to build it myself without using packages here is the code i searched and found:

    // Automatic FlutterFlow imports
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/widgets/index.dart'; // Imports other custom widgets
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

class IngridentsCheckBox extends StatefulWidget {
  const IngridentsCheckBox({
    Key? key,
    this.width,
    this.height,
    required this.onChange,
    required this.isChecked,
    required this.size,
    required this.iconSize,
    required this.selectedColor,
    required this.selectedIconColor,
    required this.borderColor,
    required this.checkIcon,
  }) : super(key: key);

  final double? width;
  final double? height;
  final Function onChange;
  final bool isChecked;
  final double size;
  final double iconSize;
  final Color selectedColor;
  final Color selectedIconColor;
  final Color borderColor;
  final Icon checkIcon;

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

class _IngridentsCheckBoxState extends State<IngridentsCheckBox> {
  bool _isSelected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isSelected = !_isSelected;
          widget.onChange(_isSelected);
        });
      },
      child: AnimatedContainer(
        margin: EdgeInsets.all(4),
        duration: Duration(milliseconds: 500),
        curve: Curves.fastLinearToSlowEaseIn,
        decoration: BoxDecoration(
            color: _isSelected
                ? widget.selectedColor ?? Colors.blue
                : Colors.transparent,
            borderRadius: BorderRadius.circular(3.0),
            border: Border.all(
              color: widget.borderColor ?? Colors.black,
              width: 1.5,
            )),
        width: widget.size ?? 18,
        height: widget.size ?? 18,
        child: _isSelected
            ? Icon(
                Icons.check,
                color: widget.selectedIconColor ?? Colors.white,
                size: widget.iconSize ?? 14,
              )
            : null,
      ),
    );
  }
}

and those are the parameters i am sending to the custom widget: enter image description here

i am getting the same error which is not clear enough to know exactly what is the issue, in previous versions of the code the error disappeared when i removed "onChange" function, so i do not know if it was the reason,

i also tried to do it using flutter state but couldn't make it, so i will be thankful if someone helps,

PLEASE NOTE: the code quoted is for a custom checkbox i found on stackoverflow, i used to customize it later if worked on flutterflow but i couldn't make it work




mercredi 5 juillet 2023

Need to get or populate the checkbox status when clicked on edit

I've check boxes displayed in the Recycler view with edit and delete options. Now I need to see / populate the data / get the Clicked / checked checkBox when I click on edit.

My Recycler View Activity

class RecView : AppCompatActivity() {

private var is_Role01: Boolean = false
private var is_Role02: Boolean = false
private var is_Role03: Boolean = false
private var is_Role04: Boolean = false
private var is_Role05: Boolean = false

private lateinit var addsBtn: FloatingActionButton
private lateinit var recv: RecyclerView
private lateinit var userList: ArrayList<UserData>
private lateinit var myAdapter: MyAdapter
private lateinit var RN: EditText
private lateinit var UN: CheckBox
private lateinit var PN: CheckBox
private lateinit var BD: CheckBox
private lateinit var AN: CheckBox
private lateinit var PR: CheckBox

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recview)
    userList = ArrayList()
    addsBtn = findViewById(R.id.addingBtn)
    recv = findViewById(R.id.mRecycler)
    myAdapter = MyAdapter(this, userList)
    recv.layoutManager = LinearLayoutManager(this)
    recv.adapter = myAdapter
    addsBtn.setOnClickListener { addInfo() }
}


@SuppressLint("NotifyDataSetChanged")
private fun addInfo() {
    val inflater = LayoutInflater.from(this)
    val v = inflater.inflate(R.layout.adduser, null)
    val addDialog = AlertDialog.Builder(this)

    RN = v.findViewById(R.id.roleName)
    UN = v.findViewById(R.id.role01)
    PN = v.findViewById(R.id.role02)
    BD = v.findViewById(R.id.role03)
    AN = v.findViewById(R.id.role04)
    PR = v.findViewById(R.id.role05)

    addDialog.setView(v)
    addDialog.setPositiveButton("Ok") { dialog, _ ->
        val rolename = RN.text.toString()
        val names = UN
        val number = PN
        val dob = BD
        val anni = AN
        val per = PR

        userList.add(UserData("Role Name : $rolename", names, number, dob, anni, per))
        myAdapter.notifyDataSetChanged()
        Toast.makeText(this, "Adding User Information Success", Toast.LENGTH_SHORT).show()
        dialog.dismiss()

        UN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = UN.isChecked
            is_Role01 = checked
        }
        PN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = PN.isChecked
            is_Role02 = checked
        }
        BD.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = BD.isChecked
            is_Role03 = checked
        }
        AN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = AN.isChecked
            is_Role04 = checked
        }
        PR.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = PR.isChecked
            is_Role05 = checked
        }


    }
    addDialog.setNegativeButton("Cancel") { dialog, _ ->
        dialog.dismiss()
        Toast.makeText(this, "Cancel", Toast.LENGTH_SHORT).show()
    }
    addDialog.create()
    addDialog.show()
}

}

My Adapter Class Where I have edit and delete options.

class MyAdapter(val c: Context, val userList: ArrayList) : RecyclerView.Adapter<MyAdapter.UserViewHolder>() {

inner class UserViewHolder(val v: View) : RecyclerView.ViewHolder(v) {
    var roleName: TextView = v.findViewById(R.id.mRoleName)
    var name: CheckBox = v.findViewById(R.id.role01)
    var mbNum: CheckBox = v.findViewById(R.id.role02)
    var dob: CheckBox = v.findViewById(R.id.role03)
    var anni: CheckBox = v.findViewById(R.id.role04)
    var per: CheckBox = v.findViewById(R.id.role05)

    var mMenus: ImageView

    init {
        mMenus = v.findViewById(R.id.mMenus)
        mMenus.setOnClickListener { popupMenus(it) }
    }

    @SuppressLint("DiscouragedPrivateApi", "NotifyDataSetChanged")
    private fun popupMenus(v: View) {
        val position = userList[adapterPosition]
        val popupMenus = PopupMenu(c, v)
        popupMenus.inflate(R.menu.menu)
        popupMenus.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.editText -> {
                    val v = LayoutInflater.from(c).inflate(R.layout.adduser, null)
                    val roleName = v.findViewById<EditText>(R.id.roleName)
                    val name = v.findViewById<CheckBox>(R.id.role01)
                    val number = v.findViewById<CheckBox>(R.id.role02)
                    val dob = v.findViewById<CheckBox>(R.id.role03)
                    val anni = v.findViewById<CheckBox>(R.id.role04)
                    val per = v.findViewById<CheckBox>(R.id.role05)
                    AlertDialog.Builder(c).setView(v).setPositiveButton("Ok") { dialog, _ ->
                        position.roleName = roleName.text.toString()
                        position.userName = name
                        position.userMb = number
                        position.userDob = dob
                        position.userAnni = anni
                        position.per = per
                        notifyDataSetChanged()
                        Toast.makeText(c, "User Information is Edited", Toast.LENGTH_SHORT)
                            .show()
                        dialog.dismiss()

                    }.setNegativeButton("Cancel") { dialog, _ ->
                        dialog.dismiss()

                    }.create().show()

                    true
                }
                R.id.delete -> {
                    /**set delete*/
                    AlertDialog.Builder(c).setTitle("Delete").setIcon(R.drawable.ic_warning)
                        .setMessage("Are you sure delete this Information")
                        .setPositiveButton("Yes") { dialog, _ ->
                            userList.removeAt(adapterPosition)
                            notifyDataSetChanged()
                            Toast.makeText(c, "Deleted this Information", Toast.LENGTH_SHORT)
                                .show()
                            dialog.dismiss()
                        }.setNegativeButton("No") { dialog, _ ->
                            dialog.dismiss()
                        }.create().show()

                    true
                }
                else -> true
            }

        }
        popupMenus.show()
        val popup = PopupMenu::class.java.getDeclaredField("mPopup")
        popup.isAccessible = true
        val menu = popup.get(popupMenus)
        menu.javaClass.getDeclaredMethod("setForceShowIcon", Boolean::class.java)
            .invoke(menu, true)
    }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val v = inflater.inflate(R.layout.list_item, parent, false)
    return UserViewHolder(v)
}

override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
    val newList = userList[position]
    holder.roleName.text = newList.roleName

    if (newList.userName.isChecked) {
        holder.name.visibility = View.VISIBLE
    } else {
        holder.name.visibility = View.GONE
    }

    if (newList.userMb.isChecked) {
        holder.mbNum.visibility = View.VISIBLE
    } else {
        holder.mbNum.visibility = View.GONE
    }


    if (newList.userDob.isChecked) {
        holder.dob.visibility = View.VISIBLE
    } else {
        holder.dob.visibility = View.GONE
    }


    if (newList.userAnni.isChecked) {
        holder.anni.visibility = View.VISIBLE
    } else {
        holder.anni.visibility = View.GONE
    }

    if (newList.per.isChecked) {
        holder.per.visibility = View.VISIBLE
    } else {
        holder.per.visibility = View.GONE
    }
}

override fun getItemCount(): Int {
    return userList.size
}

}

My Data Class

data class UserData( var roleName: String, var userName: CheckBox, var userMb:CheckBox, var userDob:CheckBox, var userAnni:CheckBox, var per:CheckBox )

The Data which are given while saving initially should be populated to the edit screen. Could anyone help me out with this.

In here I've selected 2 check boxes and given a Role Name as Admin, now when I click on menu the same data should be populated or get

When I click on edit, the data selected in the previous page should be visible.




How to pass data of the checkbox group with vue quasar?

In the checkbox group I'm itterating through an array, but when I reform the array to the array of objects with label prop, value prop, hence passing it in the template the code doesn't run. Having the error - v-html will override element children. It comes because of the v-html="opt" in the template. I'm expecting to render the text of the stringOptions array.

<q-select
              hide-bottom-space
              options-dense
              hide-dropdown-icon
              input-debounce="500"
              @filter="filterFn"
              style="width: 200px"
              counter
              hint="Selected items"
              use-input
              dense
              hide-selected
              clearable
              filled
              v-model="model"
              :options="filterOptions"
              label="Actors"
              multiple
            >
              <template
                v-slot:option="{ itemProps, opt, selected, toggleOption }"
              >
                <q-item v-bind="itemProps">
                  <q-item-section>
                    <q-item-label v-html="opt"></q-item-label> // error here
                  </q-item-section>
                  <q-item-section side>
                    <q-checkbox
                      :model-value="selected"
                      @update:model-value="toggleOption(opt)"
                    ></q-checkbox>
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            
<script>
export default {
    stringOptions: [
    'All',
    'Alfa',
    'Omega',
    'Lampda',
    // { label: 'All', value: 'all' },
    // { label: 'Alfa', value: 'alfa' },
    // { label: 'Omega', value: 'omega' },
    // { label: 'Lampda', value: 'lampda' }
  ],
}
</script>



mardi 4 juillet 2023

Saving checkbox state when X item is selected?

I am creating the GUI of a preprocessor to be able to solve flow problems, I need the items that are in the ListWidget to save the state of the checkbox that I want to select

Example of the behavior I require

Is this possible? If so, how would I achieve it?

I tried using the setData method, I wanted to save the state of each checkbox using an array with values ​​of 0 and 1, so every time one of the items was selected, I expected the state to be saved as a value in the array, to later read it when the item is selected again and place the corresponding checkbox as checked.

    self.bordesWindow.ui.listWidgetVarEsc.itemSelectionChanged.connect(self.settingCheckBoxStateBorde)
    self.bordesWindow.ui.listWidgetVarEsc.itemClicked.connect(self.gettingCheckBoxStateValue)

def settingCheckBoxStateBorde(self):
    self.arrayValuesCheckboxesBordes = np.zeros(3)
    self.constDataBordeCheckboxState = Qt.ItemDataRole.UserRole
    item = self.bordesWindow.ui.listWidgetVarEsc.currentItem()
    item.setData(self.constDataBordeCheckboxState, self.arrayValuesCheckboxesBordes)
    if self.bordesWindow.ui.checkBoxVariablesEscValor.isChecked():
        item.data(self.constDataBordeCheckboxState)[0] = 1
    elif self.bordesWindow.ui.checkBoxVariablesEscFlujo.isChecked():
        item.data(self.constDataBordeCheckboxState)[1] = 1
    elif self.bordesWindow.ui.checkBoxVariablesEscConveccion.isChecked():
        item.data(self.constDataBordeCheckboxState)[2] = 1

def gettingCheckBoxStateValue(self):
    item = self.bordesWindow.ui.listWidgetVarEsc.currentItem()
    if item.data(self.constDataBordeCheckboxState)[0] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscValor.setChecked(True)
    elif item.data(self.constDataBordeCheckboxState)[1] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscFlujo.setChecked(True)
    elif item.data(self.constDataBordeCheckboxState)[2] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscConveccion.setChecked(True)



VBA for insert commumn with checkboxes and afterward print checked boxes

I have an Excel file where i want to use VBA to insert a column in front of the excising column A. The file contains other VBA's for generate a list. So, the list can change in numbers of columns and rows. I use below VBA to print, it works just fine. But I want it to do like: Press print bottom, the VBA insert a new column A with check boxes. A Msg box pops up and stay on top (Press OK when you are ready to print), then you can select the lines that you want to print in the check boxes. If you don't select any check boxes the print VBA should print all active lines as it do now, except the new column A with check boxes.

Sub Print()

Call Uden_pre_booking   'Starts the VBA that makes a fresh list

Dim ws3 As Worksheet
Dim EndRow As Long, EndCol As Long

Set ws3 = Sheets("Vis_Oversigt")

EndCol = ws3.Cells(4, 6).Value + 10
EndRow = ws3.Range("B" & Rows.Count).End(xlUp).Row + 2
   
ws3.PageSetup.PrintArea = ws3.Range(Cells(1, 1), Cells(EndRow, EndCol)).Address



ActiveSheet.PrintPreview

End Sub

I have tried several VBA's from different sites, but doesn't manage to get it into a functional VBA.

Hope that someone will help me make a functionally VBA.




lundi 3 juillet 2023

How to handle checkbox change in React.js?

I'm trying to handle change of the value when a check box is clicked. The component loads a response like this:

[
   {
       "id_ver_group": 7,
       "checklist": [
           {
            "check": "Custom ver 1",
            "valor": false,
            "opcional": true
           },
        {
            "check": "Custom ver 2",
            "valor": false,
            "opcional": false
        }
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
  {
       "id_ver_group": 6,
       "checklist": [
           {
               "check": "Custom ver 1",
               "valor": false,
               "opcional": true
           },
           {
               "check": "Custom ver 2",
               "valor": false,
               "opcional": false
           },
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
]

The response is grouped by "id_ver_group" in an "Accordion" tag where each "checklist" item is displayed in a table, its columns are: "verify" (string), "value" (bool) and "optional " (bool) , the checkbox tag is used to display the "value" and "optional" columns, the latter being read-only. This is the component code:

// imports...
import {
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  Checkbox,
  Select,
  InputLabel,
  Button,
} from '@material-ui/core'

export function AddEditChecklist(props) {
     
const { Tanques, onClose, onRefetch } = props
const { Successful, errores } = alertas()
const { Data, getBaseVer } = useVerificaciones()
const { addTankVer, updateTankVer } = useTanques()
const { OperadorDB, getOperadorDB } = useOperador()
const [selectedOperator, setSelectedOperator] = useState('');
const [isOperatorSelected, setIsOperatorSelected] = useState(true);

const [selectedGroup, setSelectedGroup] = useState(null);
  const [selectedGroupIndex, setSelectedGroupIndex] = useState(null);

  useEffect(() => {
    getOperadorDB()
    getBaseVer()
  }, []);

  const [data, setData] = useState([]);

  useEffect(() => {
    setData(Data?.map(item => ({
      ...item,
      checklist: item.checklist.map(checklistItem => ({
        ...checklistItem,
        valor: false  
      }))
    })) || []);
  }, [OperadorDB, Data]);

  const handleAccordionChange = (groupId) => {
    setSelectedGroupIndex(groupId); 
    setSelectedGroup(groupId)
    
    if (selectedGroup === groupId) {
      setSelectedGroup(null); 
    } else {
      setSelectedGroup(groupId); 
    }
  };

// check box handle
  const handleCheckboxChange = (groupId, itemIndex, checklistItem) => {
    setData((prevData) => {
      const updatedData = [...prevData];
      const groupData = updatedData[groupId];

      if (groupData && groupData[itemIndex]) {
        checklistItem.valor = !checklistItem.valor; 
      }

      return updatedData;
    });
  };

  // group data by id
  const groupedData = data ? data.reduce((groups, item) => {
    const groupId = item.id_ver_group;
    if (!groups[groupId]) {
      groups[groupId] = [];
    }
    groups[groupId].push(item);
    return groups;
  }, {}) : {};
// handleSubmit...

return (
    <>
      {/* checklist */}
      {Object.keys(groupedData).map((groupId) => (
        <Accordion
          key={groupId}
          expanded={selectedGroup === groupId}
          onChange={() => handleAccordionChange(groupId)}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="h6">Conjunto de verificaciones # {groupId}</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <div>
              {groupedData[groupId].map((item, index) => (
                <div key={item.id_ver_group}>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell><strong>Verificación</strong></TableCell>
                        <TableCell><strong>¿Cumple?</strong></TableCell>
                        <TableCell><strong>¿Opcional? (no modificable)</strong></TableCell>
                      </TableRow>
                    </TableHead>
                    {item.checklist.map((checklistItem) => (
                      <TableBody key={checklistItem.check}>
                        <TableRow>
                          <TableCell>
                            {checklistItem.check}
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              checked={checklistItem.valor}
                              name={checklistItem.check}
                              onChange={() => handleCheckboxChange(groupId, index, checklistItem)}
                            />
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              readOnly
                              checked={checklistItem.opcional}
                              name={checklistItem.check}
                            />
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    ))}
                  </Table>
                </div>
              ))}
            </div>
          </AccordionDetails>
        </Accordion>
      ))}
      <br></br>
      <Divider></Divider>
      <br></br>
      <Button variant="contained" color="primary" onClick={handleSubmit}>
        Save
      </Button>
    </>
  )
} 

Doing some research, I was able to come up with something to handle the checkbox changing, but the checkbox doesn't change its value when clicked. I really don't know how to solve this. Any help is appreciated.