samedi 31 juillet 2021

React custom checkbox input component not rerendering

I'm extracting my checkbox input to separate custom component so I can easily reuse it later. But whenever the state on the parent changes, the checked value inside this custom component is not changing. It's actually changing when I move page first and open it later but not in real-time. But when I use default input component it works in real-time. Any idea how's this possible?

import React from 'react';

const Checkbox = ({ name, id, className, onValueChange, defaultChecked = false }) => {
  let classes = 'checkbox';

  if (className) {
    classes += ` ${className}`;
  }

  const valueChangeHandler = (event) => {
    if (onValueChange) {
      onValueChange(event.target.checked);
    }
  };

  return (
    <input 
      type="checkbox"
      name={ name }
      id={ id }
      className={ classes }
      defaultChecked={ defaultChecked }
      onChange={ valueChangeHandler }
    />
  );
};

export default Checkbox;



How to keep transparency on a custom painted Checkbox control

I have the problem to create an owner drawn checkox as I don't like the check styles. Subclassing the Winform checkbox is not the big deal and overpainting the checkbox itself easy. But I don't like the position of the text as there are no properties for positioning it.

So basically, clear the control's graphic, paint the checkbox AND the text how and where I like.

Just, not working as clearing the graphic results in a black rectangle and you loose the transparency. But without clearing or overpainting client area, original text will always overlap owner drawn text.

Any solutions?




Transparent, custom checkbox with owner drawn text

I had the problem to create an owner drawn checkox as I didnt like the check styles. Subclassing the Winform checkbox is no big deal and overpainting the checkbox itself easy. But I didnt like the position of the text and there are no properties for positioning it.

So basically, clear the control's graphics and paint all new. Just, not working as you loose then the transparency. But without overpainting, original text painting was always overlapped owner draw text.

The solution was to set control's text to string.empty, call the base OnPaint method and override the OnTextChange event. That's it. Now I can draw the text exactly how I want and control is still transparent:

    class mycheckBox
    {
        private string _Text;

        protected override void OnTextChanged(EventArgs e)
        {
         // Prevent calling paint method on text change
        }

       protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
       {
        _Text = this.Text;
        this.Text = string.empty;
        base.OnPaint(e);
        Text = _Text; 

        // do your drawing here
        }
    }



vendredi 30 juillet 2021

Blazor InputCheckBox

So the overall goal is I want to have check boxes on a form that all the different Patterns and the different types of cuts (Mens, Womens, Universal) and I want to be able to check Patterns x, y, and z then cut type Mens and Womens. Then pass or access the values I have checked to a method that then does all of the unique configurations. That then calls my Data Access Library and saves them to my SQL Server.

I have my insert one Pattern at a time working by getting data from a drop down populated by a hard coded list using EditForms then calling my InsertPattern Function.

I am not sure how to use the InputCheckBox option in Blazors EditForms. I understand it has to be tied to a boolean so I tried creating two lists of booleans to match my PatternName and CutType / Gender but it seems that is not the way to approach it.

I had read previously that I have to setup a onChange function to work with my edit form. It this supposed to be the one that calls the boolean list associated to my PatternName and Patterncut lists?

So My real question is how do I approach setting up these input check box? Below is the examples of my lists and models. Pattern model has 4 parts PatternID the PK PatternName, PatternType and Inactive which is just for future implementation. Of course my callInserts will need to be changed but once I figure out how to use the input checkboxes correctly I should know how to do it.

    @page "/Pattern"

@using DataAccessLibrary
@using DataAccessLibrary.Models

@inject IPatternData _db


<h4>Current Patterns </h4>
@if (patternList is null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Pattern Name</th>
                <th>Pattern Cut</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var CurrentPatterns in patternList)
            {
                <tr>
                    <td>@CurrentPatterns.PatternName</td>
                    <td>@CurrentPatterns.PatternCut</td>
                </tr>
            }
        </tbody>
    </table>
}
<h3>Insert Patterns</h3>
<EditForm Model=@newPattern OnValidSubmit=@InsertPattern>
    <ValidationSummary />


    <InputSelect @bind-Value=newPattern.PatternName>
        <option value=" ">"..."</option>
        @foreach (string patName in AllPatternNames)
        {
            <option value=@patName>@patName</option>
        }
    </InputSelect>
    <InputSelect @bind-Value=newPattern.PatternCut>
        <option value=" ">"..."</option>
        @foreach (string cut in Gender)
        {
            <option value=@cut>@cut</option>
        }
    </InputSelect>

    <button type="submit" class="btn btn-primary"> Submit</button>
</EditForm>

<h3>Insert Patterns V2</h3>
<EditForm Model=@newPattern OnValidSubmit=@CallInserts>
    <ValidationSummary />
    @foreach (string patName in AllPatternNames)
    {
        <label>@patName</label>
        <InputCheckbox @bind-Value=@patName />

    }
    @foreach (string cut in Gender)
    {
        <label>@cut</label>
        <InputCheckbox @bind-Value=@cut />

    }



    <button type="submit" class="btn btn-primary"> Submit</button>
</EditForm>
@*@foreach (var cutType in Gender)
{
    <input type="checkbox" />
    @cutType
}

@foreach (var patternName in AllPatternNames)
{
    <input type="checkbox" />
    @patternName
}*@



@code {


    private List<PatternModel> patternList;
    private PatternModel newPattern = new PatternModel();
    private List<string> AllPatternNames = new List<string> {"Middle Weight Coverall",
   "Light Weight Coveral",
    "Winter Coverall",
    "Arctic Coverall",
    "Button Up Workshirt",
    "Henley Shirt’",
    "Welders Shirt",
    "Daily Bib",
    "Winter Bib",
    "Arctic Bib",
    "Jeans",
    "Work Pants",
    "Tactical Pant",
    "Parka",
    "Bomber",
    "Frost Jacket",
    "Fleece  ¼ / full zip",
    "Hat Liner",
    "Balaclava",
    "Lab Coats" };

    public List<string> Gender = new List<string>
{
        "Men",
        "Women",
        "Universal"
    };

    private List<bool> selectedPatterns = new List<bool>
{
        false, false, false, false, false,false, false, false, false, false,false, false, false, false, false,false, false, false, false, false,false, false, false, false, false,false, false, false, false, false
    };
    private List<bool> selectedCut = new List<bool> { false, false, false };

    protected override async Task OnInitializedAsync()
    {
        patternList = await _db.Get();

    }

    private async Task InsertPattern()
    {

        PatternModel NP = new PatternModel
        {
            PatternCut = newPattern.PatternCut,
            PatternName = newPattern.PatternName
        };

        await _db.Insert(NP);
        patternList.Add(NP);
        newPattern = new PatternModel();

    }
    private void CallInserts()
    {
        for (int i = 0; i < Gender.Count; i++)
        {
            if (selectedCut[i] == true)
            {
                for (int x = 0; i < AllPatternNames.Count; x++)
                {
                    if (selectedPatterns[x] == true)
                    {
                        PatternModel NP = new PatternModel
                        {
                            PatternCut = Gender[i],
                            PatternName = AllPatternNames[i]
                        };
                        patternList.Add(NP);
                        newPattern = new PatternModel();
                        //newPattern.PatternCut = Gender[i];
                        //newPattern.PatternName = AllPatternNames[i];
                    }
                }
            }
            //await InsertPattern();
        }
    }



    //private List<ClosuresModel> closure;

}

If any more info is needed please let me Know!!




Checkbox FOR loop array in VBA

I have a word document with 100+ checkboxes. It is an ActiveX object. The Checkbox1.Caption is the GroupName. If a Checkbox is checked (Checkbox1.Value = True) then I want to display that GroupName in a Message Box to allow the user to easily copy groups as text that are checked without having to scan the whole document. My code works fine, except that I have Set each CheckBox to allow it to be used in array for FOR loop. I'd like to use a for Loop to pass all Checkbox objects into an array which I can then use in the code

'Set CBox(1) = CheckBox1
'Set CBox(2) = CheckBox2
'Set CBox(3) = CheckBox3

 Dim iCount As Integer
 Dim CheckBox As String

 For iCount = 1 To 3
 CBox(iCount) = "CheckBox" & iCount
 Next iCount

 Dim Grp(1 To 50) As String
 Dim GrpText(1 To 5) As String

 Dim i As Integer
 Dim j As Integer
 Dim k As Integer

 For i = 1 To 3
 If CBox(i).Value = True Then Grp(i) = CBox(i).Caption & ";" Else Grp(i) = ""
 Next i

 For j = 1 To 5
    For k = ((j - 1) * 10 + 1) To ((j - 1) * 10 + 10)
      GrpText(j) = Grp(k) & GrpText(j)
    Next k
 Next j
 InputBox "Copy The Below Text", "Groups", GrpText(1) & GrpText(2) & GrpText(3) & GrpText(4) &       GrpText(5)



How can I store multiple checkbox with different name to mysql using laravel

I am working on a project that will require the user to select different checkbox

The checkbox is coming from the database with different names

I am using foreach to store the values to the database but I dont know how to store the second checkbox on the database

<div class="form-check">
     <input class="form-check-input" id="cleaning-check-box" name="service1[]" type="checkbox"
                                value="1" id="flexCheckDefault">
     <label class="form-check-label" for="flexCheckDefault">
              Cleaning
     </label>
</div>
<div class="form-check">
     <input class="form-check-input" id="cleaning-check-box" name="service1[]" type="checkbox"
                                value="1" id="flexCheckDefault">
     <label class="form-check-label" for="flexCheckDefault">
              Cleaning
     </label>
</div>

<div class="form-check">
     <input class="form-check-input" id="cleaning-check-box" name="service2[]" type="checkbox"
                                value="1" id="flexCheckDefault">
     <label class="form-check-label" for="flexCheckDefault">
              Cleaning
     </label>
</div>
<div class="form-check">
     <input class="form-check-input" id="cleaning-check-box" name="service2[]" type="checkbox"
                                value="1" id="flexCheckDefault">
     <label class="form-check-label" for="flexCheckDefault">
              Cleaning
     </label>
</div>

   $services = $request->get("service1");

    foreach($services as $key => $service){
        $payroll = new Payroll();
        $payroll->service = service;

$payroll->save(); }




How to create dynamic tree structure in svelte?

I need a treeview in svelte that has checkboxes with each node.

I am unable to get functionality that if we check a parent node then all of its (only its) children whether they are file of folders, all of them (child) get checked automatically and any of them is unchecked later then the parent should also get unchecked. How can I achieve this?

Below is the code that I followed from here. I tried few things but no luck.

App.svelte-

<script>
    import Folder from './Folder.svelte';

    let root = [
        {
            name: 'Important work stuff',
            files: [
                { name: 'quarterly-results.xlsx' }
            ]
        },
        {
            name: 'Animal GIFs',
            files: [
                {
                    name: 'Dogs',
                    files: [
                        { name: 'treadmill.gif' },
                        { name: 'rope-jumping.gif' }
                    ]
                },
                {
                    name: 'Goats',
                    files: [
                        { name: 'parkour.gif' },
                        { name: 'rampage.gif' }
                    ]
                },
                { name: 'cat-roomba.gif' },
                { name: 'duck-shuffle.gif' },
                { name: 'monkey-on-a-pig.gif' }
            ]
        },
        { name: 'TODO.md' }
    ];
</script>

<Folder name="Home" files={root} expanded/>

File.svelte-

<script>
    export let name;
    $: type = name.slice(name.lastIndexOf('.') + 1);
</script>

<span style="background-image: url(tutorial/icons/{type}.svg)">{name}</span>

<style>
    span {
        padding: 0 0 0 1.5em;
        background: 0 0.1em no-repeat;
        background-size: 1em 1em;
    }
</style>

Folder.svelte-

<script>
    import File from './File.svelte';

    export let expanded = false;
    export let name;
    export let files;
    let checkedState = true;

    function toggle() {
        expanded = !expanded;
    }
    
    function onCheckboxChanged(e){
        console.log("out: "+document.getElementById("cb1").checked)
    }
</script>

<input type="checkbox" on:change={onCheckboxChanged} id="cb1" bind:checked={checkedState}><span class:expanded on:click={toggle}>{name}</span>

{#if expanded}
    <ul>
        {#each files as file}
            <li>
                {#if file.files}
                    <svelte:self {...file}/>
                {:else}
                    <input type="checkbox" on:change={onCheckboxChanged} id="cb1" bind:checked={checkedState}><File {...file}/>
                {/if}
            </li>
        {/each}
    </ul>
{/if}

<style>
    span {
        padding: 0 0 0 1.5em;
        background: url(tutorial/icons/folder.svg) 0 0.1em no-repeat;
        background-size: 1em 1em;
        font-weight: bold;
        cursor: pointer;
    }

    .expanded {
        background-image: url(tutorial/icons/folder-open.svg);
    }

    ul {
        padding: 0.2em 0 0 0.5em;
        margin: 0 0 0 0.5em;
        list-style: none;
        border-left: 1px solid #eee;
    }

    li {
        padding: 0.2em 0;
    }
</style>




jeudi 29 juillet 2021

How to add dynamically control when checkbox in datagridview is checked vb.net

I tired for this
How to add dynamically textbox, label, and form from checkbox in datagridview?

this is my code

Sub getDataWIP()
    dgvbool = False
    D_DATA.Columns.Clear()
    Dim dt As DataTable = getData("SELECT created_at AS 'TANGGAL', assy_code AS 'ASSY CODE', model AS 'MODEL', lot_no AS 'LOT NUMBER',  " &
                                   "remark AS 'REMARK', qty AS QTY, shift AS SHIFT, pic AS PIC " &
                                   "FROM WIP_AUTO")
    D_DATA.DataSource = dt
    Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
    checkBoxColumn.HeaderText = ""
    checkBoxColumn.Width = 30
    checkBoxColumn.Name = "checkBoxColumn"
    D_DATA.Columns.Insert(0, checkBoxColumn)
    dgvbool = True
End Sub

and this

Private Sub P_PRINT_Click(sender As Object, e As EventArgs) Handles P_PRINT.Click
    Template.Show()
    Dim message As String = String.Empty
    For Each row As DataGridViewRow In D_DATA.Rows
        Dim isSelected As Boolean = Convert.ToBoolean(row.Cells("checkBoxColumn").Value)
        If isSelected Then
            message += Environment.NewLine
            message += row.Cells("MODEL").Value.ToString()
            Dim txt As New Label
            txt.Text = row.Cells("MODEL").Value
            txt.Location = New Point(50, 50)
            Template.Controls.Add(txt)
        End If
    Next
End Sub



i can't send the selected checkboxs to the database using mysqli

I am trying to send multiple checkboxes to database , i tried the following the code but it doesn't work as am new to php and am using procedural mysqli

<div class="form-group">
            <label class="checkbox-inline"><input type="checkbox" value="int" name="ch[]">Interruption de service</label>
            <label class="checkbox-inline"><input type="checkbox" value="hlp" name="ch[]">HLP</label>
            <label class="checkbox-inline"><input type="checkbox" value="gmao" name="ch[]">GMAO</label>
            <label class="checkbox-inline"><input type="checkbox" value="maj" name="ch[]">Majeur</label>
          </div>
     <button type="submit" class="btn btn-primary" name="submit">Submit</button>
          
          
          <?php
            if(isset($_POST['submit'])){
                echo "Les cases suivant sont cochez :<br>" ;
                $chk=implode(",",$_POST['ch']);
                $query="INSERT INTO `evenement` (toDo) values ('$chk')";
            }
           ?>
    
    //and also i i have condition that verified the click on submit 
    
    if (isset($_POST['submit'])) {
    $toDo=$_POST['ch'];
    $sql = "insert into `evenement` values ('','$ligne','$s_voiture','$code','$matricule','$s_conducteur','$un1','$un2','$h_debut','$h_fin','$desc','$lieu',$voie,'$meteo','$toDo')";
    
      $result = mysqli_query($con, $sql);
      if ($result) {
        echo "Information Inseree";
      } else {
        die(mysqli_error($con));
      }
    }

// and as a result in the database , when i check the column of toDO it says array




Inserting select all checkboxes into JS proving difficult

I have recently started helping with a live project to do with calculating values of "dimensions" containing different "enemies", "evolutions", and the rewards thereof. It already has checkboxes but they are coded differently than I have seen elsewhere, so it is proving difficult to add a select all/deselect all checkbox to each of the 4 sections. The single HTML is easy, the three JS are fighting me. However, I am not incredibly knowledgeable on coding so it may be a matter of ignorance. I am used to each box being coded separately, and these are not.
Here's a link to the live project.
Here's a link to the entire github repository if anyone's interested. Calc.js and calculator.html are the main files we're working with here.

Here's sections of the coding related to the checkboxes. Top three are in the same .js file, fourth is in the .html file.

    for (const [name, enemy] of Object.entries(enemies)) {
        if (enemy.base) {
            let evolved_enemy = enemy;
            do {
                if (evolved_enemy.evolution === undefined) {
                    break;
                }
                const evolved_name = evolved_enemy.evolution;
                evolved_enemy = enemies[evolved_enemy.evolution];
                evolutions_list.appendChild(create_evolution_checkbox(evolved_name, on_evolution_toggle));
            } while (evolved_enemy !== undefined);
            base_enemies.push(enemy);
        }
        evolved[name] = false;
    }
const create_evolution_checkbox = (name, changeCallback) => {
    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.name = name.replace(/ /g, "_");
    checkbox.classList.add("bonus_checkbox");
    checkbox.addEventListener("change", changeCallback);
    const label = document.createElement("label");
    label.textContent = name;
    label.htmlFor = name;
    const container = document.createElement("li");
    container.appendChild(label);
    container.appendChild(checkbox);
    return container;
};
const on_evolution_toggle = (event) => {
    const enemy_name = event.currentTarget.name.replace(/_/g, " ");
    evolved[enemy_name] = !evolved[enemy_name];
    let enemy = find_evolution_base(enemy_name);
    //make sure all evolutions are checked that are before this
    const is_checked = evolved[enemy_name];
    let enemy_encountered = false;
    do {
        if (enemy.evolution === undefined) {
            break;
        }
        if ((is_checked && !enemy_encountered) || (!is_checked && enemy_encountered)) {
            const checkbox = document.querySelector(`input[name=${enemy.evolution.replace(/ /g, "_")}]`);
            if (checkbox !== null) {
                checkbox.checked = evolved[enemy_name];
            }
            evolved[enemy.evolution] = evolved[enemy_name];
        }
        if (enemy.evolution === enemy_name) {
            enemy_encountered = true;
        }
        enemy = enemies[enemy.evolution];
        // eslint-disable-next-line no-constant-condition
    } while (true);
    calculate_map_values();
};
        <label for="mapValueEvolutionsList">Check unlocked evolutions:</label>
        <ul id="mapValueEvolutionsList" name="mapValueEvolutionsList"></ul>

I apologize in advance as I'm sure my ignorance is showing through, but I would appreciate any help someone can provide in adding a select/deselect all checkbox to each individual section (not the whole page of checkboxes at once) that also defaults to on with click, as otherwise it won't change the values by default. This is something that will help me understand it better as well, so thank you in advance if you're willing to help.




Django DetailView - display boolean from models as checkboxes

There's a number of snippets to display booleans in Django Forms as checkboxes (i.e. specifying Checkbox as a widget). For instance (assuming a boolean field defined in the model for bar):

class FooForm(forms.ModelForm):

    class Meta:
        model = Foo
        fields = ['bar'] 
        widgets = {
            'bar' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),   
        }

However I also need to display a (disabled) checkbox in DetailView (client says so). But I can't figure out an elegant way to do this, since I don't have a form meta for details view...

My current thinking is something like this (bootstrap checkbox):

<div class="form-check">
   <label class="form-check-label">
      <input type="checkbox"  disabled>Bar
   </label>
<\div>

Any way to accomplish this in a fashion closer to the Form's widgets?




Delete an object created when another checkbox is selected in the same row in angular

I have a simple table with descriptions and two columns representing a state: YES and NO.

table

Each checkbox represents an object in which it includes the "Condition" property that is null at startup. Depending on what is marked, an array of objects is formed. What I want to do is that when another checkbox in the same row is selected, delete the previously created object. Without affecting the other rows.

For example when I select a checkbox:

check1

And by selecting the other checkbox, I would like to delete the previous object

check2

I was playing around with the event checked and change to prevent the user from selecting the two checkboxes in the same row. Also to delete the created object by unchecking a selected checkbox, making the "Condition" true or false.

I have a demo on stackblitz: Demo

.HTML

<form [formGroup]="demoFormGroup" style="margin-top:20px; margin-bottom:30px">
  <div formArrayName="info">
    <table>
      <tr>
        <th></th>
        <th>YES</th>
        <th>NO</th>
      </tr>
      <tr *ngFor="let x of data; let i = index">
        <td></td>
        <td>
          <mat-checkbox
            (change)="onChange($event,x,true)"
            [checked]="x.Condition"
          ></mat-checkbox>
        </td>
        <td>
          <mat-checkbox
            (change)="onChange($event,x,false)"
            [checked]="x.Condition != null && !x.Condition"
          ></mat-checkbox>
        </td>
      </tr>
    </table>
  </div>
</form>
<pre></pre>

.TS

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  demoFormGroup: FormGroup;
  data: any;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.demoFormGroup = this.fb.group({
      info: this.fb.array([])
    });

    this.data = [
      {
        Id: 4,
        Description: 'Option 1',
        Condition: null
      },
      {
        Id: 6,
        Description: 'Option 2',
        Condition: null
      }
    ];
  }

  onChange(event: any, option: any, enabled: boolean) {
    option.Condition = enabled;
    const ctrl = (<FormArray>this.demoFormGroup.get('info')) as FormArray;
    if (event.checked) {
      ctrl.push(new FormControl(option));
    } else {
      this.removeObject(ctrl, event);
    }
  }
  removeObject(ctrl: any, event: any) {
    const i = ctrl.controls.findIndex(
      (x: any) => x.value === event.source.value
    );
    ctrl.removeAt(i);
  }
}



html checkboxes associative array - how to access this array in javascript?

I'm trying to do this:

<input type="checkbox" name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">

and get access to this array in javascript like this

1.

var myarr = document.getElementsByName('appliances');
alert('here ' + myarr);

result: alert shows "here [object NodeList]"

2.

var myarr = document.getElementsByName('appliances');
    alert('here ' + myarr['grill']);

result: alert shows "here undefined"

How may I get access to this array?




p:selectBooleanCheckbox *look only* shifted after adding a row to a p:dataTable

I have a p:dataTable. In this table, I have a checkbox in a column. This is the code:

<p:selectBooleanCheckbox 
    value="#{var.selected}"
    itemLabel="#{var.description}" 
/>

After I add a row and update the whole table, the selected checkboxes after the row inserted have the checks shifted up! But it's only a graphical problem! The checkboxes that now appears unched are yet checked, because I show other things in the roiw if the checkbox is selected. On the contrary, the checkbox that now appear checked do not show the additional components.

I checked the html, and the classes and attributes that make them checked disappears. But debugging the backend I see that the in the list connected to the table, after the add, all the items have the expected value.




mercredi 28 juillet 2021

The checkbox in Boostrap Table could not be initialized (React hooks)

Below is my code sample https://codesandbox.io/s/snowy-resonance-7sc6w?file=/src/index.js

I just want to initialize the checkbox property "checked" with state ,but it doesn't works. Any help is appreciated




Vue JS - Checkbox / if Checked do This if unchecked do that

im trying to create a checkbox that runs one function when it is initaly checked and runs another when it is then unchecked.

here something ive tryied out theres also a variable that already has been read out and represents the current status

   <input type="checkbox" :checked="e.Processed == true" v-model="toggle" true-value= functionTrue false-value="no">



My seekbar doesn't work in a BottomSheetDialog

I created a BottomSheetDialog with a checkbox and a SeekBar. I want that if the checkbox is checked, the seekbar can be used. My code works but only if i use setContentView(MyLayout), but that makes the layout appair on screen and i want that it works on the dialog. How can i make it work without that? My code here: Ps: I am sorry for my english, but it isn't my first language.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar=findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);
    toolbar.setOverflowIcon(getDrawable(R.drawable.ic_baseline_more_vert_24));


    ImageButton menu_filtri = findViewById(R.id.button_filtri);
    menu_filtri.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this,R.style.BottomSheetDialogTheme);
            View BottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_bottom_sheet,(LinearLayout)findViewById(R.id.bottom_sheet_container));

            bottomSheetDialog.setContentView(BottomSheetView);
            bottomSheetDialog.show();
            setContentView(R.layout.layout_bottom_sheet);

            range_distanza = (CheckBox) findViewById(R.id.next_checkbox);
            seekbar = (SeekBar) findViewById(R.id.range_seekbar);
            set_seekbar();

        }
    });



}

public void set_seekbar() {
    range_distanza.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean ischecked) {
            seekbar.setEnabled(ischecked);
        }
    });
}



mat-checkbox not changing mat-ripple-element width and height

I am using the standart mat-checkbox like this:

                    <mat-checkbox class="checkbox-download example-margin"
                              (change)="checkboxChange($event.checked, item.id)"
                              [checked]="item.checked"></mat-checkbox>

And i would like to change its default 40x40 px dimension of click/hover circle into 36x36 px. I have tried changing the css like this:

 .mat-checkbox-ripple, .mat-ripple-element{
    width: 36px !important;
    height: 36px !important;
    left: calc(50% - 18px) !important;;
    top: calc(50% - 18px) !important;;
  }

which leads to the dimension being changed:

This is expected size of mat-checkbox click/hover area

also the classes are fine while hover:

Classes

But when i click it with the mouse and while the mouse button is still clicked i get dynamically added during this time div with 40x40 pixels dimensions while i expect it to be with 36x36 px and just be darker but it looks like:

This ugly result

Any ideas how to change the dimensions of the checkbox click area? I can see here They add 20 px steady ripple radius but how to change it locally to 18px?




Is there any way to stop state change of checkbox(check to uncheck) i have checkbox list and on scroll of list checkbox state change

Is there any way to stop state change of checkbox(check to uncheck) I have checkbox list and on scroll of list checkbox state change without using keep alive because my list is in page view and if I use keep alive next page intestate() method call only one's so I need help without using keep alive how can I save state of checkbox in list flutter




StickyEnd not functioning for Checkbox

enter image description hereThe checkbox is being overlapping even though stick end is used . Happened with chrome update

<ng-container matColumnDef="select" stickyEnd>
                <th mat-header-cell *matHeaderCellDef style="padding-left: 10px;">
                    <mat-checkbox (change)="$event ? masterToggle() : null"
                        [checked]="selection.hasValue() && isAllSelected()"
                        [indeterminate]="selection.hasValue() && !isAllSelected()">
                    </mat-checkbox>
                </th>

enter image description here




Checkbox arn't wotking with CORS extension

I use a CORS extension on my navigator for a webGL usage.

When i use these extensions, the click on the checkbox or raddio button does not work anymore. (they don't show the blue color when checked)

Is there a way to solve this problem ?




mardi 27 juillet 2021

how can I do to pass the value of my radiobutton to my chheckbox in angular?

I have 2 tables with the same service but I want that when pressing the radiobutton the checkbox of the table below is also marked How could I make that happen?

html

search Buscar Staff search Buscar

TS at the moment I only show the idPersona in a console.log ()

      handleSeleccionPersona = (checked, data) => {
       console.log("radio es:" + data['idPersona'])
        this.showme2 = !this.showme2
      }

enter image description here




the control boxes are relocated when the excel file is opened on server by multiple users

Can someone help me with this problem. When I open the file on my pc the boxes looks ok on their positions but when other users open it, the check boxes do not remain on their original position. Is there a way where I can fix the positions of these control boxes on a specific cell address.

enter image description here




lundi 26 juillet 2021

Variable text in MS Words

I have a pile of word templates for calibration certificates where the main text is the same. The difference is what I have used for measuring equipment and if I have excluded any test. I wonder how to create a document template where I can easily choose which tests have been done and which equipment has been used? I use these templates several times a day and in a perfect world there would be check boxes where you select the correct text.

Please, is this still in Word and how to use it?

I made an advanced Word document in the 90's with some similar function, but I do not remember how I did ...

best regrads Bosch




Filter data with checkbox buttons in React

I would like to filter data based on pressing multiple checkbox buttons. Currently only the most recently pressed button works and shows the output instead of also showing outputs from other buttons which are pressed as well.

The state of checkbox buttons works correctly i.e. when clicked it is true, when unclicked it is false - however I am not sure how to connect it with my find function which fetches the data.

  const Checkbox = ({ type = "checkbox", name, checked = false, onChange }) => {
    return (
      <input
        type={type}
        name={name}
        checked={checked}
        onChange={onChange}
      />
    );
  };
  const [checkedItems, setCheckedItems] = useState({}); //plain object as state
  const handleChange = (event) => {
    // updating an object instead of a Map
    setCheckedItems({
      ...checkedItems,
      [event.target.name]: event.target.checked,
    });
    find(event.target.name)
  };

useEffect(() => {
    console.log("checkedItems from UseEffect: ", checkedItems); }, [checkedItems]);
  const checkboxes = [
    {
      name: "🤵‍♀️ Finance",
      key: "financeKey",
      label: "financeLabel",
    },
    {
      name: "👩‍🎨 Marketing",
      key: "marketingKey",
      label: "marketingLabel",
    },
    {
      name: "👨‍💼 Sales",
      key: "salesKey",
      label: "salesLabel",
    },
  ];
                  <label>
                    {checkedItems["check-box-1"]}{" "}
                    {/* Checked item name : {checkedItems["check-box-1"]}{" "} */}
                  </label>{" "}
                  <br />
                  {checkboxes.map((item) => (
                    <label key={item.key}>
                      {item.name}
                      <Checkbox
                        name={item.name}
                        checked={checkedItems[item.name]}
                        onChange={handleChange}  
                      />
                    </label>
                  ))}
           

The function below fetches data from database

  const find = (query, by) => {
    JobDataService.find(query, by)
      .then((response) => {
        setJobs(response.data.jobs);
        setPages(response.data.totalPages);
      })
      .catch((e) => {
        console.log(e);
      });
  };



How can I get labels on checkboxes to line up in a row in Material Dashboard?

I have some text controls and a checkbox in a Material Dashboard page. I would like the labels for all the controls lined up above the actual controls. I've tried several different things but the label for the checkbox just will not line up with the labels for the text controls.

Here's what I've got:

'''

Title
    <div id='myContainer'>
        <div class="row" style="display:flex;align-items:center">
            <div class="form-group bmd-form-group">
                <label for="Text1">Text1</label>
                <input id="Text1" type="text" name="Text1" class="form-control" value=@ViewData["Text1"]>
            </div>
            <div class="form-group bmd-form-group">
                <div class="form-check">
                    <label for="CheckedFlag">Checked?</label>
                    <input id="CheckedFlag" type="checkbox" name="CheckedFlag" class="form-control" asp-for="CheckedFlag" />
                </div>
            </div>

            <div class="form-group bmd-form-group">
                <label for="Text2">Text2</label>
                <input id="Text2" type="text" class="form-control" name="Text2" value="@ViewData["Text2"]">
            </div>

        </div>
    </div>
</form>
'''


dimanche 25 juillet 2021

How can i process value get from checkbox by JS then do something with it in Java action?

I have a checkbox like this in JSP

<input type="checkbox" id="checkBox" name="checkBox"/>

In JS file I wrote a function to set data for a variable when checkbox be clicked

$("checkBox").change(function(){
var checkBox= 0;
if(this.checked) {
    checkBox= 1;
} else {
    checkBox= 0;
}
})

Then in Java action class I want to do something when checkbox be clicked

if(bean.getCheckBox == 1) {//do something}

But it's not working. Please help me fix this one ! thanks




Checkbox not check inside showDialog flutter

I have set up my code to when i tap on the list tile , it should pop up a dialog , inside the dialog i have 3 checkboxes , they are working because the value is updating correctly but the check mark dosnt appear at first unless i click first time , reopen dialog , there it appeares , if anyone could help fix my issue , thank you in advance .

  • This is my code

  void _showTemperatureUnit(BuildContext context){
      showDialog(
          context: context,
          builder: (context){
            return StatefulBuilder(
              builder: (context,state){
                return AlertDialog(
                  title: Text('Pick A Unit',style: TextStyle(fontFamily: 'bebas',
                      fontWeight: FontWeight.bold),),
                  content: Container(
                    height: MediaQuery.of(context).size.height / 5,
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Expanded(child: Text('Celsius ',style: TextStyle(fontFamily: 'bebas',
                                fontWeight: FontWeight.bold),),flex: 9,),
                            Flexible(
                              child: Checkbox(
                                value: _isCelsius,
                                onChanged: (val){
                                  setState(() {
                                    _isCelsius = val!;
                                    _isKelvin = false;
                                    _isFer = false;
                                    _selectedUnit = 'metric';
                                  });
                                },
                              ),
                              flex: 1,
                            )
                          ],
                        ),
                        SizedBox(height: 5,),
                        Row(
                          children: [
                            Expanded(child: Text("Fahrenheit",style: TextStyle(fontFamily: 'bebas',
                                fontWeight: FontWeight.bold),),flex: 9,),
                            Flexible(
                              child: Checkbox(
                                value: _isFer,
                                onChanged: (val){
                                  setState(() {
                                    _isFer = val!;
                                    _isCelsius = false;
                                    _isKelvin = false;
                                    _selectedUnit  = 'standard';
                                  });
                                },
                              ),
                              flex: 1,
                            )
                          ],
                        ),
                        SizedBox(height: 5,),
                        Row(
                          children: [
                            Expanded(child: Text('Kelvin',style: TextStyle(fontFamily: 'bebas',
                                fontWeight: FontWeight.bold),),flex: 9,),
                            Flexible(
                              child: Checkbox(
                                value: _isKelvin,
                                onChanged: (val){
                                  setState(() {
                                    _isKelvin = val!;
                                    _isFer  = false;
                                    _isCelsius = false;
                                    _selectedUnit = 'imperial';
                                  });
                                },
                              ),
                              flex: 1,
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  actions: [
                    RaisedButton(onPressed: () async {
                      SharedPreferences prefs = await SharedPreferences.getInstance();
                      prefs.setString('unit', _selectedUnit);
                      Navigator.push(context, MaterialPageRoute(builder: (context) => WeatherPage()));
                    },child: Text('Pick',style: TextStyle(color: Colors.white),),color: Colors.blue,),
                    RaisedButton(onPressed: (){
                      Navigator.pop(context);
                    },child: Text('Cancel',style: TextStyle(color: Colors.white),),color: Colors.blue,)
                  ],
                );
              },
            );
          });
  }



How to set value on selected items with checkboxListTile

What is the correct way to Setstate of checkboxListTile to get both toggle button and added value to it?

What I want is when you check the box, You see the check button. then the value added into the base price. Please kindly help.

CheckboxListTile(
                                activeColor: Colors.blue,
                                dense: true,
                                //font change
                                title: new Text(
                                  listTopping[i].price.toStringAsFixed(0) +
                                      ' บาท',
                                  style: TextStyle(
                                    fontSize: 25,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                value: listTopping[i].isCheck,
                                secondary: Container(
                                  height: 50,
                                  width: 300,
                                  child: Text(
                                    listTopping[i].topping,
                                    style: TextStyle(
                                      fontSize: 25,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                                onChanged: (bool? val) {
                                  itemChange(val!, i);
                                },
                              ),

Here is the setstate that I believe is wrong...

  void itemChange(bool val, int i) {
    setState(() {
      listTopping[i].isCheck = val;
    });
  }
}



Checkbox inside the "for" (loop), Django

my checkbox html :

<form method="GET">
    
<button type="submit" class="btn btn-primary w-100 mt-3">Filter!</button>
</form>

it work correctly to make filter. views :

subcatid = request.GET.getlist('subcategory')

query string:

?subcategory=5&subcategory=6

it can be one or more than one, depends on number of subcategories. but when I go next page i suppose it become like :

?page=2&subcategory=5&subcategory=6

but it remove earliest subcategory i choose and keep the last one, just one, like :

?page=2&subcategory=5

acutely when i put Manually ?page=2&subcategory=5&subcategory=6 in url field it works but not from pagination buttons.

so while all checkboxes in filter has same names, name="subcategory" i made them unique by changing to name="", now each checkbox has unique name, now after tapping next page, Everything is kept, and there is no problem like before, but in views, I don't know how to get them with deafferents names

subcatid = request.GET.getlist('subcategory')  



samedi 24 juillet 2021

woocommerce add extra filed in checkout Page if selected Country is A

would like to add extra field on woocommerce checkout page - where to apply if condition if the selected country is equal to A - the checkout field should appear on checkout page

/**

* Add custom field to the checkout page

*/

add_action('woocommerce_after_order_notes', 'custom_checkout_field');

function custom_checkout_field($checkout)

{

echo '<div id="custom_checkout_field"><h2>' . __('Requried For Outside UAE') . '</h2>';

woocommerce_form_field('custom_field_name', array(

'type' => 'text',

'class' => array(

'my-field-class form-row-wide'

) ,
'label' => __('House No,Villa No,Building Name') ,

'placeholder' => __('') ,

'label' => __('Street Name') ,

'placeholder' => __('Street Name') ,

'label' => __('Landmark') ,

'placeholder' => __('Enter Nearest Landmark') ,

) ,

$checkout->get_value('custom_field_name'));

echo '</div>';

}
 



vendredi 23 juillet 2021

Check which worksheets to export as pdf

I am a beginner in Excel VBA but I would like to create a file where I can select certain worksheets by means of a userform with checkboxes. In principle, it is then intended that only the check boxes where the value is true should be exported.

Below I have 2 codes that work well separately from each other but I have not yet been able to get them to work together.

Note: both codes come from the internet.

If possible I would like to write a loop to keep the overview.

the code to export sheets as pdf and put them in a outlook

Sub Saveaspdfandsend1()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xArrShetts As Variant
Dim xPDFNameAddress As String
Dim xStr As String
xArrShetts = Array("test", "Sheet1", "Sheet2") 'Enter the sheet names you will send as pdf files enclosed with quotation marks and separate them with comma. Make sure there is no special characters such as \/:"*<>| in the file name.

For I = 0 To UBound(xArrShetts)
On Error Resume Next
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
If xSht.Name <> xArrShetts(I) Then
MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
Exit Sub
End If
Next


Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))

xStr = xFolder & "\" & xSht.Name & ".pdf"
xNum = 1
While Not (Dir(xStr, vbDirectory) = vbNullString)
xStr = xFolder & "\" & xSht.Name & "_" & xNum & ".pdf"
xNum = xNum + 1
Wend
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard
Else

End If
xArrShetts(I) = xStr
Next

'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.CC = ""
.Subject = "????"
For I = 0 To UBound(xArrShetts)
.Attachments.Add xArrShetts(I)
Next
If DisplayEmail = False Then
'.Send
End If
End With
End Sub

the other code i tried I can see which checkbox is checked unfortunately I can't rewrite it so only the checked boxes will be exported to pdf.

Private Sub CommandButton100_Click()

For i = 100 To 113

If UserForm2.Controls("CheckBox" & i).Value = True Then
a = a + 1
End If

Next i

k = 1

For i = 100 To 113

If UserForm2.Controls("CheckBox" & i).Value = True And a = 1 Then
    b = UserForm2.Controls("CheckBox" & i).Caption & "."
ElseIf UserForm2.Controls("CheckBox" & i).Value = True And k <> a Then
    b = b & UserForm2.Controls("CheckBox" & i).Caption & ", "
    k = k + 1
ElseIf UserForm2.Controls("CheckBox" & i).Value = True And k = a Then
    b = b & "and " & UserForm2.Controls("CheckBox" & i).Caption & "."
End If

Next i

MsgBox ("You have selected " & b)

End Sub

Can someone help me please I am struggling for some time now?




How to check if checkbox is checked php

This is html code for my checkbox and button

 <input type="checkbox" id="DNA" name="DNA" value="checkox_value">
 
<button type="button" name="submit" onClick="search()" id="sim_btn" class="btn btn-primary">Start Simulation</button>

I want to check if checkbox is checked and if yes write the input to my file.
I tried using the isset function but it doesn't work any other suggestions?

if(isset($_POST["DNA"])) { 
        $input3 = "signal(f).";
        fwrite($handleStoryFile, $input3 . PHP_EOL); 
    }  



vanilla js hide row table on checkbox

I have the following codes. checkbox for hide table row

Problem: Filter boolean can't hide of table but hide select option ? I want to hide row

Fiddle: http://jsfiddle.net/ocy8hzux/

Can anyone advise with my codes?

function filter(event, filterCol) {
  let element = event.target;
  let condt1 = document.getElementsByClassName(filterCol);
  for (let i = 0; i < condt1.length; i++) {
    if (condt1[i].innerHTML.toLowerCase() == element.value.toLowerCase()) {
      if (element.checked == true) {
        condt1[i].parentElement.style = ""
      } else {
        condt1[i].parentElement.style = "display:none"
      }
    }
  }
}

document.querySelectorAll('.option1')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check1")));
  
  
document.querySelectorAll('.option2')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check2")));
<div id="input">
  <label>Filter Name </label><br>
  <label>Human<input class="option1" type="checkbox" value="Human" checked/></label>
  <label>Robot<input class="option1" type="checkbox" value="Robot"checked/></label><br><br>
  
   <label>Filter boolean </label><br>
  <label>true<input class="option2" type="checkbox" value="true" checked/></label>
  <label>false<input class="option2" type="checkbox" value="false" checked/></label>
</div><br>
<table id="my-table">
  <thead>
    <tr>
      <th> Name </th>
      <th> boolean </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="check1">Robot</td>
      <td>
        <select>
            <option class="check2">true</option>
            <option >true</option>
        </select>
      </td>
    </tr>
    <tr>
        <td class="check1">Human</td>
      <td>
        <select>
            <option class="check2">true</option>
            <option >false</option>
        </select>
      </td>
    </tr>
    <tr>
     <td class="check1">Robot</td>
      <td>
        <select>
            <option class="check2">false</option>
            <option >false</option>
        </select>
      </td>
    </tr>
    <tr>
     <td class="check1">Human</td>
      <td>
        <select>
            <option class="check2">true</option>
            <option >true</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

Sorry for my bad English, can't explain all what I need, hope you understand what I need

Thanks !




How to display a checked checkbox in a PHP update form? postgres sql

I have to show a checked check box (like this one), but currently when extracting the value from the database (it shows this).

Is there a way to show the checked check box when extracting the known value from the database (PgAdmin)(All code is either HTML,CSS or PHP)

Code:

    Topings: <br><br>
 <label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Vanilla") echo "checked" ?> value="<?php echo $row['toping'];  echo "checked" ?>"><span class="checkmark"></span><span class="checkbox-txt"> Vanilla</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Chocolate") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark"></span><span class="checkbox-txt" >Chocolate</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Caramel") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark"></span><span class="checkbox-txt" >Caramel</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Strawberry") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark"></span><span class="checkbox-txt" >Strawberry</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="M&M's") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark"></span><span class="checkbox-txt" >M&M's</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Oreo") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark"></span><span class="checkbox-txt" >Oreo</span><br/></br></label>
<label class="checkbox-container">
<input type="checkbox" name="toping" <?php if(isset($_POST['toping']) && $_POST['toping']=="Meringue") echo "checked" ?>value="<?php echo $row['toping']; ?>"><span class="checkmark "></span><span class="checkbox-txt" >Meringue</span><br/></label>



jeudi 22 juillet 2021

Django - How to group forms.CheckboxSelectMultiple items by unique parent field value?

My category models:

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=255, default='')

    def __str__(self):
        return "%s" % (self.name)


class SubCategory(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=255, default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)


    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

Here's my Job class:

class Job(models.Model):
    ...
    skill_set = models.ManyToManyField(SubCategory)

my forms.py:

class CustomSelectMultiple(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s - %s" %(obj.category, obj.name)
        # return "%s" %(obj.name)

class NewJobForm(forms.ModelForm):
    
    skill_set = CustomSelectMultiple(widget=forms.CheckboxSelectMultiple, queryset=SubCategory.objects.all())
    
    class Meta:
            model = Job
            fields = ['skill_set']

In my template file I have a standard:


In my context:

form = NewJobForm()

So as expected in my form I see:

enter image description here

But I would like my checkboxes to be display as such:

enter image description here

How can I achieve that?




Ant table custom filter checkbox without dropdown

I am using and table for my project where I want to filter records on click of checkbox inside my header row, when I click on check box all zero valued rows should be filtered and others should stay, is there any way I can do this? Demo




Using checkboxes to show and hide sheets with apps script

I would like to use 5 checkboxes to hide (false) and show (true) sheets. I have the impression that this is not possible with onEdit. Can someone help me how I can solve this. Thank you very much for the help. GJM




mercredi 21 juillet 2021

how to disable/enable checkbox in flutter based on data of previous page in flutter

I want to disable "are you pregnant" checkbox if I choose (gender)radio button as "male" in previous page named as Registration page. I used routes argument in main class to navigate through pages.

//Radio button ListTile(
                title: const Text('Male'),
                leading: Radio<Gender>(
                  value: Gender.Male,
                  groupValue: _gender,
                  onChanged: (Gender? value) {
                    setState(() {
                      var isMale = false;
                      _gender = value;
                      if (_gender == Gender.Male){
                        isMale= true;
                        CheckUpPage(gender: isMale);
                      }
                      
                    });
                  },
                ),
              ),

i am using enum class named Gender for radio button value argument. CheckBoxState.checkUpTitleList[0] = 'are you pregnant'

Widget buildSingleCheckBox(CheckBoxState checkBox) => CheckboxListTile(
    controlAffinity: ListTileControlAffinity.leading,
    activeColor: Theme.of(context).primaryColor,
    value: checkBox.value,
    title: Container(
      width: 300,
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 4),
      child: Text(
        checkBox.title,
        softWrap: true,
        overflow: TextOverflow.fade,
      ),
    ),
    
    onChanged: (checkBox.title == CheckBoxState.checkUpTitleList[0] && widget.gender == true)? null: (val){
      setState(() {
        checkBox.value =val!;
      });
    },
          
        
      
  );

I tried to do it this way but didn't worked.




Tk GUI works until I try to add a check box

I have the following code which works fine...

from tkinter import *
import serial
import struct

usbport    = 'COM3'
ser        = serial.Serial(usbport, 9600, timeout=1)
slider_max = 255;
midway     = int(slider_max / 2)

def init():
    print("Started")

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.scale_0 = Scale(master, from_=0, to=slider_max, command=lambda ev: self.getPWM(0), bd=5, bigincrement=2, length=360, width=30, label='RED')
        self.scale_0.set(midway)
        self.scale_0.pack(side=LEFT)
        self.scale_1 = Scale(master, from_=0, to=slider_max, command=lambda ev: self.getPWM(1), bd=5, bigincrement=2, length=360, width=30, label='GREEN')
        self.scale_1.set(midway)
        self.scale_1.pack(side=LEFT)

        self.centre = Button(frame, text="Centre All", command=self.centre)
        self.centre.pack(side=TOP)
        self.zero = Button(frame, text="Zero All", command=self.zero)
        self.zero.pack(side=LEFT)
        self.maximum = Button(frame, text="Max All", command=self.maximum)
        self.maximum.pack(side=RIGHT)

        # self.chained = IntVar()
        # self.chk = Checkbutton(self, text="chain", variable=self.chained)
        # self.chk.pack(side=BOTTOM)


            
    def getPWM(self, slider):
        
        if slider == 0:
            pwm = self.scale_0.get()
            
        if slider == 1:
            pwm = self.scale_1.get()  
            
        ser.write(struct.pack('>B', 255))
        ser.write(struct.pack('>B', slider))
        ser.write(struct.pack('>B', pwm))
        

    def centre(self):
        
        for idx in range(0, 2):
            
            ser.write(struct.pack('>B', 255))
            ser.write(struct.pack('>B', idx))
            ser.write(struct.pack('>B', midway))
            
        self.scale_0.set(midway)
        self.scale_1.set(midway)


    def zero(self):
        
        for idx in range(0, 2):
            
            ser.write(struct.pack('>B', 255))
            ser.write(struct.pack('>B', idx))
            ser.write(struct.pack('>B', 0))
            
        self.scale_0.set(0)
        self.scale_1.set(0)

        
    def maximum(self):
        
        for idx in range(0, 2):
            
            ser.write(struct.pack('>B', 255))
            ser.write(struct.pack('>B', idx))
            ser.write(struct.pack('>B', slider_max))

            
        self.scale_0.set(slider_max)
        self.scale_1.set(slider_max)


init()
root = Tk()
app = App(root)
root.mainloop()

However when I uncomment the check box code

    self.chained = IntVar()
    self.chk = Checkbutton(self, text="chain", variable=self.chained)
    self.chk.pack(side=BOTTOM)

I get the following error,

Traceback (most recent call last):

  File "D:\Tentacle\Servo controller\PC_side_TK_slider_controller.py", line 98, in <module>
    app = App(root)

  File "D:\Tentacle\Servo controller\PC_side_TK_slider_controller.py", line 41, in __init__
    self.chk = Checkbutton(self, text="chain", variable=self.chained)

  File "D:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2646, in __init__
    Widget.__init__(self, master, 'checkbutton', cnf, kw)

  File "D:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2292, in __init__
    BaseWidget._setup(self, master, cnf)

  File "D:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2262, in _setup
    self.tk = master.tk

AttributeError: 'App' object has no attribute 'tk'

I have looked through posts about AttributeError: 'App' object has no attribute 'tk' but am just getting more & more confused.

Why would adding a checkbox crash the program?




How to add checkboxes values to textarea field

I have textarea field and 3 groups of checkboxes. User can individually select any checkbox and checkbox value will be added to textarea field. But how to include "Select all" functionality to select all checkboxes in group? I created "Select all" function, but after selection values are not added to textarea field.

// Add checkbox value to text field
$checks = $("ul li :checkbox");
$checks.on("change", function() {
  var string = $checks.filter(":checked").map(function(i,v){
    return this.value;
  }).get().join(",");
  $("#results").val( "checked:" + string);
});

// Select all checkboxes in the group
jQuery(function($){
  $('#allg1').click(function () { $('.group1 li input').not(this).prop('checked', this.checked);});
  $('#allg2').click(function () { $('.group2 li input').not(this).prop('checked', this.checked);});
  $('#allg3').click(function () { $('.group3 li input').not(this).prop('checked', this.checked);});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="results" rows="2" cols="60"> </textarea>

<ul class="group1">
  <input type="checkbox" id="allg1" name="allg1"><label for="allg1">Select all from group G1</label>
  <li><input type="checkbox" value="G101"></li>
  <li><input type="checkbox" value="G102"></li>
  <li><input type="checkbox" value="G103"></li>
</ul>

<ul class="group2">
  <input type="checkbox" id="allg2" name="allg2"><label for="allg2">Select all from group G2</label>
  <li><input type="checkbox" value="G201"></li>
  <li><input type="checkbox" value="G202"></li>
  <li><input type="checkbox" value="G203"></li>
</ul>

<ul class="group3">
  <input type="checkbox" id="allg3" name="allg3"><label for="allg3">Select all from group G3</label>
  <li><input type="checkbox" value="G301"></li>
  <li><input type="checkbox" value="G302"></li>
  <li><input type="checkbox" value="G303"></li>
</ul>



(Flutter) Listview builder won't show checkboxlist

It does not show any error but the listview builder doesn't show any checkboxlist. where did I goes wrong? Please correct me.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:selfordering1/models/addon.dart';
import 'package:selfordering1/models/models.dart';

class Americano extends StatefulWidget {
  @override
  _AmericanoState createState() => _AmericanoState();
}

class _AmericanoState extends State<Americano> {
  List<Products> beverages = [];
  List<addonsize> listSize = [];
  List<addontopping> listTopping = [];
  var items = Products().beverages;

  bool _value = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        backgroundColor: Colors.transparent,
        elevation: 0.0,
      ),
      extendBodyBehindAppBar: true,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/lightwood.jpg'),
            fit: BoxFit.fill,
          ),
        ),
        child: ListView(
          physics: NeverScrollableScrollPhysics(),
          primary: false,
          padding: const EdgeInsets.all(100),
          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 200,
                  height: 200,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(items[1].img),
                    ),
                  ),
                ),
                Text(
                  items[1].name,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 30,
                      color: Colors.brown),
                ),
                Container(
                  margin: EdgeInsets.all(50),
                  child: Text(
                    items[1].price.toStringAsFixed(0) + ' บาท',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 30,
                        color: Colors.brown),
                  ),
                ),
              ],
            ),
               Row(
                 children: [
                   Expanded(
                     child: ListView.builder(
                            shrinkWrap: true,
                            itemCount: listTopping.length,
                            itemBuilder: (BuildContext context, int i) {
                              return new Card(
                                child: new Container(
                                  padding: new EdgeInsets.all(10.0),
                                  child: Column(
                                    children: <Widget>[
                                      new CheckboxListTile(
                                        activeColor: Colors.blue,
                                        dense: true,
                                        //font change
                                        title: new Text(
                                          listTopping[i].topping,
                                          style: TextStyle(
                                              fontSize: 25,
                                              fontWeight: FontWeight.bold,
                                              ),
                                        ),
                                        value: listTopping[i].isCheck,
                                        secondary: Container(
                                          height: 50,
                                          width: 50,
                                          child: Text(listTopping[i]
                                              .price
                                              .toStringAsFixed(0)),
                                        ),
                                        onChanged: (bool? val) {
                                          itemChange(val!, i);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            }),
                   ),
                 ],
               ),
                ],
            ),
      ),
    );
  }

  void itemChange(bool val, int i) {
    setState(() {
      listTopping[i].isCheck = val;
    });
  }
}

Here is the model

import 'package:flutter/material.dart';

class addonsize {
  int id;
  String size;
  double price;

  addonsize({
    required this.id,
    required this.size,
    required this.price,
  });
}


List<addonsize> listSize = [
  addonsize(
    id: 6,
    size: 'Grande',
    price: 30,
  ),
  addonsize(
    id: 7,
    size: 'Venti',
    price: 50,
  ),
];


class addontopping {
  int id;
  String topping;
  double price;
  bool isCheck;

  addontopping({
    required this.id,
    required this.topping,
    required this.price,
    required this.isCheck,
  });
}

List<addontopping> listTopping = [
  addontopping(
    id: 8,
    topping: 'Whipcream',
    price: 0,
    isCheck: true,
  ),
  addontopping(
    id: 9,
    topping: 'Javachip',
    price: 30,
    isCheck: false,
  ),
  addontopping(
    id: 10,
    topping: 'SoyMilk',
    price: 20,
    isCheck: false,
  ),
  addontopping(
    id: 11,
    topping: 'ExtraSyrup',
    price: 30,
    isCheck: false,
  ),
];

If there are more detailed needed, please let me know. Also, if it's not too much, I would like the price to adjust accordingly to topping's click. Please show me the examples @_@




mardi 20 juillet 2021

Assign the value of a checkbox to a FormControlName (Angular)

I have a reactive form and want to take the value of a checkbox (not 'true' or 'false') and assign it to a formControlName (selectedSizeValueControl).

I have try some method but they do not work for me.

Can anyone please help?

The code:

<form [formGroup]="variantForm" (ngSubmit) = "submit()">

  <mat-checkbox value="" formControlName = "selectedSizeValueControl"  ></mat-checkbox>-->
 
  <mat-radio-button value=""><input type="text" #sale_preis formControlName ="sale_preis"></mat-radio-button>

  <button >save</button>
</form>



lundi 19 juillet 2021

React.js Chakra UI multi-checkbox with use state

Hello everyone I am trying to implement a react.js checkboxes from an array and store the checked values in the state with the UseState hook. I am able to display the checkboxes but am unable to check and uncheck them. I am new to react and come from a Vuejs background and am used to the v-model sytax. Any help here would be great. Heres my code:

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory, useLocation } from 'react-router-dom';
import {
  Box,
  Button,
  Checkbox,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
} from '@chakra-ui/react';
import { Form, Input, message } from 'antd';
import styled from 'styled-components';
import useQueryParams from 'utilities/useQueryParams';

import useDelayedServiceCall from '../../../../utilities/useDelayedServiceCall';
interface FormValues {
  query: string;
}

interface SqlQueryRequest {
  query: string;
}

interface SqlQueryResponse {
  column_names: string[];
  rows: string[][];
}
const INITIAL_VALUES: FormValues = {
  query: '',
};
const initArray = [
  'First Name',
  'Middle Name',
  'Last Name',
  'Full Name',
  'Birthday',
  'Address',
  'Email',
  'Phone Number',
  'Ip Address',
  'Aliases',
  'Sign up date',
];
const newArray = initArray.map((item) => ({ value: item, checked: false }));
export default function SqlQueryForm() {
  const [checked, setChecked] = useState(newArray);
  const [array, setArray] = useState(newArray);
  const { t } = useTranslation([
    'actions',
    'common',
    'validations',
    'translation',
  ]);
  function handleCheck(e: any) {
    console.log('e', e);
    if (checked.includes(e.target.value)) {
      const index = checked.indexOf(e.target.value);
      checked.splice(index, 1);
    } else {
      setChecked([
        ...checked,
        {
          value: e.target.value.toString(),
          checked: Boolean(e.target.value.checked),
        },
      ]);
    }
  }
  const query = useQueryParams().get('query')?.trim();
  const history = useHistory();
  const location = useLocation();
  const [{ data, loading }, sqlQuery] = useDelayedServiceCall<
    SqlQueryResponse,
    SqlQueryRequest
  >(
    'franklin',
    'SqlQuery',
    undefined,
    (error) =>
      void message.error(t('common:events.error', { error: error?.message })),
  );
  const vertical = data?.rows[0]?.map((_, columnIndex) =>
    data.rows.map((row) => row[columnIndex]),
  );
  function handleFinish(values: FormValues) {
    const { query: newQuery } = values;
    const path = `${location.pathname}?query=${newQuery}`;
    history.replace(path);
    sqlQuery(values);
  }

  return (
    <>
      <p>
        The PII Reporter tool provides authorized personal access to customer
        PII information. All activity on this API is logged and access is
        reported. Elevated franklin privileges are required to perform the
        underlying actions.
      </p>
      <Box width="60vw">
        <Form>
          <Form.Item>
            <Input type="email" placeholder="email" />
          </Form.Item>
          <Form.Item>
            <Input.TextArea
              disabled={loading}
              rows={5}
              style=
            />
          </Form.Item>
          {newArray.map((item, index) => (
            <Checkbox
              key={Math.random()}
              {...item}
              onChange={handleCheck}
              isChecked={checked.toString().includes(item.value)}
            >
              {item.value}
            </Checkbox>
          ))}
        </Form>
      </Box>
    </>
  );
}



How to reset checkboxes each time component renders in ReactJS

I have a reactJS component below where I'm rendering 3 buttons. Each button, when clicked, updates this.state.networks with a new list of networks. Each time the reactJS component is rendered, a checkbox is made for each network in this.state.networks. However I notice that if I uncheck one checkbox and then hit any button again to change this.state.networks that checkbox is still unchecked however it may now be unchecked for a different network.

What I'd like to do is have ALL of the checkboxes checked each time a button is clicked. That way if you uncheck a checkbox but then hit a button to update this.state.networks and hence the checkboxes, all of the checkboxes are 'reset' or checked.

To see this in action go to my notebook: https://observablehq.com/@reneelempert/react-example

class Mychart extends React.Component {

constructor(props) {
  
  super(props);
  this.state = {
    networks: ['BET', 'BHER', 'CMDY', 'CMT', 'DISJR', 'DSNY', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TOON', 'TVL', 'VH1'],
    customBtnSelected: 'all'
  };
  this.removedNets = [];
  this.buttons = [
    {update: ['BET', 'BHER', 'CMDY', 'CMT', 'DISJR', 'DSNY', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TOON', 'TVL', 'VH1'], label: 'Show All', key: 'all'}, 
    {update: ['DISJR', 'DSNY', 'NICK', 'NKJR', 'NKTNS', 'TNNK', 'TOON'], label: 'Show Kids Nets Only', key: 'kids'},
    {update: ['BET', 'BHER', 'CMDY', 'CMT', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TVL', 'VH1'], label: 'Show Legacy Viacom Only', key: 'legacy'}
  ];
  
}

createElements() {
  
  const buttons = this.buttons.map((button) => {
    return React.createElement( 'button', { className: button.key === this.state.customBtnSelected ? 'custom-btn selected' : 'custom-btn unselected', onClick: () => {this.setState({customBtnSelected: button.key, title: button.title, networks: button.update}) } }, button.label)
  });
  
  const mydiv = React.createElement('div', {}, null);
  
  const checkBoxes = this.state.networks.map((brand) => {
     return React.createElement('div', {class: 'brand-check', id: brand, style: {display: 'inline', paddingLeft: 5, paddingRight: 5}}, [React.createElement('input', {type: 'checkbox', name: brand, defaultChecked: 'checked', onClick: () => {console.log('clicked');} }, null), React.createElement('label', {for: brand, style: {fontSize: 13}}, brand)] )}
  );
  
  const myElements = buttons.concat(mydiv, checkBoxes);
  
  return myElements;

}

render() {
  const myElements = this.createElements();
  return (myElements);
}

}

// Instantiate the react component and render it
let parent = html`<div>`;
ReactDOM.render(React.createElement(Mychart), parent);



With a pure css accordion with checkbox, can you open and close all open tabs?

Code is from here --> https://codepen.io/raubaca/pen/PZzpVe

I have looked at the other answers to questions similar to this. Nothing actually answers this question sufficiently. Or else they're about slightly convergent issues, or use jquery etc, or for css in a different format.

When using the checkbox method to make a pure css accordion where you can have multiple tabs open at one time, is it possible to close all the tabs at once? And also open all the tabs at once? I'm assuming I can do something like input:unchecked ~ .tab-content {...} But there's no input:unchecked in the css specs.

@charset "UTF-8";
body {
  color: #2c3e50;
  background: #ecf0f1;
  padding: 0 1em 1em;
}

h1 {
  margin: 0;
  line-height: 2;
  text-align: center;
}

h2 {
  margin: 0 0 0.5em;
  font-weight: normal;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

.row {
  display: flex;
}
.row .col {
  flex: 1;
}
.row .col:last-child {
  margin-left: 1em;
}

/* Accordion styles */
.tabs {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 4px -2px rgba(0, 0, 0, 0.5);
}

.tab {
  width: 100%;
  color: white;
  overflow: hidden;
}
.tab-label {
  display: flex;
  justify-content: space-between;
  padding: 1em;
  background: #2c3e50;
  font-weight: bold;
  cursor: pointer;
  /* Icon */
}
.tab-label:hover {
  background: #1a252f;
}
.tab-label::after {
  content: "❯";
  width: 1em;
  height: 1em;
  text-align: center;
  transition: all 0.35s;
}
.tab-content {
  max-height: 0;
  padding: 0 1em;
  color: #2c3e50;
  background: white;
  transition: all 0.35s;
}
.tab-close, .tab-open {
  display: flex;
  justify-content: flex-end;
  padding: 1em;
  font-size: 0.75em;
  background: #2c3e50;
  cursor: pointer;
}
.tab-close:hover {
  background: #1a252f;
}

input:checked + .tab-label {
  background: #1a252f;
}
input:checked + .tab-label::after {
  transform: rotate(90deg);
}
input:checked ~ .tab-content {
  max-height: 100vh;
  padding: 1em;
}
        <!-- <h1>Pure CSS Accordion <sup>2.0</sup></h1> -->
        <div class="row">
          <div class="col">
            <h2>Open <b>multiple</b></h2>
            <div class="tabs">
                <div class="tab">
                    <input type="checkbox" id="chck0" name="chk">
                    <label for="chck0" class="tab-open">Open All &times;</label>
                  </div>
              <div class="tab">
                <input type="checkbox" id="chck1"  name="chk">
                <label class="tab-label" for="chck1">Item 1</label>
                <div class="tab-content">
                  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ipsum, reiciendis!
                </div>
              </div>
              <div class="tab">
                <input type="checkbox" id="chck2"  name="chk">
                <label class="tab-label" for="chck2">Item 2</label>
                <div class="tab-content">
                  Lorem ipsum dolor sit amet consectetur adipisicing elit. A, in!
                </div>
              </div>
              <div class="tab">
                <input type="checkbox" id="chck3" name="chk">
                <label for="chck3" class="tab-close">Close All &times;</label>
              </div>
            </div>
          </div>



dimanche 18 juillet 2021

Checkbox activity on my Android Example shows error with multiple texts show/hide option

This may be a silly question, but I am struck halfway when I tried to create a simple app with a checkbox. When I use the checkbox to show and hide a single text, this works fine. But if it's for a second text, the app crashes. I wanted to hide one text and show another when the checkbox is clicked.

enter image description here

Here is the code

        if (isChecked) {
            txtHelloWorld.setVisibility(View.VISIBLE);
            txtHelloWorldChecked.setVisibility(View.INVISIBLE);

        } else {

            txtHelloWorld.setVisibility(View.INVISIBLE);
            txtHelloWorldChecked.setVisibility(View.VISIBLE);

        }
    }



samedi 17 juillet 2021

Angular 11 checkbox options like Gmail

I am trying to do a checkbox with options like Gmail

Option Image

I wrote functions to select all and deselect all. But I don't know how to bind them.

.ts

  checkedRow = false;
  checkedAll = false;

  AllSelectedHandler(checked: boolean, book){
      // this is done to select all and deselect all
   }

.html

 <nb-checkbox [value]= "books" [checked]="checkedAll" (checkedChange)="AllSelectedHandler($event, books)" ></nb-checkbox>  //this is worked

 <select name="delete-option" id="delete-option" ><i class="nb-arrow-dropdown fa-1x"></i> 
          <option  value="all" >All</option>
           <option value="none" > None</option>
 </select>

I need how to bind inside the tag




Possible to automatically add multiple checkboxes to Excel from SQL Query?

I have the following data in a view that is output to an Excel sheet via a query.

+----------+---------+---------------+
| Verified | Deleted |      Name     |
+----------+---------+---------------+
|     0    |    0    | Sean Hull     |
|     1    |    0    | Bonnie Davis  |
|     0    |    0    | John Smith    |
|     0    |    1    | Evel Knieval  |
|     1    |    1    | Bart Simpson  |
|     0    |    0    | Peter Griffin |
+----------+---------+---------------+

Ideally the first two columns would convert to checkboxes with 1 = Checked, and 0 = Unchecked, but I'm fairly certain that is not possible. I have added two columns to the right the table so the sheet looks something like this.

+----------+---------+----------+---------+---------------+
| Verified | Deleted | Verified | Deleted |      Name     |
+----------+---------+----------+---------+---------------+
|          |         |     0    |    0    | Sean Hull     |
|          |         |     1    |    0    | Bonnie Davis  |
|          |         |     0    |    0    | John Smith    |
|          |         |     0    |    1    | Evel Knieval  |
|          |         |     1    |    1    | Bart Simpson  |
|          |         |     0    |    0    | Peter Griffin |
+----------+---------+----------+---------+---------------+

I know I can add a Checkbox via the Developer area, however I have to then manually format the control to set the Cell Link.

Is it possible to automatically create a linked Checkbox? I don't think I can avoid having to edit the sheet to add the additional columns, but if the checkboxes could be created in some kind of automated way, that would be a huge help as I have a couple views with a couple thousand rows, and manually linking each one isn't really an option.




Angular 11 Select All, Deselect All check boxes like Gmail

I am trying to do check boxes with select all and deselect all options.

I have faced an issue that,

first I checked all option(that works), secondly I uncheck one or more checkboxs(NOT CheckALL one)(that is also works). finally i check all option(This does not works)

(when I select all options that is OK ( all checkbox are checked) when I deselect all options that is OK ( all checkbox are unchecked))

Output is :

Screenshot of Output

.component.ts file

AllSelectedHandler(checked: boolean, book) {
    const idArr = book.map(i => i.id);
    console.log("ID array " + idArr);

    if (checked == true) {
      this.checkedAll = true;
      this.checkedRow = true;

      idArr.forEach(id => {

        if (this.checkedAll == true) {
          this.checkedRow = true;
          console.log("checkedRow works ")
          console.log(this.checkedRow)
        }

        if (this.checkedRows.includes(id)) {
          this.checkedRows.push();
          console.log("if works");
        }
        else {
          this.checkedRows.push(id);
         // this.checkedRow = true;
          console.log("else works");
          console.log("id is " + id);
        }

      });

      console.log(this.checkedRows);
      console.log("checked row" + this.checkedRows);

      const numSelected = this.checkedRows.length;
      console.log("no of selected" + numSelected);
    }
    else {
      this.checkedAll = false;
      this.checkedRow = false;
      this.checkedRows = [];
      this.multipleDelete = false;
      console.log(this.checkedRows);
    }
    const numRows = this.books.length;
    console.log("no of rows " + numRows);
  }

.html

  <nb-checkbox [value]= "books" [checked]="checkedAll" (checkedChange)="AllSelectedHandler($event, books)" ></nb-checkbox>
                        
  <nb-checkbox value= [checked]="checkedRow"
                        (checkedChange)="CheckboxChangeHandler($event, data.id)"></nb-checkbox>

In console:

ID array 23,22,21,2,1

checkedRow works 
true
else works
id is 23

checkedRow works 
true
else works
id is 22

checkedRow works 
true
if works

checkedRow works 
true
if works

checkedRow works 
true
if works

(5) [21, 2, 1, 23, 22]

checkedrows 21,2,1,23,22

no of selected 5

no of rows 5

Here notice that All checkedRow values are true. But in output check box is unchecked.

Please can anyone tell what is the issue?




How can i show automating checkbox from database using java? [closed]

In a desktop application that I have created, I want to display a checkbox whose data comes from a database. How can I do it? I use netbeans as my IDE. Thank you..




vendredi 16 juillet 2021

Can't download excel file from php

My index page is working and it alerts when no checkbox is checked but my download button to excel won't function. What might be the problem with this? Any tips on how to solve this one? Not fully understand the checkbox functioning, anyone can help me?

<?php  
//export.php  
require_once "connection.php";
$output = '';

if(isset($_POST["id"]))
{
  foreach($_POST["id"] as $id)
  {
    $query = "SELECT * FROM allowance WHERE id = '".$id."'";
    $result = mysqli_query($connect, $query);

    if(mysqli_num_rows($result) > 0)
    {
      $output .= '
      <table class="table" bordered="1">  
                    <tr>  
                      <th>Name</th>
                      <th>Scholarship Program</th>
                      <th>Course</th>
                      <th>Semester</th>
                      <th>Status</th>
                    </tr>
      ';

      while($row = mysqli_fetch_array($result))
      {
          $output .= '
          <tr>  
                         <td>'.$row["Name"].'</td>  Name
                         <td>'.$row["Scholarship Program"].'</td>  
                         <td>'.$row["Course"].'</td>  
                         <td>'.$row["Semester"].'</td>  
                         <td>'.$row["Status"].'</td>
          </tr>
          ';
      }

      $output .= '</table>';
      header('Content-Type: application/xls');
      header('Content-Disposition: attachment; filename=download.xls');
      echo $output;
    }
  }
}
?>



Trying to make a userform with Checkboxes to choose which sheets need to be exported as a PDF and put in a mail

Hi I'am an beginner but I'm looking for a way where I can connect a userform with checkboxes so I can choose which sheets I want to export as a pdf and send with the following sub: I'll also include the file with the userform.

      Sub Saveaspdfandsend()
'dim everything
    Dim xSht As Worksheet
    Dim xFileDlg As FileDialog
    Dim xFolder As String
    Dim xYesorNo As Integer
    Dim xOutlookObj As Object
    Dim xEmailObj As Object
    Dim xUsedRng As Range
     
    Set xSht = ActiveSheet
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
     
    If xFileDlg.Show = True Then
       xFolder = xFileDlg.SelectedItems(1)
    Else
       MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
       Exit Sub
    End If
    xFolder = xFolder + "\" + xSht.Name + ".pdf"
     
    'Check if file already exist
    If Len(Dir(xFolder)) > 0 Then
        xYesorNo = MsgBox(xFolder & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", _
                          vbYesNo + vbQuestion, "File Exists")
        On Error Resume Next
        If xYesorNo = vbYes Then
            Kill xFolder
        Else
            MsgBox "if you don't overwrite the existing PDF, I can't continue." _
                        & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"
            Exit Sub
        End If
        If Err.Number <> 0 Then
            MsgBox "Unable to delete existing file.  Please make sure the file is not open or write protected." _
                        & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"
            Exit Sub
        End If
    End If
     
    Set xUsedRng = xSht.UsedRange
    If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
        'Save as PDF file
        xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder, Quality:=xlQualityStandard
         
        'Create Outlook email
        Set xOutlookObj = CreateObject("Outlook.Application")
        Set xEmailObj = xOutlookObj.CreateItem(0)
        With xEmailObj
            .Display
            .To = ""
            .CC = ""
            .Subject = xSht.Name + ".pdf"
            .Attachments.Add xFolder
            If DisplayEmail = False Then
                '.Send
            End If
        End With
    Else
      MsgBox "The active worksheet cannot be blank"
      Exit Sub
    End If
    End Sub   I

I am looking for a way in which i can choose which sheets i want to export and not. I am planning to do that with a userform with checkboxes.

if you have a better solution let me know!

kind regards!




Vaadin-Grid: Select all check box does not work in the UI

Problem:

I have a grid with lazy loading and therefor my data is not in memory.

To show the check box to select/deselct all i used this Question. My code looks like this:

// set selection mode
grid.setSelectionMode(SelectionMode.MULTI);
// make select all check box visible
GridSelectionModel<ProofTemplate> selectionModel = grid.getSelectionModel();
((GridMultiSelectionModel<ProofTemplate>) selectionModel)
    .setSelectAllCheckboxVisibility(SelectAllCheckboxVisibility.VISIBLE);

The Problem is, that the check box does not work in the UI as you can see:

enter image description here

If i log the selected items with the following code the check box works as expected

grid.addSelectionListener(l -> {
    log.info("selected: " + l.getAllSelectedItems().size());
});

Question:

What can i do that the check box also works in the UI?