lundi 31 octobre 2022

Bind checkbox value to parent component with controlvalueaccesor

I recently started learning Angular and I'm facing a form issue. I currently have a form with a label and an input field. Since this is quite a large form I decided to make a separate component for the input and validation of the form.

A table row therefore looks like this:

          <tr
            app-table-row-input
            [label]="'ConfigInterval'"
            [formControl]="RestForm.controls['ConfigInterval']"
            [type]="'number'"
          ></tr>

HTML table-row-input

    <th>
    <label class="required"></label>
    </th>
    <th>
    <input
    type=""
    [ngClass]="{
      'validation invalid': !ngControl.valid
    }"
    style="width: auto"
    class="fullwidth"
    [formControl]="ngControl.control"
    required
    />
    <span
    class="validation-msg"
    *ngIf="ngControl.invalid && (ngControl.dirty || ngControl.touched)"
    >
    Not valid
    </span>
    </th>

The types of number and text result in the form input being updated. However when I try to also use this for the checkbox type the form isn't updated with "true" or "false" like it does when not using a separate component. My code for the checkbox currently looks like this:

html parent Form component

            <tr
            app-table-checkbox
            [label]="'AuthEnabled'"
            [formControl]="RestForm.controls['AuthEnabled']"
            [id]="'cb1'"
            [type]="'checkbox'"
            ></tr>

html checkbox input component:

    <th>
     <label class="required"></label>
    </th>
    <th>
    <input
    type=""
    class="fullwidth"
    id=""
    [formControl]="ngControl.control"
    required
    />
    <label for="">True or False</label>
    </th>

The TS in both components looks the same (except for id property not being there):

    export class TableCheckboxComponent implements ControlValueAccessor {
   @Input() label: string;
   @Input() type = 'text';
   @Input() id: string;

   constructor(@Self() public ngControl: NgControl) {
    ngControl.valueAccessor = this;
   }
   writeValue(obj: any): void {}
   registerOnChange(fn: any): void {}
   registerOnTouched(fn: any): void {}
   }

Can somebody explain why the text and number inputs do work but this doesnt work for the checkbox?




how to get list of checked checkbox value and prepare json object?

<input type="checkbox" name="UserData" id="c1" value="A">
<input type="checkbox" name="UserData" id="c1" value="B">
<input type="checkbox" name="UserData" id="c1" value="C">
<input type="checkbox" name="UserData" id="c1" value="D">

var deleteInfo = "";
var bFirst=true;
$(":checkbox").each(function () {
    var ischecked = $(this).is(":checked");
    if (ischecked) {
        if (bFirst) {
            deleteInfo += '' + $(this).val() + '"';
            bFirst=false;
        } else {
            deleteInfo += ',' + $(this).val() + '"';
        }
    }
});

var strUserID = document.getElementById("sUserID").value;
var myData = {
    "UserID"     : strUserID, 
    deleteInfo
};

$.ajax({
    type: "POST",
    url: "RemoveUserData",
    data: JSON.stringify(myData),
    dataType: "json",
    success: function(result){
        alert (result.status);
    }
});
return false;

i have a jsp page which get user checked value from checkbox and then prepare json array object with user id. but i don't know how to prepare the variable for ajax prcocess. my expected json object is {"UserID": "PETER", "deleteInfo": ["A","C"]}

anyone can help how to format the json value like this: {"UserID": "PETER", "deleteInfo": ["A","C"]}

Thanks.




dimanche 30 octobre 2022

Multiple Checkboxes with ngRepeat, having problems binding ng-model

Good Afternoon,

I have a couple of problems that I have spent a few days trying to figure out, the first is my ngModel is not binding correctly as some of the checkboxes should be checked on load, you can see there state next to each one. The second problem which could be related to the first problem is that when I check one of the boxes, it unchecks itself after a second. I can see the ng-change is firing but it is always 'True'.

I have tried ngChecked, which I did get working but I know from reading the docs this is not meant to be used with ngModel.

Time for the code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <form name="myForm">
    <div ng-if="data.show_desc == 'true'"></div>
    <ul ng-repeat="item in data.checklist_items">
      <li>
        <label for="lists_1">
          <input type="checkbox"
                 id="lists_1"
                 ng-model="all"
                 ng-change="c.selectAll(all)"
                 />
          <span ng-if="data.bold == 'true'"><strong></strong>- </span>
          <span ng-if="data.bold == 'false'"></span>
        </label> 

        <ul ng-repeat="sub_item in data.sub_checklist_items | filter:item.name">    
          <li> 
            <label for="sub_items_2">
              <input type="checkbox"
                     id="sub_items_2"
                     ng-model="sub_item.completed"
                     ng-change="c.selectRecord(sub_item)" 
                     />
              </label> - 
          </li>    
        </ul>
      </li>
    </ul>
  </form>
</html>

Top Level List:

[
   {
      "name":"Checklist Item 1",
      "completed":"false",
      "sys_id":"52269f70473e1110ca70bce5536d43db"
   },
   {
      "name":"Checklist Item 2",
      "completed":"false",
      "sys_id":"9e269f70473e1110ca70bce5536d43db"
   },
   {
      "name":"Checklist Item 3",
      "completed":"false",
      "sys_id":"da269f70473e1110ca70bce5536d43db"
   },
   {
      "name":"Checklist Item 4",
      "completed":"false",
      "sys_id":"1a269f70473e1110ca70bce5536d43db"
   }
]

Sub Level list:

[
   {
      "name":"Sub Checklist 4",
      "completed":"true",
      "sys_id":"1a269f70473e1110ca70bce5536d43dc",
      "parent_checklist":"Checklist Item 4"
   },
   {
      "name":"Sub Checklist 1",
      "completed":"true",
      "sys_id":"92269f70473e1110ca70bce5536d43dc",
      "parent_checklist":"Checklist Item 1"
   },
   {
      "name":"Sub Checklist 1",
      "completed":"true",
      "sys_id":"da269f70473e1110ca70bce5536d43dc",
      "parent_checklist":"Checklist Item 2"
   },
   {
      "name":"Sub Checklist 2",
      "completed":"true",
      "sys_id":"56269f70473e1110ca70bce5536d43dc",
      "parent_checklist":"Checklist Item 1"
   },
   {
      "name":"Sub Checklist 2",
      "completed":"true",
      "sys_id":"9e269f70473e1110ca70bce5536d43dc",
      "parent_checklist":"Checklist Item 2"
   }
]

When its brought together

Any ideas?

So far I have tried ngChecked and AngularJS directive for list of checkboxes. My end goal is to track the state of each checkbox and maybe when the top level is checked then all the sub checklists are also checked, I really didn't think it was going to be this hard...sigh




How to add a checkbox to turn and on and off my script

var color = prompt("Please type a color code below!");

(function() {
    var Properties = {
        SCRIPT_CONFIG: {
            NAME_COLOR: `${color}`, 
        },
        MENU_CONFIG: {

            COLOR_1: "#00FFF0", 
        },
    }
    function changebackgroundcolor() {

        $('.fade-box').css({
            background: 'linear-gradient(to right bottom,hsl('+Properties.COLOR_HUE+', 50%, 50%),hsl('+Properties.COLOR_HUE2+', 50%, 50%)'
        })
    }
    var { fillText } = CanvasRenderingContext2D.prototype;
    CanvasRenderingContext2D.prototype.fillText = function(text, x, y) {
        let localstorage = Properties.SCRIPT_CONFIG
        if(text == document.getElementById("nick").value) {
            this.fillStyle = localstorage.NAME_COLOR;
        }
        fillText.call(this, ...arguments);
    }
    document.addEventListener("DOMContentLoaded", ready)
})();

can you add a check box to turn and off the color say the game defualt color is white and my script makes it black i want a checkbox what i can click to go back to defualt or back to script

i tried some checkbox's multiple times but it didnt do nothing i was hoping i had a check box that turned the script on and off!




samedi 29 octobre 2022

How to change boolean value from a Dialog?

I need to change a Boolean value from a Dialog. It works if I have my Checkbox on my page, but not when I try it in a Dialog.

How can I get the value of ìsselected1 from my Dialog to my page?

Here is my Dialog:

IconButton(onPressed: () {
                showDialog(context: context, builder: (ctx) {
                  return StatefulBuilder(
                    builder: (context, setState) {
                      return Dialog(
                        child: SizedBox(
                          height: 200,
                          width: 100,
                          child: Column(
                            children: [
                           
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Row(
                                  children: [
                                    Text('Test'),
                                    Checkbox(value: isselected1, onChanged: (value) {
                                      setState(() {
                                     
                                        isselected1 = value!;
                                      });
                                    }),
                                    
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      );
                    },
                  );
                });

              }, icon: Icon(Icons.add))
            ],
          ),



jeudi 27 octobre 2022

Validate checkboxes values in PHP

I have a group of checkboxes with different values each. I want to assign their values in php variables which i'm going to send to database. The main problem is that i don't know how to check inside the php code if the values of selected items matching their default values which i setup in the html (apple == apple, samsung == samsung) and so on. This is because someone can just change the input value inside the console and insert whatever he likes in my DB. Any ideas how i can sort this out. Many thanks!

    <form action="" method="POST">
        <label for="apple">Apple</label>
        <input id="apple" type="checkbox" name="myCheckBoxes[]" value="Apple">
        <label for="samsung">Samsung</label>
        <input id="samsung" type="checkbox" name="myCheckBoxes[]" value="Samsung">
        <label for="lenovo">Lenovo</label>
        <input id="lenovo" type="checkbox" name="myCheckBoxes[]" value="Lenovo">
        <label for="google">Google Pixel</label>
        <input id="google" type="checkbox" name="myCheckBoxes[]" value="Google Pixel">

        <button type="submit" name="submit">Send</button>
    </form>

PHP Code:

if (isset($_POST['submit'])) {
    $checkBoxes = $_POST['myCheckBoxes'];
    $numberSelected = count($checkBoxes);
    
    if ($numberSelected > 3) {
        echo 'Please select only 3 from the options';
    } else {
        for ($i = 0; $i < $numberSelected; $i++) {
            $option1 = $checkBoxes[0];
            $option2 = $checkBoxes[1];
            $option3 = $checkBoxes[2];
        }
        echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
    }  
}



Hiding the div and li elements when checkbox is checked/unchecked

Can anyone guide me in the correct direction please? I'm stuck with checked and not checked checkboxes. What needs to be added:

  • Text in the text field & checkbox checked - hides the div element
  • Text in the text field & checkbox unchecked by entry - hides the first li element
  • Empty text field by entry & checkbox checked hides the second li element

What I have now:

let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")

but.disabled = true
divv.style.display = "block" 

cons.addEventListener("input", function() {
if (cons.checked && txt.value !== ''){
  consError.style.display = "none"
  but.disabled = false
  } else {
    consError.style.display = "block"
    but.disabled = true
  }
})

txt.addEventListener("input", function(){
  if (txt.value !== '' && cons.checked === false ) {
  but.disabled
  } else {
    but.disabled = false
  }
})

function fun () {
  out.textContent =  "Hey " + txt.value + "!"
}

but.addEventListener("click",fun)

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A checkbox</title>
  </head>
  <body>
    <label for="name">Name</label>
    <input id="name" placeholder="Name">
    <label>
      <input id="consent" type="checkbox">
      I agree
    </label>
    <input id="send" type="button" value="Submit">
    <p id="greeting"></p>
    <div id="errors" style="color: red; display: none;">
      <p>Error:</p>
      <ul>
        <li id="name-error">Please enter a name</li>
        <li id="consent-error">Please give consent</li>
      </ul>
    </div>
    <script src="index.js"></script>
  </body>
</html>

Before I had cons.addEventListener like this and it was hiding the second li element but didn't keep the button disabled

cons.addEventListener("input", function() {
if (cons.checked){
  consError.style.display = "none"
  } else {
    consError.style.display = "block"
  }
})



how to make checkbox works fine in notebook, tkinter, matplotlib

I have 3 sheets in a notebook that do the same thing as I show in the code below. (This code works fine here but not in my code)

All sheets have the function checkbox_O and g_checkbox with the same name and all use the global variable lines

When I press the graph button, the graphs are displayed but the checkboxes only work fine on sheet 1.

I did code tests and I realize that, in sheet 2 and 3, the g_checkbox function does not have access to the lines array (I don't know why)

This is what I tried to fix it and it didn't work:

  1. tried to write g_checkbox function as a class method
  2. I tried to place a global lines variable for each sheet
  3. I changed the name of the function checkbox_O in each sheet, so that it is different in each one of them

I need help please to know how to make the checkboxes work in all three sheets. I don't know what I'm doing wrong and I don't know how to fix it.

Thanks in advance

import numpy as np
import tkinter as tk
from tkinter import ttk
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use('TkAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import(FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib import style
from matplotlib.widgets import CheckButtons, Button, TextBox, RadioButtons


x = np.arange(-15, 15, .01)
lines = []


class root(tk.Tk):
    def __init__(self):
        super().__init__() 
        self.geometry('750x618')
        self.my_book()
        
    def my_book(self):
        #I left it out so the code doesn't get too long
        

class myFrame(ttk.Frame):
    def __init__(self,  master=None):
        super().__init__(master)
        self.master = master
        self.my_widgets()

    
    def my_widgets(self):
        self.f = Figure(figsize=(7, 5.5), dpi=100)
        self.plott = self.f.add_subplot()
    
        self.canvas = FigureCanvasTkAgg(self.f, self)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack()

        self.button_ax = self.f.add_axes([0.76, 0.95, 0.11, 0.04])
        self.button_graph = Button(self.button_ax, 'Graph', color='darkgrey')
        self.button_graph.on_clicked(self.callback_button)
        plt.show()

    def callback_button(self, event):
        self.graph_1()
        self.graph_2()

    def checkbox_O(self, lines, f):
        self.check_ax = f.add_axes([0.76, 0.085, 0.21, 0.16])
        labels = [str(line.get_label()) for line in lines]
        labels_visual = ['graph1', 'graph2']
        visibility = [line.get_visible() for line in lines]
        self.check = CheckButtons(self.check_ax, labels_visual, visibility)

        def g_checkbox(label):
            selec_index = [ind for ind, lab in enumerate(self.check.labels) if label in lab._text]
            for index, laabel in enumerate(labels):
                if laabel==label:
                    lines[index].set_visible(not lines[index].get_visible())
                    if (lines[index].get_visible()):
                        self.check.rectangles[selec_index[0]].set_fill(True)
                    else:
                        self.check.rectangles[selec_index[0]].set_fill(False)

            f.canvas.draw()
        self.check.on_clicked(g_checkbox)
        plt.show()

    def graph_1(self):
        global lines
        for i in range(0, 15):
            V = np.sin(i/10*x) + 2*i 
            l0, = self.plott.plot(x, V, label='graph1')
            lines.append(l0)
        self.checkbox_O(lines, self.f)
        
    def graph_2(self):
        global lines
        for i in range(0, 15):
            l0, = self.plott.plot([i, i], [0, 10], label='graph2')
            lines.append(l0)   
        self.checkbox_O(lines, self.f)
    
        
        
if __name__ == "__main__":
    app = root()
    app.mainloop()

PS: By the way, I took the code from stackoverflow and modified it so that it works like this




mercredi 26 octobre 2022

How to hide checkbox label by value?

Have 2 identical blocks of code:

<label class="checkbox-body chkpositive tags-block mb-5">
  <input class="checkbox" type="checkbox" value="" name="tags[]">
  <div id="checkbox" class="checkbox-block"></div>
  <p class="constructor_checkbox-text"> ()</p>
</label>
<label class="checkbox-body chknegative tags-block mb-5" value="">
  <input class="checkbox" type="checkbox" value="" name="notags[]" id="chknegative">
  <div id="checkbox" class="checkbox-block"></div>
  <p class="constructor_checkbox-text"></p>
</label>

They are different only in name of label classes chkpositive and chknegative, and input names

They are responsible for showing of tags which must placed in process of choise films. I need to do so that when press on tag from block chkpositive tag with identical value in block chknegative dissapeared. And vice versa when press on tag from block chknegative to disappear identical tag from chkpositive. By method "toggle" for example.

I wanted to do this with javascript and jQuery, but haven't a success. Can this issue have a simple solutions?

12 hours find for a solutions, try many codes, saw analogs with google, but don't found. Came to the conclusion that I need something similar, but working:

$(function() {
    $(".chkpositive input").click(function(event) {
        var x = $(this).is(':checked').value;
        if (x == true) {
            $(this).value.(".chknegative").hide();
        } else {
            $(this).value.(".chknegative").show();
        }
    });
  });

$(function() {
    $(".chknegative input").click(function(event) {
        var x = $(this).is(':checked').value;
        if (x == true) {
            $(this).value.(".chkpositive ").hide();
        } else {
            $(this).value.(".chkpositive ").show();
        }
    });
  });



mardi 25 octobre 2022

Change Mat-pseudo-checkbox color on a button click

I have created a UI with the help of mat-selection list. mat-selection-list having checkboxes.

If we click on the checkbox, it should be on green color.

enter image description here

When i click on the submit button, wanted to change the color into brown

Here is the code i have used

Html code

<mat-selection-list #searchList class="selection-list">
        <mat-list-option checkboxPosition="before" >
        </mat-list-option>     
</mat-selection-list>

.scss

.selection-list.mat-selection-list.mat-pseudo-checkbox-checked,
  .mat-pseudo-checkbox-indeterminate,
  .mat-accent .mat-pseudo-checkbox-checked,
  .mat-accent .mat-pseudo-checkbox-indeterminate {
    background: $green-500;
  }

How to change the checkbox color when we click on the submit button.

Thanks in advance.




event.target.checked doesn't return True or False when using NextUi checkbox component

I'm using a NextUi Checkbox component and I'm trying to create a handleFonction in order to get boolean of the event (true of false). So I use event.target.checked but it returns undefined. Event if I use event.checked it dosen't work (still undefined)

here my function to handle checkbox :

`const handleChange = (event, option) => { const checked = event.target.value

if (checked) {
  changePrice(option.price)
} else {
  changePrice(-option.price)
}

}`

and here my component form Nextui

<Checkbox
                color='warning'
                id={option.text}
                name={option.text}
                size='md'
                className={styles.checkbox}
                label={option.text}
                isRounded={true}
                onChange={(event) => handleChange(event, option)}
              />

Thanks a lot for your reply




How to clear JCheckBox text which was added to TextArea when unselected

I am creating a programme which displays the value of JCheckBoxes whenever one or more are selected in a textarea I am trying to make it so when the checkbox is unselcted that specific text only dissapears for example.

Java : check c+: check

TextArea Display Java c+

Java : uncheck c+: check

TextArea Display c+


     
     cBox1 = new JCheckBox("Java");
     panelCheckBoxes.add(cBox1);
     cBox1.addActionListener(this);
     
     cBox2 = new JCheckBox("C+");
     panelCheckBoxes.add(cBox2);
     cBox2.addActionListener(this);
public void actionPerformed(ActionEvent e) {    
        
     {
             if (e.getSource() instanceof JCheckBox) {

                    JCheckBox cb = (JCheckBox)e.getSource();
                    String text = cb.getText();
                    
                    boolean isNotSelected = !cb.isSelected();
                
                     if(cb.isSelected()) {
                             txtrShow.append(text + "\n");
                     }else if(isNotSelected == true)
                         txtrShow.replaceSelection("");
                }
             
        
             }



Bug on checkboxes in laravel livewire

I'm having a doble problems with my checkboxes on livewire component.

I'm trying to save in my form's table two checkboxes. This checkboxes take their value in an other table named "Garde_type". Checkbox "home" save in my form's table the ID 1, checkbox "visit" save ID 2. Here all is simple...but

Laravel livewire ask me property rules to save my data. Ok ! But when i put in rules my 2 checkboxes : in my form the checkbox can't be checked..when i check them they check/uncheck immediately = first problem. Second problem : no matter check/uncheck...everytime i submit my form, the 2 checkboxes are consider "checked" and then saved in my DB.

Here you can take a look to my code, i tried many things but i have no idea any more.

This is the livewire component "controler" :

class VilleSelect extends Component {     

public $visit;
public $home;
public $user_id;

protected function rules() {

 return [     
    
   'visit' => 'nullable',
   'home' => 'nullable',
];
    }


public function submit() {

   $annonces=annonces::create([
        'home' => $this->home->id,
        'visit' => $this->visit->id,
    ]);
    
    $annonces->save();
       
}

This is the checkboxes :

 <div class="mt-4 space-y-4">
     <div class="flex items-start">
          <div class="flex h-5 items-center">
            <x-jet-input wire:model="home" value="" type="checkbox"/>
          </div>
          <div class="ml-3 text-sm">
            <x-jet-label for="home" value=""/>
          </div>
      </div>
      <div class="flex items-start">
          <div class="flex h-5 items-center">
            <x-jet-input wire:model='visit' value="" type="checkbox"/>
          </div>
                
          <div class="ml-3 text-sm">
            <x-jet-label for="visit" value=""/>
          </div>
       </div>               
  </div>



lundi 24 octobre 2022

Send unchecked checkboxes but with array

I have an input of checkboxes as an array:

<input type="checkbox" name="checkbox[]">

And I want to send the unchecked checkboxes as well. So if it's unchecked I want it to be in the array as well

I tried the solution in this post: POST unchecked HTML checkboxes:

  <input type='hidden' name='checkbox[]'>
  <input type='checkbox' name='checkbox[]'>

However, in the post it's not an array of checkboxes. In my case it doesn't work, it just adds it to the array and not overriding it.

So if I have a list of 5 checkboxes where 2 of them has been checked, I'll end up with 7 total of POST parameters (5 from the hidden, and 2 from the checkbox)




HOW TO ADD JCHECKBOX TO A JCOMBOBOX

I need to do a menu with checkboxes inside, I cant do it! I checked all the java api documentation and dont exist examples. Help...

   JComboBox<JCheckBox> cb = new JComboBox<JCheckBox>();

   cb.add(cbEasy = new JCheckBox("EASY", false));
   cb.add(cbDifficult = new JCheckBox("DIFFICULT", false));

In the interface its empty the combobox...




dimanche 23 octobre 2022

Toggle between set of checkboxes and uncheck the checked one when clicked

i have three checkboxes on my page and i want just one to be selected. If user clicks on another checkbox i uncheck the current one and check the clicked one. The problem here is that when a user check a box he just can't uncheck it... he can move to another one but i want to give the user option to uncheck the checked one as well. Any ideas? Thanks.

    const checkBoxes = document.querySelectorAll('input[type="checkbox"]');
    checkBoxes.forEach((checkBox) => {
        checkBox.addEventListener('click', () => {
            checkBoxes.forEach((checkBox) => {
                checkBox.checked = false;
            });

            checkBox.checked = true;

        });

    });
        <input type="checkbox" value="Option1">
        <input type="checkbox" value="Option2">
        <input type="checkbox" value="Option3">



Checkbutton does not work on a nested tkinter window

I am trying to create a Tkinter window with a button which when clicked will provide with a new window. The new window has a checkbox and I want some actions to be done based on the checkbox value.

from tkinter import *
from tkinter import messagebox

def my_command():

    def cb_command():
        firstname = fname_entry.get()
        messagebox.showinfo("First Name", firstname)
        if cbVar.get() == 1:
            messagebox.showinfo(cbVar.get())
        else: messagebox.showinfo("Not found!")

    root = Tk()
    root.geometry("200x200")
    fname = Label(root, text="First Name")
    fname.grid(row= 0, column = 0, sticky = "news", padx=5, pady=5)
    fname_entry = Entry(root, width = 10)
    fname_entry.grid(row =0, column = 1, sticky = "news", padx=5, pady=5)
    cbVar = IntVar()
    cb1 = Checkbutton(root, text="Please check this", variable=cbVar, onvalue=1, offvalue=0, command=cb_command)
    cb1.grid(row = 1, column = 0)
    root.mainloop()

window = Tk()
window.geometry("200x200")
button1 = Button(window, text = "Run", command = my_command)
button1.pack()
window.mainloop()

I wrote this simple code which works fine with all other entry widgets. However, the checkbutton in the new window does not work. Can someone suggest any alternative?




samedi 22 octobre 2022

flutter checkboxListTile is not getting checked in flutter

I am using CheckboxListTile to check the items instead of checkbox. I want to fetch data of selected Items. All works fine. I am getting the expected data but the state of checkbox is staying the same it is not changing...

 List selectedItemsList = [];
  List checkListItems = [
    {
      "id": 0,
      "value": false,
      "title": "Sunday",
    },
    {
      "id": 1,
      "value": false,
      "title": "Monday",
    },
  ];
 
 Center(
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: ListView.builder(
            itemCount: checkListItems.length,
            itemBuilder: (BuildContext context, int index) {
              bool? isChecked = false;
              return CheckboxListTile(
                  title: Text(checkListItems[index]['title'].toString()),
                  selected: isChecked,
                  value: isChecked,
                  onChanged: (value) {
                    setState(() {
                      isChecked = value;
                      print(isChecked);
                    });
                    if (selectedItemsList.contains(checkListItems[index])) {
                      selectedItemsList.remove(checkListItems[index]);
                    } else {
                      selectedItemsList.add(checkListItems[index]);
                    }
                  });
            },
          ),
        ),
      ),



R shiny Multiple slider dynamic inputs based on checkbox inputs

This is an extension of the question asked here: R shiny Multiple slider inputs based on checkbox inputs. The issue I have is that my checkbox "One" should open sliders 1 and 2 and checkbox "Three" should open sliders 1 and 3. If I check "One" and "Three" I am getting slider 1 twice :(. Similarly, checking "One" and "Two" opening slider 2 twice :(. Expected behavior would be that only one slider is being used. My apologies in advance if this is trivial!

library(shiny)
myData = c("One", "Two", "Three")

ui <- fluidPage(
  
  checkboxGroupInput("choosemedia", "Choose digital", 
                     choices  = myData,
                     selected = myData),
  textOutput("myText"),
  conditionalPanel(condition = "input.choosemedia.includes('One')", 
                   sliderInput("sliderOne", "Choose value no 1", 
                               min=0, max=100, value=50),
                   sliderInput("sliderTwo", "Choose value no 2",
                               min=0, max=50, value=25)),
  
  conditionalPanel(condition = "input.choosemedia.includes('Two')",
                   sliderInput("sliderTwo", "Choose value no 2", 
                               min=0, max=50, value=25)),
  
  conditionalPanel(condition = "input.choosemedia.includes('Three')",
                   sliderInput("sliderOne", "Choose value no 1", 
                               min=0, max=50, value=25),
                   sliderInput("sliderThree", "Choose value no 3",
                               min=0, max=50, value=25))
)

# Define server logic 
server <- function(input, output) {
  output$myText <- renderText({input$choosemedia})
  
}
# Run the application 
shinyApp(ui = ui, server = server)

Any suggestion will be grately appreciated.




vendredi 21 octobre 2022

How to get checked event from checkbox in tableview with map items in javafx

I just want to get checked event from checkbox within tableview that has map items. I tried some code but it does not work. Thank you.

TableColumn<Map, Boolean> tableColumn = new TableColumn<>(fieldname);
tableColumn.setCellValueFactory(new MapValueFactory<>(fieldname));
tableColumn.setCellFactory(new Callback<TableColumn<Map, Boolean>, TableCell<Map, Boolean>>() {
public TableCell<Map, Boolean> call(TableColumn<Map, Boolean> p) {
                                    return new CheckBoxTableCell<Map, Boolean>();
                                }
                            });
tableColumn.setOnEditCommit(cellEvent -> {
         // Nothing happened here

                            });



jeudi 20 octobre 2022

How to get Checkbox status in Python?

I'm coding a Remember Username feature in Python with a checkbox for my application. Now I need to be able to get the status of the checkbox because when the user exits my application and then opens it again, while the username will still be remembered, the checkbox will look unticked. So I think I need to find a way to see if the checkbox is already selected from last time or not, and set REMEMBER_USERNAME to True or False accordingly.

I have not found an easy way to do so with the way my code is written.

GUI part, it's a bit too long so I've pasted it in a pastebin here https://pastebin.com/j8FEdA36

main.py

def RememberUsername(self):
    REMEMBER_USERNAME = True
    self.checkBox = ui.CheckBox()
    self.checkBox.SetParent(self)
    self.checkBox.SetEvent(ui.__mem_func__(self.SaveUsername), "ON_CHECK", True)
    self.checkBox.SetEvent(ui.__mem_func__(self.SaveUsername), "ON_UNCHECK", False)
    self.checkBox.SetCheckStatus(REMEMBER_USERNAME)
    self.checkBox.SetTextInfo("Remember username")
    self.checkBox.Show()

def SaveUsername(self, checkType, autoFlag):
    if REMEMBER_USERNAME = True:
        # remember the username
    else:
        # forget the username

Currently it's being done manually, e.g. when I define REMEMBER_USERNAME = True, the checkbox will always be ticked, when defined as False, the checkbox will be unticked, and so on.

I apologize if I sound all over the place, please let me know If you need any further clarification.




highlight row when checkbox in a particular column is checked or true

Hello Can anyone help me and show the script for highlighting a entire row when checkbox in column u is checked or true. this will apply to the whole workbook multiple sheets. check box is always in column u though. I know the custom formula for a single row but I have 1000 lines of data and want to use a script to apply to whole workbook. Please and thank you




Angular 8: Automatically check checkbox when a condition is matched

I'm working in a side panel filter for my page, I have the parent checkbox (Select all) and the children checkboxes(specific filters).

Here is what I want, if I select a children I want the parent checkbox to be partially checked, see image below:

link to example image

Currently this is my code, my parent checkbox ngModel is set to "dataSource.data.length == selectedAssetTypeFilters.length"

<mat-panel-title>

<mat-checkbox [(ngModel)]="dataSource.data.length == selectedAssetTypeFilters.length" (click)="$event.stopPropagation()" (keydown)="$event.stopPropagation()" (change)="onSelectAll($event, 'assettype')" title="Select All">Data Asset Type</mat-checkbox> </mat-panel-title> </mat-expansion-panel-header>

<div class="filter-content">

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">

<!-- This is the tree node template for leaf nodes -->

<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>

<li class="mat-tree-node">

<mat-checkbox [(ngModel)]="node.checked" (change)="onFilterUpdate(node, 'assettype');" title="">

How can I do this?




The update does not return the selected checkbox

I'm having an error updating the checkbox when I return to the view containing it; in particular it always returns me the first checked checkbox but not the values selected before the update.

Can anyone help me to solve this problem?

<div class="mb-3">
  <div for="treatment" class="form-label">All treatments</div>
  @foreach ($treatments as $treatment)
      <input type="checkbox" id="" name="treatments[]" value="" >
      <label for=""> </label><br>
  @endforeach
</div>



mercredi 19 octobre 2022

How to line up multiple checkboxes before text-containers in react and css?

              <input type="checkbox" class="checkbox" />{" "}
              <div className="textContainer">
                <img
                  "image"
                />
              "Text"
                <div className="date">MON 27 April 2020.</div>
                <div className="time"> 3:00 PM </div>
              </div>
         

I need the checkbox to come before and outside of the text- container.




mardi 18 octobre 2022

Mark as Completed Feature in React Native App

I am building an app where students can look at questions from previous years and study (no answers just question). I am using Sanity CMS as "backend" since this is just users studying questions and not really backend "heavy" web app. Anyways, I want to have a "mark as complete" feature which will be used to keep track of how many questions have been completed so that I can show it in the dashboard in a chart. Since there will be hundreds of questions, I am not sure of the best way to implement this feature. Also, if a question has already been marked completed, there will be a bright green color in the checkbox as compared to grey when unchecked. Is it even good to do with SanityCMS? Or should I use other db engine? Any idea on how to do this would be great. Thanks.




Checkbox default value


    <div class="form-group mb-2">
            <label asp-for="@Model.ProductDTO.Discontinued" class="col-sm-2 col-form-label">Discontinued</label>
            <input type="checkbox" asp-for="@Model.ProductDTO.Discontinued" name="Discontinued" />
        </div>

public bool? Discontinued { get; set; }


    InvalidOperationException: Unexpected 'asp-for' expression result type 'System.Nullable`1[[System.Boolean, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' for <input>. 'asp-for' must be of type 'System.Boolean' or 'System.String' that can be parsed as a 'System.Boolean' if 'type' is 'checkbox'.

The Discontinued model is NUllable so checkbox can be nullable. How can I do that?




Django crispy forms inline checkboxes

I am using Django-cripsy-forms to build a form. I have a model with several attributes (MultiSelectField) all with the same choices (CHOICES).

from django.db import models
class Visit(models.Model):
    CHOICES = (
        ("A","A"),
        ("B","B"),
        ("C","C"),
        ("D","D"),
    )

    q1 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q2 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q3 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q4 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q5 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q6 = MultiSelectField(null=True, choices=CHOICES, blank=True)

I want to make a form with checkboxes for each choice for all attributes. But to avoid clutter want to have the checkboxes in-line. Sort of like a questionnaire (example below)

enter image description here

I tried using django-crispy-forms InlineCheckboxes as shown below. But the checkboxes would never be displayed inline. But would be displayed as shown in the picture below. I also tried editing the styling of the labels and inputs of individual checkboxes but that also didn't work. What am I doing wrong? And is there a better way of doing this?

from django import forms
from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import InlineCheckboxes

class VisitForm(ModelForm):
    class Meta:
        model = Visit
        fields = '__all__'
        widgets = {
            'q1': forms.CheckboxSelectMultiple(),
            'q2': forms.CheckboxSelectMultiple(),
            'q3': forms.CheckboxSelectMultiple(),
            'q4': forms.CheckboxSelectMultiple(),
            'q5': forms.CheckboxSelectMultiple(),
            'q6': forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout (
            InlineCheckboxes("q1"),
            InlineCheckboxes("q2"),
            InlineCheckboxes("q3"),
            InlineCheckboxes("q4"),
            InlineCheckboxes("q5"),
            InlineCheckboxes("q6"),
        )

enter image description here

The html of this is the following

<div id="div_id_signal" class="control-group">
    <label for="id_signal" class="control-label">Q1</label>
<div class="controls">
    <label class="checkbox inline" for="id_signal_0">
        <input type="checkbox" name="signal" id="id_signal_0" value="A">
        A
        </label>
</div>
</div>



lundi 17 octobre 2022

I am trying to pass in a DISABLEDcheckbox value to the controller, but it does not seem to be passed

Below is the code to select all the server

<input type="checkbox" id="all_maintenace" class="checkbox " style="vertical-align: middle;"
 name="all_chkb_maintenace" value=""> Maintenace All </th>

Below is the code to select individually

<input type="checkbox" id="maintenace_" class="checkbox checkbox_maintenace"
 style="vertical-align: middle;" name="chkb_maintenace[]" value=""
 >
<input type="text" name="chkb_all_users[]" value="" hidden>

Below will be the code to disable / freeze the maintenance checkboxes

<input type="checkbox" id="freeze_" class="checkbox checkbox_freeze"
 style="vertical-align: middle;" name="frz_maintenace[]" value="">
<input type="text" name="chkb_all_users_frz[]" value="" hidden>

Below will be the script

$(document).on('click', '#all_maintenace', function() {
          var checkboxes = $('.checkbox_maintenace');
          var chk_value = $('.checkbox_maintenace').val();


          $.each(checkboxes, function(i, v) {
            var disabled = $(v).prop("disabled");
            var checked_length = $(v).is(":checked");

            $(v).prop("checked", $('#all_maintenace').prop("checked"));

            if (disabled && !checked_length) {
              $(v).prop('checked', false); // Unchecks it
            } else if (disabled && checked_length) {
              $(v).prop('checked', true); // Checks it
            }

          });
        });
    $(function() {
          $(".checkbox_freeze").on("change", function() {
            var ticked = $(this).val();
            const checked = this.checked;
            $("#maintenace_"+ticked).attr("disabled", checked)
          });
        });

controller:

$all_user = $request->chkb_all_users;
$selected_user = $request->has('chkb_maintenace') ? $request->chkb_maintenace : [];
$un_selected_user = array_diff($all_user, $selected_user);

So my question is how do i pass the to the controller the checkbox value that i have disabled/freeze, while the other checkboxes that i have not disabled/freeze are passed into the controller




Change state of a checkbox with addEventListener in JavaScript

I'm really new to JavaScript. I'm having some issues with my JavaScript code to change the state (checked or unchecked) of my checkbox input every time I click on an anchor element (the size and content is correct in CSS).

HTML simplified

<section>
  <a id="trigger"><img src="images/logo.png"></a>
  <input type="checkbox" id="nav-toggle">
</section>

JavaScript

let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
  let i = document.getElementById('nav-toggle');
  if(i.checked === false) {
     i.checked = true;
  } else {
    i.checked = false;
    }
  }
});

Let me know if my JavaScript code make sense, and what should I fix to make it work. Thanks!




dimanche 16 octobre 2022

Check checkbox with data from another database

I've been twisting my head for days without getting what I want, so I'm writing here hoping to get some help. I have two tables (actually 3, but we'll leave the last one out here).

TABLE 1 NAME:
pakkliste_gjenstand

COLUMNS:
id 
pakkliste_gjenstand


TABLE 2 NAME:
pakkliste_detalj

COLUMNS:
id
prosjekt_id 
pakkliste_detalj_gjenstand_id
pakkliste_detalj_gjenstand

In the "pakkliste_gjenstand" table there are hundres of lines with items that I can select by checkboxes, and add to the "pakkliste_detalj" table. The id-field from the "pakkliste_gjenstand"-table is stored in the "pakkliste_detalj"-table as pakkliste_detalj_gjenstand_id

Then we get to what I want, namely to run a reverse to be able to update my "pakkiste_detalj"-table. I want to be able to loop through the entire "pakkliste_gjenstand"-table, and check off the lines that are already selected in "pakkliste_detalj"-table. I need to match the id-field in table 1 (pakkliste_gjenstand) with pakkliste_detalj_gjenstand_id in table 2 (pakkliste_detalj).

I use the following code to loop throug the "pakkliste_gjenstand"-table:

<?php
$do_search=mysqli_query($link, "SELECT * FROM pakkliste_gjenstand ORDER BY pakkliste_gjenstand ASC");
while ($row = mysqli_fetch_array($do_search)) 
{
$id=$row['id'];
$produkt=$row['pakkliste_gjenstand'];
?>
<input type="checkbox" name="check_list[]" value="<?php echo $id; ?>*<?php echo $produkt; ?>"> <?php echo $produkt; ?>
<br>
<?php 
}
?>

Is it possible to do something with this so that I can have the items from "pakkliste_detalj" to be checked, but still show the rest of the lines as well?

I've searched the net, and tried different codes as LEFT JOIN, INNER JOIN and a lot other approaches without luck.

Could anyone help me? I don't want to use javascript ...




Create Check box's with different object name in Python

I am using XML file that has a set of elements inside. I want to create a check box for each element with different object name so the user can select only one of them and apply specific function for the selected one. so far I was able to loop inside the xml and create the check box's but all with the same object name but this is not good for me since each functionality is link to all selected.

my code looks like this:

import xml.etree.ElementTree as et
tree = et.parse('C:\Python_Projects\Jira_Rest\myviews.xml')
        num_reporters = tree.findall('.//view')

y=160
        p = 0
        for i in range(0, len(num_reporters)):
            view = (my_views[i].attributes['viewname'].value)

            self.checkbox = QtWidgets.QCheckBox(self.centralwidget)
            self.checkbox.setGeometry(QtCore.QRect(160, y, 211, 17))
            font = QtGui.QFont()
            font.setFamily("MS Shell Dlg 2")
            font.setPointSize(9)
            font.setBold(False)
            font.setItalic(False)
            font.setWeight(9)
            self.checkbox.setFont(font)
            self.checkbox.setStyleSheet("font: 75 9pt \"MS Shell Dlg 2\";")
            self.checkbox.setObjectName("checkBox" + str(p))
            self.v.setText(view)
            y+=40
            p=p+1



samedi 15 octobre 2022

Select Items and Sub Items using checkboxes

I'm working on a react native project and it has multiple item selection (only some items) component as below.

enter image description here

When the first time I select the values all the data will be stored correctly.

enter image description here

But When I remove the Items from the list, data will be cleared and I'm getting empty list.

My code as follows. I did lots of code changes and fixes but it won't work. Please help me to resolve this matter, Thanks in advance.

select sub categories :

const subCategotySelectionHandler = (subCategoryName, isItemChecked) => {
            console.log(selectedSubCategoryNames);
            if (isItemChecked && !selectedSubCategoryNames?.includes(subCategoryName)) {
                setSelectedSubCategoryNames([...selectedSubCategoryNames, subCategoryName]);
                setItemSelection(true);
                categorySelectHandler(item.category_name, item.value, true)
            }
            if (!isItemChecked && selectedSubCategoryNames.includes(subCategoryName)) {
                console.log(subCategoryName);
                setSelectedSubCategoryNames(selectedSubCategoryNames.filter(item => item !== subCategoryName));
                setSelectedSubCategoryNames(selectedSubCategoryNames.filter(item => console.log(item !== subCategoryName)));
          categorySelectHandler(null, null, false)
                 }
            }
        }

get the selected main categories :

 const categorySelectHandler = (categoryName, categoryValue, itemSelected) => {
                if (itemSelected) {
if (isItemChecked && !selectedCategoryName?.includes(categoryName)){
                // increaseSelectedTagCount();
                setSelectedCategoryName([...selectedCategoryName, categoryName]);
            }
                    setSelectedCategoryValue(categoryValue);
                } else {
                    if (isItemChecked && !selectedCategoryName?.includes(categoryName)){
                // decreaseSelectedTagCount();
                setCheckedTagItemList(selectedCategoryName.filter(item => item !== categoryName));
            }
                    setSelectedCategoryValue(null);
                }
            }

create the object to share with parent component,

useEffect(() => {
            console.log(selectedSubCategoryNames);
            let obj = {
                categoryName: selectedCategoryName,
                value: selectedCategoryValue,
                subCategoryList: selectedSubCategoryNames
            };
            getSelectedCategoriesObj(obj);
        }, [selectedCategoryName, selectedSubCategoryNames]);



jeudi 13 octobre 2022

Children checkbox not selected on Parent checkbox selection in React

In a React project, certain records which are fetched from JSON are displayed. It also has checkbox, with Parent checkbox on the table head. My intention is when Parent checkbox is selected all children checkbox should be selected. I have also referred other posts but, none had been useful.So I tried with one solution but, didn't work. Please refer to code below.

const [checkedAll, setCheckedAll] = useState(false);

  // Function for Parent checkbox
  const selectAllCallback = (checked) => {
    setCheckedAll(true);
  };

  // Function for Children checkbox
  const checkBoxSelect = (checked, id) => {
    if (checkedAll) {
      checked = true;
    }
  };

This is what I am trying to implement. What could be the best solution to tackle this?. Please refer to codesandbox link --> https://codesandbox.io/s/jovial-aryabhata-95o2sy?file=/src/Table.js




mercredi 12 octobre 2022

How to use React Native Paper Checkbox or Checkbox.Item using flat list?

You can only check and uncheck at once with the current source. I want to do it one by one... Help :( thank you!!

      const [checked, setChecked] = React.useState(false);

      const obdngList = 
      [ 
        {"a": "test1", "b": "test2", "c": "test3"}
      , {"a": "test111", "b": "test222", "c": "test333"}
      ];


                      <FlatList
                        data={obdngList}
                        renderItem={({ item }) => (
                          <Checkbox.Item 
                            label={item.a}
                            value={item.b}
                            status={checked ? 'checked' : 'unchecked'} 
                            onPress={() => {
                              setChecked(!checked)
                            }}
                          />
                        )}
                      />



Blazor InputCheckbox binding to string backing field

I am trying to make a dynamic form system and I want to be able to bind an InputCheckbox to a database field that's a string rather than a bool...

<InputCheckbox @bind-Value="@entry.Value" 
               class="form-check-inline" 
               style="width: 50px; height: 50px;"></InputCheckbox>

is what I am trying but entry.Value is a string and so this is giving me "Cannot convert string to bool"

Any ideas?

Thanks!




mardi 11 octobre 2022

How to create multiple input checkboxes, with a select all checkbox in function based react?

EXPLANATION

  • I have an array of objects.
  • They are being mapped and the data is being displayed on the screen.
  • I need to make it so that whenever a checkbox is clicked for a given object, that object is added to a new array. and when it is unclicked, it is removed from that array.
  • I also need a 'MAIN' checkbox that selects all items and adds them to the array when checked and removes all items when unchecked.

CODE EXPLANATION

// array of people objects

arrOfPersonObjs = [
    {id:1, name:'john, age:30,
    {id:2, name:'Lisa, age:34,
    {id:3, name:'Rob, age:30,
    {id:5, name:'Lucy, age:32,
    {id:5, name:'Tammy, age:38
    ]

// display JSX (this is psuedocode)
<input type='checkbox' className='SelectAll'/>
arrOfPersonObjs.map((curr)=>{
<input type='checkbox' className='SelectIndividualTicket/>
display curr.name
display curr.age
})
  • So as you can see, each object displayed will have a controlled checkbox associated with it.
  • There will also be a 'master' select all button.

QUESTIONS

  1. How do I set it up so that when an checkbox is checked, the input is marked as checked, and the person object that is associated with the checked checkbox is added to a new array.
  2. if an object is already in the array, and its button is checked(going from checked to no longer being checked), then the person obj is removed from the new array
  3. How do I create a selectAll checkbox that adds checked to all checkboxes when clicked... and adds them all to a new array.
  4. and if select all is already 'activated' and you click the selectAll checkbox again, all of the checkboxes and no longer marked as checked and are then removed from the new array.'

CURRENT FRUSTRATIONS

  • I havent found any up to date documentation that discusses my specific requirements
  • working with a single checkbox is relatively straightforward, but things get confusing when it comes to multiple checkboxes because I dont know how to keep track of which checkboxes have been marked as checked. and which hasn't.



lundi 10 octobre 2022

PHP: How to check more then one row for check a checkbox

I would like to check a checkbox if I have integer 1 stored in row a or b.

For now I created a working version to check for row 'a'. How can I check also for row 'b'? So as said above if row a or/and b has integer 1 stored check the checkbox.

<input type="checkbox" name="a" id="a" value="1" <?php if($row['a'] == "1") { echo "checked"; }?>>



dimanche 9 octobre 2022

how to do it ?-> Among the two checkboxes in a row, the user can select only one checkbox at a time

in flutter -> Among the two checkboxes in a row, the user can select only one checkbox at a time. how can i do it.here i have use ("RoundCheckBoxCus" because i need this type of round checkbox with icon) checkbox package. ...from my code user can select 2checkbox at a time, but i need only one can select at a time.in a row.

please check my code->

 Container(
                    margin: EdgeInsets.only(
                        top: ScreenUtil().setHeight(352),
                        left: MediaQuery.of(context).size.width * 0.72),
                    child: Row(
                      children: <Widget>[
                        // SizedBox(
                        //   height: 540.h,
                        // ),
                        SizedBox(
                          width: 13.w,
                        ),
                        Container(
                          child: RoundCheckBoxCus(
                            onTap: (selected) => print(selected),
                            uncheckedColor: Colors.transparent,
                            uncheckedWidget: Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                    color: Colors.transparent,
                                  ),
                                  borderRadius: BorderRadius.all(Radius.circular(20.sp))
                              ),
                              child:  Icon(Icons.check,size:15.sp,),
                            ),
                            size: 19.w,
                          ),
                        ),
                        SizedBox(width: 30.w,),
                        Container(
                          child: RoundCheckBoxCus(

                            onTap: (selected) => {
                            setState(() {
                            isChecked = true;
                            },
                            )},
                            uncheckedColor: Colors.transparent,
                            uncheckedWidget: Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                    color: Colors.transparent,
                                  ),
                                  borderRadius: BorderRadius.all(Radius.circular(20.sp))
                              ),
                              child:  Icon(Icons.check,size:15.sp,),
                            ),
                            size: 19.w,
                          ),
                        ),
                        SizedBox(
                          width: 13.w,
                        ),
                      ],
                    ),
                  ),

in flutter -> Among the two checkboxes in a row, the user can select only one checkbox at a time. how can i do it.here i have use RoundCheckBoxCus checkbox package




how to create the blue border on checkbox when mouse is over the containing element C# WPF

I have a WrapPanel containing a Label and a CheckBox; when the MouseLeftButtonUp event is triggered on the wrappanel, the checkbox is checked. The idea is to make label and the checkbox look like 1 element.

Now, the CheckBox element has this feature, that when the mouse is hovering over it, it gets surrounded by a blue border. in my case, the checkbox only takes that blue border to itself when the checkbox is directly hovered by the mouse (not the entire wrappanel). I need my checkbox to get this blue border when the mouse is over the wrappanel, not only the checkbox itself.

I tried to call the myCheckbox.Focus(); when the MouseEnter for the wrappanel is triggered, but didn't do the trick.

And I also saw this link on how to checkbox focus border apear when calling CheckBox.Focus() But it doesn't contain a solution either.

Any help is appreciated.




vendredi 7 octobre 2022

ASP.NET TreeView checkboxes behave as Radio Buttons

I'm using a TreeView Control on ASP.NET with C#, and needs to make all the nodes (Roots and Leafs) with checkboxes. Then, I need these checkboxes to work as Radio Buttons so when clicking on one checkbox, the previously checked checkbox is now unchecked and the new one is becoming checked.

My work on this problem was first to add showCheckBoxes="All" attribute to the asp:TreeView then to use the TreeView1_TreeNodeCheckChanged event. However, this event is not triggered automatically and needs a postback for the page to fire up! So I used a javascript function to make it fire up as recommended on similar posts in stackoverflow.com but for different problems.

<script type="text/javascript">
    function postBackByObject() {
        var o = window.event.srcElement;
        if (o.tagName == "INPUT" && o.type == "checkbox") {
            __doPostBack("", "");
        }
    }
</script>


protected void Page_Load(object sender, EventArgs e)
        {
          TreeView1.Attributes.Add("onclick", "postBackByObject()");    
        }

However, still I couldn't figure out how to write the TreeNodeCheckChanged function to make the previously checked checkbox unchecked , and make the new one checked! As the post back action is making a confusion for me.

Thanks in Advance




How to set a cell value to zero if checkbox is checked

I have a sheet I and I want to have the values in one row be set to zero once the corresponding checkbox is clicked. Here is what my sheet looks like(https://postimg.cc/CBDdYsjN), I want each cell in column E to be set to zero when its same row checkbox in col A is set to true.




how to insert multiple row data based on checkbox selection in Laravel

hope you all are doing well. I'm stuck with multiple row insertion in laravel. I keep on getting an error which says: Trying to access array offset on value of type null. My code is below as follows;

blade.php file:

<tbody>
                             
                            @forelse($GIV as $GIV)
                                <tr>
                                    <td> <input type="checkbox" name="status[]" id="status" value="Issued" ></td>
                                    <td> <input type="text"   class="form-control"   id="id"   name="item_id[]"  hidden="" value=""></td>
                                    <td> <input type="text"   class="form-control"   id="pr_no"          name="pr_no[]"          hidden="" value=""></td>
                                    <td> <input type="text"   class="form-control"   id="dep_name"       name="dep_name[]"       hidden="" value=""></td>
                                    <td> <input type="hidden"   class="form-control"   id="item_name"      name="item_name[]"    value=""></td>
                                    <td> <input type="text"   class="form-control"   id="description"    name="description[]"    hidden="" value="" ></td>
                                    <td> <input type="number" class="form-control"   id="item_qty"       name="item_qty[]"       hidden="" value=""></td>
                                    <td> <input type="text"   class="form-control"   id="unit_measure"   name="unit_measure[]"   hidden="" value=""></td>
                                    <td> <input type="number" class="form-control"   id="authorized_qty" name="authorized_qty[]" hidden="" value=""></td>
                                    
                                </tr>
                             
                                @empty
                                <tr><td colspan="16"><center>No Data Found</center</td></tr>
                                @endforelse </tbody>                                                                    

Control file:

public function addDataGIV(Request $request)
{
   $data =request()->all;
    foreach(request()->status as $status)
    {
        DB::table('g_i_v_s')
        ->insert(
            [
                
                'item_id'       =>$data['item_id'][$status],
                'item_name'     =>$data['item_name'][$status],
                'description'   =>$data['description'][$status],
                'item_qty'      =>$data['item_qty'][$status],
                'unit_measure'  =>$data['unit_measure'][$status],
                'authorized_qty'=>$data['authorized_qty'][$status],
                'dep_name'      =>$data['dep_name'][$status],
                'pr_no'         =>$data['pr_no'][$status],
                ]
                );
     }
   }

When a user selects the checkbox and clicks the submit button, I want only the selected checkbox row including the checkbox value to be stored into the database, without any errors. I kindly ask for help.

Thanks, in advance :)




Increase checkbox dimension in listview c# [duplicate]

everyone, I am using a listview within which there are chekboxes. I can't find a way to increase their size. I tried setting the height and width, but that didn't work. I attach the code of the listview which also contains all the customizations made (not by me). This is the code of the listview:

        <ListView x:Name="ProgramsList" ItemsSource="{Binding lPD}" Foreground="White" HorizontalAlignment="Center" Height="519" Margin="0,392,0,0" VerticalAlignment="Top" Width="1216" FontFamily="Sanuk Offc Light" FontSize="14">
            <ListView.View>
                <GridView>
                    <GridViewColumn x:Name="PinOrder" Header="Order" Width="100" DisplayMemberBinding="{Binding OrderPin}"/>
                    <GridViewColumn x:Name="Pin" Header="Pin" Width="205" DisplayMemberBinding="{Binding Pin}"/>
                    <GridViewColumn x:Name="ProfiloSaldatura" Header="Profilo saldatura" Width="205" DisplayMemberBinding="{Binding SolderingProfile}"/>
                    <GridViewColumn x:Name="AbilitaPuliziaPrimaDelPunto" Header="Pulizia prima del punto" Width="205">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Margin="5,0" IsChecked="{Binding EnableCleaningBeforePoint}" Checked="EnableCleaningBeforePoint_Checked" Unchecked="EnableCleaningBeforePoint_Unchecked"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn x:Name="AbilitaPuliziaDopoIlPunto" Header="Pulizia dopo il punto" Width="205">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Margin="5,0" IsChecked="{Binding EnableCleaningAfterPoint}" Checked="EnableCleaningAfterPoint_Checked" Unchecked="EnableCleaningAfterPoint_Unchecked"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn x:Name="AbilitaPrestagnaturaPrimaDelPunto" Header="Prestagnatura prima del punto" Width="205">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Margin="5,0" IsChecked="{Binding EnablePresolderingBeforePoint}" Checked="EnablePresolderingBeforePoint_Checked" Unchecked="EnablePresolderingBeforePoint_Unchecked"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

Qui sotto invece allego tutte le personalizzazione fatte:

    <Window.Resources>
        <!--Control colors.-->

        <Color x:Key="ContentAreaColorLight">#FFC5CBF9</Color>
        <Color x:Key="ContentAreaColorDark">#FF7381F9</Color>

        <Color x:Key="DisabledControlLightColor">#FFE8EDF9</Color>
        <Color x:Key="DisabledControlDarkColor">#FFC5CBF9</Color>
        <Color x:Key="DisabledForegroundColor">#FF888888</Color>

        <Color x:Key="SelectedBackgroundColor">#046beb</Color>
        <Color x:Key="SelectedUnfocusedColor">#046beb</Color>

        <Color x:Key="ControlLightColor">#666769</Color>
        <Color x:Key="ControlMediumColor">#666769</Color>
        <Color x:Key="ControlDarkColor">#2b2929</Color>

        <Color x:Key="ControlMouseOverColor">#046beb</Color>
        <Color x:Key="ControlPressedColor">#046beb</Color>


        <Color x:Key="GlyphColor">#FF444444</Color>
        <Color x:Key="GlyphMouseOver">sc#1, 0.004391443, 0.002428215, 0.242281124</Color>

        <!--Border colors-->
        <Color x:Key="BorderLightColor">#F5F5F5</Color>
        <Color x:Key="BorderMediumColor">#FFFFFF</Color>
        <Color x:Key="BorderDarkColor">#FFFFFF</Color>

        <Color x:Key="PressedBorderLightColor">#046beb</Color>
        <Color x:Key="PressedBorderDarkColor">#046beb</Color>

        <Color x:Key="DisabledBorderLightColor">#046beb</Color>
        <Color x:Key="DisabledBorderDarkColor">#046beb</Color>

        <Color x:Key="DefaultBorderBrushDarkColor">Black</Color>

        <!--Control-specific resources.-->
        <Color x:Key="HeaderTopColor">#FFC5CBF9</Color>
        <Color x:Key="DatagridCurrentCellBorderColor">Black</Color>
        <Color x:Key="SliderTrackDarkColor">#FFC5CBF9</Color>

        <Color x:Key="NavButtonFrameColor">#FF3843C4</Color>

        <LinearGradientBrush x:Key="MenuPopupBrush" EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="{DynamicResource ControlLightColor}" Offset="0" />
            <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="0.5" />
            <GradientStop Color="{DynamicResource ControlLightColor}" Offset="1" />
        </LinearGradientBrush>

        <LinearGradientBrush x:Key="ProgressBarIndicatorAnimatedFill"
                     StartPoint="0,0"
                     EndPoint="1,0">
            <LinearGradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="#000000FF" Offset="0" />
                    <GradientStop Color="#600000FF"
                    Offset="0.4" />
                    <GradientStop Color="#600000FF"
                    Offset="0.6" />
                    <GradientStop Color="#000000FF"
                    Offset="1" />
                </GradientStopCollection>
            </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>

        <Style x:Key="{x:Static GridView.GridViewScrollViewerStyleKey}"
       TargetType="ScrollViewer">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ScrollViewer">
                        <Grid Background="{TemplateBinding Background}">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>

                            <DockPanel Margin="{TemplateBinding Padding}">
                                <ScrollViewer DockPanel.Dock="Top"
                          HorizontalScrollBarVisibility="Hidden"
                          VerticalScrollBarVisibility="Hidden"
                          Focusable="false">
                                    <GridViewHeaderRowPresenter Margin="2,0,2,0"
                                          Columns="{Binding Path=TemplatedParent.View.Columns,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          ColumnHeaderContainerStyle="{Binding
                Path=TemplatedParent.View.ColumnHeaderContainerStyle,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          ColumnHeaderTemplate="{Binding
                Path=TemplatedParent.View.ColumnHeaderTemplate,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          ColumnHeaderTemplateSelector="{Binding 
                Path=TemplatedParent.View.ColumnHeaderTemplateSelector,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          AllowsColumnReorder="{Binding
                Path=TemplatedParent.View.AllowsColumnReorder,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          ColumnHeaderContextMenu="{Binding
                Path=TemplatedParent.View.ColumnHeaderContextMenu,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          ColumnHeaderToolTip="{Binding
                Path=TemplatedParent.View.ColumnHeaderToolTip,
                RelativeSource={RelativeSource TemplatedParent}}"
                                          SnapsToDevicePixels="{TemplateBinding
                SnapsToDevicePixels}" />
                                </ScrollViewer>

                                <ScrollContentPresenter Name="PART_ScrollContentPresenter"
                                    KeyboardNavigation.DirectionalNavigation="Local"
                                    CanContentScroll="True"
                                    CanHorizontallyScroll="False"
                                    CanVerticallyScroll="False" />
                            </DockPanel>

                            <ScrollBar Name="PART_HorizontalScrollBar"
                     Orientation="Horizontal"
                     Grid.Row="1"
                     Maximum="{TemplateBinding ScrollableWidth}"
                     ViewportSize="{TemplateBinding ViewportWidth}"
                     Value="{TemplateBinding HorizontalOffset}"
                     Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" />

                            <ScrollBar Name="PART_VerticalScrollBar"
                     Grid.Column="1"
                     Maximum="{TemplateBinding ScrollableHeight}"
                     ViewportSize="{TemplateBinding ViewportHeight}"
                     Value="{TemplateBinding VerticalOffset}"
                     Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" />

                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="GridViewColumnHeaderGripper"
       TargetType="Thumb">
            <Setter Property="Width"
          Value="18" />
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush StartPoint="0,0"
                           EndPoint="0,1">
                        <LinearGradientBrush.GradientStops>
                            <GradientStopCollection>
                                <GradientStop Color="{DynamicResource BorderLightColor}"
                          Offset="0.0" />
                                <GradientStop Color="{DynamicResource BorderDarkColor}"
                          Offset="1.0" />
                            </GradientStopCollection>
                        </LinearGradientBrush.GradientStops>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Border Padding="{TemplateBinding Padding}"
                Background="Transparent">
                            <Rectangle HorizontalAlignment="Center"
                     Width="1"
                     Fill="{TemplateBinding Background}" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1"
                           StartPoint="0.5,0">
                        <GradientStop Color="Black"
                      Offset="0" />
                        <GradientStop Color="White"
                      Offset="1" />
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="{x:Type GridViewColumnHeader}"
       TargetType="GridViewColumnHeader">
            <Setter Property="HorizontalContentAlignment"
          Value="Center" />
            <Setter Property="VerticalContentAlignment"
          Value="Center" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="GridViewColumnHeader">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal" />
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="HeaderBorder">
                                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource ControlMouseOverColor}" />
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Pressed" />
                                    <VisualState x:Name="Disabled" />
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Border x:Name="HeaderBorder" BorderThickness="0,0,0,1" Padding="2,1,2,0" Height="20" Margin="0,0,0,0">
                                <Border.BorderBrush>
                                    <LinearGradientBrush StartPoint="0,0"
                                   EndPoint="0,1">
                                        <LinearGradientBrush.GradientStops>
                                            <GradientStopCollection>
                                                <GradientStop Color="{DynamicResource BorderLightColor}"
                                  Offset="0.0" />
                                                <GradientStop Color="{DynamicResource BorderDarkColor}"
                                  Offset="1.0" />
                                            </GradientStopCollection>
                                        </LinearGradientBrush.GradientStops>
                                    </LinearGradientBrush>
                                </Border.BorderBrush>
                                <Border.Background>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                        <LinearGradientBrush.GradientStops>
                                            <GradientStopCollection>
                                                <GradientStop Color="{DynamicResource ControlLightColor}" Offset="0.0" />
                                                <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1.0" />
                                            </GradientStopCollection>
                                        </LinearGradientBrush.GradientStops>
                                    </LinearGradientBrush>
                                </Border.Background>
                                <ContentPresenter x:Name="HeaderContent" Margin="0,0,0,1" RecognizesAccessKey="True" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Border>
                            <Thumb x:Name="PART_HeaderGripper" HorizontalAlignment="Right" Margin="0,0,-9,0" Style="{StaticResource GridViewColumnHeaderGripper}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Role"
             Value="Floating">
                    <Setter Property="Opacity"
              Value="0.7" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="GridViewColumnHeader">
                                <Canvas Name="PART_FloatingHeaderCanvas">
                                    <Rectangle Fill="#60000000" Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding ActualHeight}" />
                                </Canvas>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
                <Trigger Property="Role" Value="Padding">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="GridViewColumnHeader">
                                <Border Name="HeaderBorder" BorderThickness="0,0,0,1">
                                    <Border.Background>
                                        <SolidColorBrush Color="{DynamicResource ControlLightColor}" />
                                    </Border.Background>
                                    <Border.BorderBrush>
                                        <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                            <LinearGradientBrush.GradientStops>
                                                <GradientStopCollection>
                                                    <GradientStop Color="{DynamicResource BorderLightColor}" Offset="0.0" />
                                                    <GradientStop Color="{DynamicResource BorderDarkColor}" Offset="1.0" />
                                                </GradientStopCollection>
                                            </LinearGradientBrush.GradientStops>
                                        </LinearGradientBrush>
                                    </Border.BorderBrush>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>

        <Style x:Key="{x:Type ListView}" TargetType="ListView">
            <Setter Property="SnapsToDevicePixels" Value="true" />
            <Setter Property="OverridesDefaultStyle" Value="true" />
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
            <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
            <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListView">
                        <Border Name="Border" BorderThickness="1">
                            <Border.Background>
                                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                    <GradientStop Color="#666769" Offset="0" />
                                    <GradientStop Color="#2b2929" Offset="1" />
                                </LinearGradientBrush>
                            </Border.Background>
                            <Border.BorderBrush>
                                <SolidColorBrush Color="{StaticResource BorderMediumColor}" />
                            </Border.BorderBrush>
                            <ScrollViewer Style="{DynamicResource
                                {x:Static GridView.GridViewScrollViewerStyleKey}}">
                                <ItemsPresenter />
                            </ScrollViewer>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsGrouping" Value="true">
                                <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter TargetName="Border" Property="Background">
                                    <Setter.Value>
                                        <SolidColorBrush Color="{DynamicResource DisabledBorderLightColor}" />
                                    </Setter.Value>
                                </Setter>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="{x:Type ListViewItem}" TargetType="ListViewItem">
            <Setter Property="SnapsToDevicePixels" Value="true" />
            <Setter Property="OverridesDefaultStyle" Value="true" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Height" Value="30" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border x:Name="Border" Padding="2" SnapsToDevicePixels="true" Background="Transparent">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal" />
                                    <VisualState x:Name="MouseOver" />
                                    <VisualState x:Name="Disabled" />
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="SelectionStates">
                                    <VisualState x:Name="Unselected" />
                                    <VisualState x:Name="Selected">
                                        <Storyboard>
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource SelectedBackgroundColor}" />
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="SelectedUnfocused">
                                        <Storyboard>
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                                <EasingColorKeyFrame KeyTime="0" Value="{StaticResource SelectedUnfocusedColor}" />
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>



mercredi 5 octobre 2022

Delete all checked rows using axios in React

I have a react table rendering data that i can get using axios from mysql database. each table row has checkbox. i can check/uncheck all checkboxes using that checkbox in thead.

i need to write code for the the function deleteAll() and call it onClick event of the Delete button( THIS WILL GET VALUES OF ALL CHECKED CHECKBOXES AND PASS IT TO THE API TO DELETE THOSE RECORDS HAVING THOSE VALUES AS IDS)

as i am new to react, i need your help.

here is my code

import React from "react";
import axios from "axios";
import { useState, useEffect} from "react";
import { Link } from "react-router-dom";
import Table from 'react-bootstrap/Table'
import Dashboard from "../login/dashboard";
import { toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

const UserGroup = () => {

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

    function dataRender(item, index) {

        return (
            <tr key={index +1}>
                <td className="text-center"><input 
                        type="checkbox" className="form-check-input"
                        key={item.id}
                        id={item.id}
                        name={item.id}
                        value={item.id}
                        checked={item?.isChecked || false}
                        onChange={handleChange}
                        /></td>
                <td className="text-center">{index + 1}</td>
                <td className="text-center">{item.id}</td>
                <td className="text-left">{item.name_eng}</td>
                <td className="text-right">{item.name}</td>
                <td className="text-center">{(item.active == 1) ? 'Yes' : 'No'}</td>
            </tr>
        )
      }

    useEffect(() =>{
        loadData();
    }, [])

    const loadData = async ()=>{
        await axios.get('http://localhost/sits_api/sysAdmin/userGroup.php')
        .then((result)=>{
            setData(result.data);
        })
    }


    const deleteAll = ()=>{
     // I NEED TO CODE THIS FUNCTION
    }
    
     
    // hand CHECK ALL CHECKBOXES
    const handleChange = (e) => {
        const {name, checked} = e.target;

        if(name==="allSelect")
            {
                let tempItem = data.map((item) => {
                    return {...item, isChecked: checked }
                });
                setData(tempItem);
            }
        else
            {
                let tempItem = data.map((item) =>
                item.id === name ? {...item, isChecked: checked } : item
                );
                setData(tempItem);
            }
    }
    /////////////////////
    return(
        <>
            <Dashboard/>

            <div className="div-content">
                <div>
                    <label className="headline">User Groups List</label>
                    <nav className="navbar navbar-expand-bg navbar-light">
                        <div className="container">
                            <Link className="btn btn-primary" to={'/usergroupadd'}>Add New</Link>
                            <Link className="btn btn-danger" to=''onClick={() => {deleteAll()}}>Delete</Link>
                        </div>
                    </nav>                  
                </div>

                <Table striped bordered hover>
                    <thead>
                        <tr>
                            <th className="text-center"><input
                                type="checkbox" className="form-check-input"
                                name="allSelect"
                                checked={data.filter((item) => item?.isChecked !== true).length < 1}
                                onChange={handleChange}
                                /></th>
                            <th className="text-center">#</th>
                            <th className="text-center">ID</th>
                            <th className="text-left">Eng. Name</th>
                            <th className="text-right">الاسم العربى</th>
                            <th className="text-center">Active</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map(dataRender)}
                    </tbody>
                </Table>
            </div>
        </>
    );
}
export default UserGroup;



Angular Dynamic Nested Checkbox selection Problem

I was working on a multi-step complex registration form and I am stuck because i am facing this issue. there is a dynamic dependent nested checkbox and when i select the parent the child check box renderes without a problem but when i select a child check box and the try to select a parent box the child box will all get checked. is there any way to fix this?

my component.ts

export class SubCategoriesComponent  {
  form!: FormGroup
  @Input('subcategories') set _(value: any) {
    this.form = value as FormGroup;
  }
  @Input() mainCategoryList!: Observable<any[]>;

  isSelected = false;


  subCategoryInfo!: SubCategory[];
  subCategorycheck!: SubCategory[];

  checkedList: any;
  masterSelected!: boolean;

  constructor() { }

//   ngOnInit(): void {
//         console.log(this.mainCategoryList);
//     this.getSubCategories();
// }

  ngOnChanges(changes: SimpleChanges): void {
    //Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
    //Add '${implements OnChanges}' to the class.
    console.log(changes);
    if(changes.mainCategoryList && changes.mainCategoryList.currentValue) {
      let subCategoryInfo = changes.mainCategoryList.currentValue;
      this.getSubCategories(subCategoryInfo);
    }
  
  }

  getSubCategories(subCategoryInfo: SubCategory[]){
    of(subCategoryInfo).pipe(map((item:SubCategory[])=>item),
      map((items:any) =>
       items.map((item:SubCategory) => {
            let data = {
              id: item.id,
              name: item.name,
              subCategories: item.subCategories,
              // isSelected: item.isSelected
            }
            return data;
       }
    
    ))).subscribe((response:SubCategory[])=>{
      this.subCategoryInfo = response;

      this.subCategoryInfo.forEach(element => {

        this.subCategorycheck = element.subCategories
      });
    console.log(this.subCategoryInfo);
    console.log(this.subCategorycheck);

    })
  }

  
  // The master checkbox will check/ uncheck all items
  checkUncheckAll() {
    for (var i = 0; i < this.subCategorycheck.length; i++) {
      this.subCategorycheck[i].isSelected = this.masterSelected;
    }
    this.getCheckedItemList();
  }

  // Check All Checkbox Checked
  isAllSelected() {
    console.log(this.subCategorycheck);
    this.masterSelected = this.subCategorycheck.every(function (item: any) {
      console.log(item);
      return item.isSelected == true;
    })
    this.getCheckedItemList();
  }

  // Get List of Checked Items
  getCheckedItemList() {
    this.checkedList = [];
    for (var i = 0; i < this.subCategorycheck.length; i++) {
      if (this.subCategorycheck[i].isSelected)
        this.checkedList.push(this.subCategorycheck[i]);
    }
    // this.mainCategoriesCheckedList.emit(this.checkedList);
    console.log(this.checkedList);
  }

}

my component.html

<form [formGroup]="form" >

<nz-checkbox-wrapper style="width: 100%;"
*ngFor="let data of subCategoryInfo;">
<!-- <div class="container" *ngIf="data.subCategories.length !== 0"> -->
  <h6 style="text-align: left; margin-top: 10px;">
    </h6>
<!-- </div> -->
  <div class="form-check row"
    *ngFor="let d of data.subCategories;">
    <input formControlName="subCategoryId"
    (change)="isAllSelected()"
    class="form-check-input" type="checkbox"
      value="" required
      ><label for="option-"></label>

  </div>

</nz-checkbox-wrapper>
</form>

i didn't bind the ngModel because that is what I need your help with on how to do it with out causing the problem i mentioned. Thanks in advance.