mardi 28 février 2023

Getting CheckBox checked state in a Python FMX GUI app

I've created a small app in the DelphiFMX GUI library for Python that has a Checkbox, Button, and Label on it:

Python GUI form with checkbox, button and label

When I click on the button, then I simply want to check the checked state of the checkbox and then write into the label whether it is checked or not. I have the following code currently for clicking on the button, but it doesn't work:

def Button_OnClick(self, sender):
    if self.myCheckBox.Checked:
        self.myLabel.Text = "The Checkbox is Checked"
    else:
        self.myLabel.Text = "The Checkbox is Unchecked"

When I click on the button, then I get the following run-time error AttributeError: Error in getting property "Checked". Error: Unknown attribute:

AttributeError: Error in getting property "Checked". Error: Unknown attribute

What is the correct or best way to get the Checked state of a CheckBox component?




lundi 27 février 2023

Checked box by google sheet

How can I uncheck the box by checking another one using the script app in google Sheets? I.e When A1 is checked and the B1 is checked so A1 is supposed to be unchecked

How can I uncheck the box by checking another one using the script app in google Sheets? I.e When A1 is checked and the B1 is checked so A1 is supposed to be unchecked ....




In react native, how can I create a system where a check box is checked, then the other one one is unchecked automatically?

This is the UI of the app

Here are just two plain check boxes. I'm using Expo Checkbox for a checkbox in react native.

I'd like to create an system where a checkbox is checked, then the other one is unchecked automatically.

Here are codes that I created so far.

import React, { useState } from "react";
import { View, StyleSheet } from "react-native";
import Checkbox from "expo-checkbox";

function ForChecked() {
  const [isChecked, setChecked] = useState("false");
  const [isChecked2, setChecked2] = useState("false");

  return (
    <View style={styles.container}>
      <Checkbox value={isChecked} onValueChange={setChecked} />
      <Checkbox
        value={isChecked2}
        onValueChange={setChecked2}
        onPress={setChecked((pre) => !pre)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default ForChecked;

I thought that this would work, but somehow it didn't. How can I accomplish this? Thank you in advance




dimanche 26 février 2023

State of timeEdit not updated in PyQt5

I have written a python code using the PyQt5 library to give a graphic to the application and would like the TimeEdit to be disabled/enabled when a CheckBox is clicked. That is, I would like when the CheckBox is checked TimeEdit to be enabled and when the CheckBox is not checked TimeEdit to be disabled.

I tried using this code which is executed first but the state of the TimeEdit does not change: def during(self): if self.checkBox_3.isChecked() == False: self.timeEdit.setEnabled(False) else: self.timeEdit.setEnabled(True)

Obviously at the beginning of the code I declared both the checkbox and the timeEdit

self.timeEdit.setGeometry(QtCore.QRect(20, 50, 93, 22)) self.timeEdit.setStyleSheet("background-color:rgb(255, 255, 255)") self.timeEdit.setObjectName("timeEdit") self.checkBox_3 = QtWidgets.QCheckBox(self.groupBox_4) self.checkBox_3.setGeometry(QtCore.QRect(10, 20, 110, 21)) self.checkBox_3.setObjectName("checkBox_3")

As a programming space I use Visual Studio Code




samedi 25 février 2023

How to uncheck all checkboxes on two separate rows in google sheets

I have a spreadsheet that will be used as a check sheet on an ambulance. There are two rows that have check boxes and I want to be able to have a button or a check box and set a trigger to turn these to false. I started using this and it worked the first time I used it but when I created a button and assigned the script it no longer worked.

function uncheckAllCheckboxes() {
   var range = SpreadsheetApp.getActive().getRange('A2:A45');
   var range = SpreadsheetApp.getActive().getRange('D2:D45');
   range.uncheck();
}

I have Checkboxes in cells A2 through A45 and again on D2 though D 34. I thought I had figured it out but I am still learning. Any Help would be appreciated.




Property 'checked' does not exist on type 'EventTarget'

I'm trying to collect all of the id's in an array from this checkbox list. I keep getting the error above telling me that checked does not exist on type EventTarget. This data used to populate the list group is input from a parent component. I want to be able to check the boxes to send the id array to function.

    <div class="overflow-auto" style="max-height: 25em;">
    <div class="p-3">
        <form [formGroup]="myForm" class="list-group">
            <li class="list-group-item" *ngFor="let credit of credits; let i = index">

                <input class="form-check-input me-2"
                       type="checkbox" 
                       #checkbox
                       (change)="onChange(credits[i].id, $event.target.checked)" />  // error happens here with .checked
                <label for=""> - <span class="text-muted"></span></label>


            </li>
            
        </form>
    </div>
</div>

Here is the component

    import { Component, Input, OnInit } from '@angular/core';
import { CastEntity } from '../movie-credits';
import { FormGroup, FormBuilder, FormArray, FormControl } from '@angular/forms';


@Component({
  selector: 'app-connected-movies',
  templateUrl: './connected-movies.component.html',
  styleUrls: ['./connected-movies.component.css']
})
export class ConnectedMoviesComponent implements OnInit {

  @Input() credits!: any;

  myForm!: FormGroup

   
  constructor(private fb: FormBuilder) { 
    
  }

  ngOnInit(){
    this.myForm = this.fb.group({
      credits: this.fb.array([])
    });   
  }

  onChange(id: string, isChecked: boolean) {
    const creditsFormArray = <FormArray>this.myForm.controls.credits;
    
    if (isChecked) {
      creditsFormArray.push(new FormControl(id));
    } else {
      let index = creditsFormArray.controls.findIndex(x => x.value == id)
      creditsFormArray.removeAt(index);
    }
  }

 
}



vendredi 24 février 2023

Echoing multiple check boxes

I am trying to write some code for a collection form for a fake dating form. I'd like the form, or the 'end' screen repeat back what the user has put in for their information.

I have text fields and radio buttons that I was able to repeat back to the user but for some reason when I do the check box portion of it, it is only repeating back the last answer I gave. (I know this isn't the correct code, but I am currently not knowledgeable about other solutions)

For example, this is what I have coded now, when I select 'men' and 'women'.

                if($_POST['pg'] == 'M') {
                    echo "You are attracted to men"."<br>";
                } else if ($_POST['pg'] == 'F') {
                    echo "You are attracted to women"."<br>";
                } else {
                    echo "You are attracted to gender neutral people"."<br>";
                }

I only receive the echo "You are attracted to women" is there anyway I can get multiple repeated back to me?




Record with 'all' in database

I have the following hypothetical scenario:

A user can toggle aircraft categories wether he is interested or not. If the user toggles Helicoper the following checkboxes with sub-categories will appear:

'Chinook', 'Apache', 'Cargo', 'Military'

to which the user can select from in form of checkboxes.

If the user toggles Airplane the following checkboxes with sub-categories will appear:

'Passenger', 'Ultralight', 'Cessna', 'Cargo', 'Military'

The following tables are designed to store the user's (id: 1) options:

aircraft_type

id | name   
1    Helicopter
2    Airplane

aircraft_class

id |  name   
1     Chinook
2     Apache
3     Ultralight
4     Cessna
5     Cargo
6     Military 

aircraft_x_class

id | aircraft_id  |  aircraft_class_id
1       1     |        1  
2       1     |        2
2       1     |        5
2       1     |        6
3       2     |        3
4       2     |        4
5       2     |        5
6       2     |        6

user_x_aircraft_x_type_x_class

id | user_id | Aircraft_x_class_id
1      1           1 
2      1           2
3      1           3

Now if I happen to have 1000 users who all selected every aircraft_class then the records pile up quickly.

To prevent (perhaps) unnecesseary records in my joint-tables I have thought of the following option at aircraft_model which is 'all'.

aircraft_class

id |  name 
....  
7     all

aircraft_x_class

id | aircraft_id  |  aircraft_class_id
....
7       1     |        7 
8       2     |        7

So when a user selects every aircraft_class of a certain type, it will not create all the records, but instead just one that states 'all'

user_x_aircraft_x_type_x_class

id | user_id | Aircraft_x_class_id
1      1           7

Question

Is this a common/good thing to do to reduce records at nested options? Are there perhaps better ways?




jeudi 23 février 2023

Checkboxes become unchecked after going back to the previous page

I want to be able to save the values of the checkboxes and have the already checked ones displayed as checked even after I go back to the previous page and again to the next page. In all cases, I do not want the checked boxes to disappear. Here is what I have written as for the HTML code:

<style>
    .add-margin {
        margin-top:10px !important;
    }
</style>
<div>
    <div ng-init="loaded()" ng-class="{'add-margin': descriptionsAvailable}" class="checkbox-inline" ng-repeat="opt in options track by $index">
        <label style="direction:ltr;">
            <input ng-disabled="answer['none']" class="save-cb-state" type="checkbox" ng-model="answer[opt]" ng-true-value="true" ng-false-value="false" name="checkbox-answer-input" display= "inline-block", style = "width: 15px; padding: 0; margin: 0; position: relative; top: 0px; align-items: center;">
            <span></span><br/>
            <span><i></i></span>
        </label>
      </div>

</div>

Here is the JavaScript code:

function() {
  // variable to store our current state
  var cbstate;

  // bind to the onload event
  window.addEventListener('load', function() {
    // Get the current state from localstorage
    // State is stored as a JSON string
    cbstate = JSON.parse(localStorage['CBState'] || '{}');

    // Loop through state array and restore checked
    // state for matching elements
    for(var i in cbstate) {
      var el = document.querySelector('input[name="' + i + '"]');
      if (el) el.checked = true;
    }

    // Get all checkboxes that you want to monitor state for
    var cb = document.getElementsByClassName('save-cb-state');

    // Loop through results and ...
    for(var i = 0; i < cb.length; i++) {

      //bind click event handler
      cb[i].addEventListener('click', function(evt) {
        // If checkboxe is checked then save to state
        if (this.checked) {
          cbstate[this.name] = true;
        }

    // Else remove from state
        else if (cbstate[this.name]) {
          delete cbstate[this.name];
        }

    // Persist state
        localStorage.CBState = JSON.stringify(cbstate);
      });
    }
  });
})();

However, when I go back to the previous page, the previously checked boxes are unchecked. This holds true as well when proceeding to the next page again.




Angular how do I implement mutually exclusive checkbox

        <div>
            <input type="checkbox" class="toggle" name="coordinatorSearch" id="coordinatorSearch" formControlName="coordinatorFilter" (click)="validateOption($event)"/>
            <label for="coordinatorSearch">Coordinator</label>
        </div>
        <div>
            <input type="checkbox" class="toggle" name="employeeSearch" id="employeeSearch" formControlName="employeeFilter" (click)="validateOption($event)"/>
            <label for="employeeSearch">Employee</label>
        </div>

How do I make these checkboxes mutually exclusive? If the user clicks the 'employeeSearch' to the on poistion then we toggle the 'coordinatorSearch' off (if it had been on)

I just don't want two switches turned on but both can be turned off.




mercredi 22 février 2023

How to format html form checkbox URL parameters to \?var1=X,Y,Z&var2=A,B,C&var3=1,2,3

I have developed a job board and need to give the user 3 types of filters:

  • Job Type

    • 1
    • 2
    • 3...
  • Region Name

    • 1
    • 2
    • 3...
  • Salary Range

    • 1
    • 2
    • 3...

I want to send the results of a user checking any combination of boxes to the URL and have it formatted like /?JT=1,3&RN=2,3&SR=1

With the help of @darkbee I have this code which works for one variable, but I didn't have the foresight to ask how to do it for three:

document.addEventListener("DOMContentLoaded", function() {
  let form = document.getElementById('myform');
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    let checkboxes = [];
    document.getElementsByName('JT').forEach(function(checkbox) {
      if (checkbox.checked) checkboxes.push(checkbox.value);
    });
    window.location = '?JT=' + checkboxes.join(',');
  });
});
<form id="myform">
  <div class="form-group">
    <input type="checkbox" name="JT" value="1">
    <label>Label X</label>
    <input type="checkbox" name="JT" value="2">
    <label>Label Y</label>
    <input type="checkbox" name="JT" value="3">
    <label>Label Z</label>
  </div>
  <div class="form-group">
    <button type="submit" class="button button1">Submit</button>
  </div>
</form>

I tried to solve the problem with three separate forms, each with DarkBee's modified code, but I could get to work was one at a time - that is, I couldn't choose checkboxes from multiple filter options.

If anyone can help, I'd be very happy.




mardi 21 février 2023

ERRO: Estou tentando colocar um limite o usuário selecionar o checkbox [closed]

O código funciona em outro ambiente, não sei se é por conta da api json que estou usando os dados estão sendo carregados através dele. Preciso de ajuda, por favorenter image description hereenter image description here

Resolver o problema!!!!




Twig: How to format html from checkbox URL parameters to \?var1=X,Y,Z

I have a html form that sends the parameters of a checkbox group (X,Y,Z) to the URL like this:

https://mycompany.com/?var1=X&var1=Y&var1=Z

I want to change the way the form sends the variables so the URL is formatted like this:

https://mycompany.com/?var1=X,Y,Z

I’m happy to use any type of code but prefer twig.

Any thoughts or advice would be greatly appreciated.

Being a newbie at this level, I’ve tried to guess various twig and Java scripts with nothing delivering the ideal outcome above.




Align ASP checkbox CSS label styling

I am using an ASP checkbox within a website I have built. The problem I'm having is that the text is aligning with the top of the checkbox because I've applied:

display: inline !important;

This is much better than if I don't add this, because otherwise it sits at the top of the space and not anywhere near the checkbox! However it looks like it is sitting a little high. Is there an easy way to make the text sit in the middle next to the checkbox? I've included a screenshot to show what I mean.

I'm not very experienced with CSS but I've tried adding margins and padding and neither have worked.

My code looks like this:

C#

<div class="col-sm-3 form-group">
   <asp:CheckBox ID="CheckBox1" runat="server" Text="Text is a little high" class="form-check-input" CssClass="chkbx_inline_top"/>
</div>

CSS

.chkbx_inline_top label {
    color: red !important;
    display: inline !important;
}

Picture showing text in red that I would like to move down

With the suggestion below and doing some more googling, I have now also tried this without luck:

https://stackoverflow.com/a/39939769/1860687

.chkbx_inline_top{
    display: flex !important;
    align-items: center !important;
}

.chkbx_inline_top label {
    align-self: flex-start !important;
}

But it hasn't worked for me:

Flex styling




lundi 20 février 2023

How can I create a custom checkbox button like this in flutter

Image here

I am trying a lot but I could make this, and I accidentally deleted my code and if somebody can help, I am so happy.




Headercheckbox checks true only all record selected.if one record diselect don't check header

<RadzenCheckBox TriState="false" TValue="bool" Value="@(chequeBooklist. Any(1->chequeBookSelected I=null & chequeBookSelected.Contains(i)))

Change (args=> chequeBookSelected= args? chequeBookList.ToList():null

<RadzenCheckBox TriState="false" TValue="bool" Value="@(chequeBookSelected !=null && chequeBookSelected.Contains(chequebook))" Change (args =>{if(!allowRowSelectOnRowClick) {Cheque BooksGrid. SelectRow(chequebook);}})"/

/RadzenDataGridColumn>

selectedHeadercheckbox checks true only all record selected.if one record diselect don't check header.but in my code i select only one record then also header checkbox




dimanche 19 février 2023

Laravel ReactJs cant check or uncheck checkboxes

I want to create an edit a from containing checkboxes. I have initial ids to auto-check the checkboxes. If I use attribute check on Input checkbox, I can't change the checked/unchecked UI.

This is my html:

{props.ids.map((val, key) => {
    return (
        <div key={key}>
            <div className="form-control">
                <label className="label cursor-pointer">
                    <input 
                        type="checkbox" 
                        name="ids"
                        checked={data.ids.includes(val.id)} 
                        className="checkbox"
                        id={val.id}
                        value={val.id}
                        onChange={(e) => handleChange(e)} 
                    />
                    <span className="label-text">{val.name} ({val.id})</span> 
                </label>
            </div>
        </div>
    )
})}

This is my handleChange function and useForm:

const { data, setData, patch, errors, processing, recentlySuccessful } = useForm({
    ids: initialIds,
});

const handleChange = (e) => {
    let tempArray = [];
    if (e.target.checked)
    {
        if (_.indexOf(data.ids, e.target.value) === -1)
        {
            tempArray = [...data.ids, e.target.value];
        } else {
            tempArray = [...data.ids];
        }
    } else {
        tempArray = data.ids.filter(val => val !== e.target.value)
    }


    setData(e.target.name, tempArray);
};

Seems check attribute on Input resulting I can't check/uncheck the UI even though the handleChange function is fired when I click the checkbox.

Am I missing something? Any idea how to fix this?




samedi 18 février 2023

Styling checkbox with Tailwind not working

I have a checkbox in my Next project and after added some styles nothings happens except changes in width, height and cursor. But color, bg, border, etc. doesn't work.

<div className="flex py-4 m-auto w-2/3 justify-between items-start">
          <div className="w-1/7">
            <div className="border-b pb-4">
              <h1 className="mb-2 font-medium">Filter 1</h1>
              <label htmlFor="c1">
                <div className="flex group active:ring-2 ring-black rounded">
                  <input
                    id="c1"
                    type="checkbox"
                    className="rounded-full h-8 w-8 cursor-pointer bg-red-100 border-red-300 text-red-600 focus:ring-red-200"
                  />
                  <p className="pl-2 text-reg cursor-pointer group-hover:underline decoration-solid">
                    Subfilter 1
                  </p>
                </div>
              </label>
            </div>
          </div>
        </div>

h-8 and w-8 are the only two tailwind classes that actually work in the checkbox (and cursor pointer too), color still default blue, no ring appears on focus, bg still white. Others elements in the example code like p, div and h1 are working perfect




Yii2 Using Multiple Checkbox Fields

I have a Yii2 app in which I want to use multiple checkbox as array. The checkbox is part of my Model, but it's not a DB column. It also has a custom value.

I loop through a list of days, set a custom value for the checkboxes and print the checkboxes to my view like this:

echo $form->field($model, 'dayIds[]')->checkbox(
            ['value' => $day->id.'_'.$person->id])->label(false);

On my Model side I have this:

public $dayIds;

foreach ($this->dayIds as $dayId) {
     //do something
}

I have tried many different scenarios but always end up with error on my Model that $this->dayIds is null.

Any ideas please?




vendredi 17 février 2023

Correct way of updating checkbox with keyboard press in React

I've got the following code:

export default function Tag(props: { tag: ITag, setTag: (tag: string) => void }) {
    const [checked, setChecked] = useState(false)

    const handleTagChange = () => {
        props.setTag(props.tag.abbreviation);
        var element = document.getElementById(props.tag.abbreviation);
        if (!checked) {
            element?.classList.add("label-toggle")
        }
        else {
            element?.classList.remove("label-toggle")
        }
        setChecked(!checked)
    }

    return (
        <div id={props.tag.abbreviation} className='label-button' onClick={handleTagChange}>
            <input id='check' key={props.tag.hotkey} checked={checked} onChange={handleTagChange} type="checkbox" />
            <div className='label-title'>{props.tag.abbreviation}</div>
            <div className='label-icon' style=></div>
            <div className='label-hotkey'>{props.tag.hotkey}</div>
        </div>
        
    )

Everything works as expected if I use mouse click to trigger the checkbox. It works both if I press on the checkbox or the surrounding div with function handleTagChange()

I've added a key listener, so that the checkbox can be triggered with a keyboard key press.

const handleHotKey = (e: KeyboardEvent) => {
    if (e.key == props.tag.hotkey) {
        handleTagChange();
    }
}

useEffect(() => {
    document.addEventListener('keydown', e => { handleHotKey(e) }, false)
}, [])

Key listener works, key press is detected, however the value of the checked state simply does not update.

I have no clue what I'm doing wrong. What is the correct way to achieve this?

Thanks.




How can I multi-select items in the model using picker in xamarin or otherwise?

xaml.cs page:

public partial class TalimatGorevEkle : ContentPage
    {
        TalimatGorevModelmobil Model;
        
        public TalimatGorevEkle() { 

            InitializeComponent();
            var kullanicilist = Methodlar.GorevliListeGetir(Sabitler.Token);
           
            
            KullaniciSec.ItemsSource = kullanicilist.GorevliListe;  //picker'da listelenecek kişiler

            
        }
    }

.xaml file:

<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="OzelKalem.Views.ListeContentViews.TalimatGorevEkle">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>
              
               <Grid>
                   <StackLayout  Grid.Row="0" Padding="8">
                       <Label Text="Görev Başlığı:" TextColor="#FF7F24" FontSize="14"></Label>
                       <Entry x:Name="talimatAdi" Placeholder="Görev Başlığı Giriniz" HeightRequest="60" ></Entry>
                       <Label Text="Görev Adı:" TextColor="#FF7F24" FontSize="14" ></Label>
                       <Entry x:Name="talimatGörevAdi" Placeholder="Görev Adı Giriniz" HeightRequest="60" ></Entry>
                       <Label Text= "Görevin Son Tarihini Seçiniz:" TextColor="#FF7F24" FontSize="14"></Label>
                       <DatePicker Format="dd-MM-yyyy HH:mm" x:Name="gorevSonTarih" TextColor="Black" ></DatePicker>
                       <Picker x:Name="KullaniciSec" Title="Kullanıcı seçiniz." ItemsSource="{Binding GorevliListeModel}" ItemDisplayBinding="{Binding GorevliKullaniciAdi}"></Picker>
                       <Button x:Name="SaveCourseButton" Clicked="GorevEkle" Command="{Binding}" Text="Kaydet" BackgroundColor="LightGray" TextColor="#FF7F24" Margin="3" />
                       
                   </StackLayout>


               </Grid>
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

I have a list in xamarin I have it displayed in picker. But I want it to be multiple selectable. How can I write for it? How should I select it as checkbox or over the picker? enter image description here




jeudi 16 février 2023

Update parent style if child has changed data-state or aria-checked

There is label that has a button inside of it like:

<label for="second">
    <button type="button" role="checkbox" aria-checked="false" data-state="unchecked" value="on" id="second">
    </button>
    Check it!
</label>

When the button is clicked, there are toggles between aria-checked="false" and aria-checked="true", also between data-state="unchecked" and data-state="checked".

Is there a way to update the style of the parent, the label in this case when those actions are happening?




Eliminate the empty spaces in QAbstractTableModel item when cell is checkable

I am trying to implement a custom QTableView. For that I am subclassing QAbstractTableModel such that it takes a list of strings. Here the implementation.

class ListTableModel(qtc.QAbstractTableModel):
def __init__(self, data: List[List[str]], headers: List[str] = None, edit: List[Union[int, Tuple[int, int]]] = None,
             checks: List[Union[int, Tuple[int, int]]] = None, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self._data = data
    self._headers = headers
    self._edit = edit
    self._checks = checks
    self._check_state = {}

    self.name = None

def get_name(self):
    return self.name

def set_name(self, name: str):
    self.name = name

def check_state(self, value, index):
    if index in self._check_state:
        return self._check_state[index]
    else:
        if value == 0:
            return qtc.Qt.Unchecked
        else:
            return qtc.Qt.Checked

def data(self, index, role):
    if index.isValid() or (0 <= index.row() < self.rowCount() and 0 <= index.column() < self.columnCount()):
        val = self._data[index.row()][index.column()]
        val = fast_real(val, coerce=False)
        if (role == qtc.Qt.DisplayRole or role == qtc.Qt.EditRole) and not index.flags() & qtc.Qt.ItemIsUserCheckable:
            if isinstance(val, float):
                return f"{val:.4f}"
            return str(val)

        if role == qtc.Qt.CheckStateRole and index.flags() & qtc.Qt.ItemIsUserCheckable:
            return self.check_state(val, index)

        return None
    return None

def setData(self, index, value, role):
    if role == qtc.Qt.EditRole:
        val = fast_real(value, coerce=False)
        self._data[index.row()][index.column()] = val
        return True

    if role == qtc.Qt.CheckStateRole:
        self._check_state[index] = value
        return True

    return False

def flags(self, index):
    if self._edit is not None and index.column() in self._edit:
        return qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled

    if self._edit is not None and (index.row(), index.column()) in self._edit:
        return qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled

    if self._checks is not None and index.column() in self._checks:
        return qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled | qtc.Qt.ItemIsUserCheckable

    if self._checks is not None and (index.row(), index.column()) in self._checks:
        return qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled | qtc.Qt.ItemIsUserCheckable

    return qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled | qtc.Qt.ItemIsEditable

def rowCount(self, parent=None):
    return len(self._data)

def columnCount(self, parent=None):
    return len(self._data[0])

def headerData(self, section, orientation, role):
    if role == qtc.Qt.DisplayRole:
        if orientation == qtc.Qt.Horizontal and self._headers is not None:
            return str(self._headers[section])

The class takes a list of list containing strings (representing the table). A list of strings representing the headers of the columns. The optional arguments edit and checks define which columns (if given as int) or cells (if given as tuple) are editable and checkable. The underlying data structure data takes values of 0 if the corresponding checkbox is unchecked, or any other value if the corresponding checkbox is checked.

My first question is that the cells that are checkable actually show some extra space, apart from drawing the checkbox. A separating line in the middle of the cell is actually visible when selecting the cell. How can I eliminate this? In the data method I control for cells that are checkable, and skip the display of the underlying data if it is. So I do not know how else to proceed here.

EXTRA: I would like to capture the signal that the model emits when any of the checkboxes are checked/unchecked. Any hint on this would be much appreciated as well.




Blazor SFGrid Checkbox Selection is not working

I am trying to set up a check box in my grid for selection. Here is my sample grid looks like.

<div class="row section-top">
                    <div class="col">
                        <SfGrid @ref="GridInstance" DataSource="@_names" AllowSelection="true" AllowPaging="true">
                            <GridSelectionSettings CheckboxOnly="true" PersistSelection="true"></GridSelectionSettings>
                            <GridColumns>
                                <GridColumn Type="ColumnType.CheckBox" Width="50"></GridColumn>
                                <GridColumn Field="@nameof(Id)" HeaderText="Id" IsPrimaryKey="true"></GridColumn>
                                <GridColumn Field="@nameof(Name)" HeaderText="Name"></GridColumn>
                            </GridColumns>
                        </SfGrid>
                    </div>
                </div>

It does show me checkbox and also select all works. But How Do i bind this to the grid so i can get the selected records/objects?

I tried this on click event but not working.

var selectedItems = this.GridInstance.GetSelectedRecordsAsync();
var selectedItemIds = new List<int>();

selectedItems.GetAwaiter().OnCompleted(() =>
{
    selectedItemIds = selectedItems.Result.Select(s => s.Id).ToList();
});

Can anyone help how i can get selected grid rows from Syncfusion Blazor SFGrid?




How to list checked enum values only?

I’m learning Blazor and was trying to put/save in a list some enum elements, only the ones that are checked. I have read loads of hints on stackoverflow and other web sites but am still unable to achieve that, I know something is missing but I’m blind for now

Let’s say I have an enum in a separate class calle Enums:

    public enum Browsers
    {
        Chrome,
        Edge,
        Firefox,
        Opera,
        Safari,
        Vivaldi
    }

Here is the html part:

@page "/Sub2"
@using TestPatternBuilder.Data

<div class="col">
    <div>Browsers:</div>
        @foreach (var browser in Enum.GetValues<Browsers>())
        {
            <input class="form-check-input mx-0" type="checkbox" id="browsers" value="@browser" />
            <label class="ms-1" for="browsers">@browser</label><br />
        }

    <button class="btn btn-secondary my-3" @onclick="AddBrowsers">Add Browsers</button>

    <ul class="mt-2">
        @foreach (var br in selectedBrowsers)
        {
            <li>@br.BrowserName</li>
        }
    </ul>
</div>

And the code part:

@code{

    List<TestBrowser> selectedBrowsers = new List<TestBrowser>();

    private void AddBrowsers()
    {
        foreach (Browsers item in Enum.GetValues(typeof(Browsers)))
        {
            selectedBrowsers.Add(new TestBrowser { BrowserName = item, isChecked = true });
        }
    }

}

I seem to have it all wrong, tried to bind without success, no idea where the isChecked state is missing...

[enter image description here](https://i.stack.imgur.com/R7y6a.png)




mercredi 15 février 2023

Change Bullet Points to Content Control Check Boxes?

Is it possible to make a document with pre-existing bullet points (or blank boxes made to be bulletpoints) into clickable content control check boxes?

Also I’m having difficulty using a find and replace macro to change blank square boxes to content control check boxes in a document I’m using. I don’t know if it has to do with the fact that maybe some of these boxes are amongst different fonts or if the find and replace tool has difficulty picking up symbols but everything I’ve tried hasn’t worked out.

I tried find and replace macros and it didn't work. I also tried regular find and replace and it didn't work




Android jetpack compose Material 3 Unable to align checkbox text

I am using Android Studio Electric Eel | 2022.1.1.

I am fairly new. I was trying out the checkbox in Compose with Material3 in Android. I am not able to align the text next to check box. Please help. Here is the code and an screenshot image of the emulator screen.

  1. project level build.gradle firl
buildscript {
    ext {
        compose_version = '1.2.0'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.4.0' apply false
    id 'com.android.library' version '7.4.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}
  1. module level build.gradle
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.test'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.test"
        minSdk 27
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.2.0'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.compose.material3:material3:1.0.0-alpha11'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
}
  1. MainActivity.kt


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TestTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Test()
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Test() {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier.padding(0.dp)
    ) {
        Row(
            modifier = Modifier.padding(3.dp)
        )
        {
            Checkbox(
                checked = true,
                onCheckedChange = { },
                modifier = Modifier.absoluteOffset((-12).dp, 0.dp)
            )
            Text(
                text = "Check me",
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp,
                textAlign = TextAlign.Left
            )
        }

        TextButton(
            onClick = { },
            modifier = Modifier.padding(end = 0.dp)
        ) {
            Text(
                text = "Right text",
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp,
                textAlign = TextAlign.Right
            )
        }


    }
}



I have attached a screen shot of the emulator screen to show how the text is aligned.

Question:

  1. How can I align the text "Check me" along with check box.
  2. How can I bring it closer to check box.

Please help.

Here is the screen shot of the emulator screen after I run the app. Notice that the text next to the check box appears displaced upwards.

I tried to place text next to checkbox in my android studio material 3 project. The text is not aligned in line with the checkbox.




mardi 14 février 2023

How to check and uncheck dynamically valued checkbox inside foreach loop in razor

I have a view which shows files from folder and the number of files may vary from user to user

I am dynamically creating checkbox and capturing its values based on filename for each row

the code is as follows

<input type="checkbox" id="@files.Filevalues" name="@files.Filevalues" value="1" checked="checked" />

My controller is as follows this passes value to view

            var getinfo = await _context.EmployeeBasicInformations.FindAsync(id);
            ViewBag.empid = getinfo.EmployeeId;
            var foldername = getinfo.EmployeeEmail;
            string dirPath = Configuration["FolderPath:Document_Path"];
            string path = Path.Combine(dirPath, foldername);
            string[] folderpath = Directory.GetFiles(path);
        List<EmpDoc> files = new List<EmpDoc>();
            foreach (string folderpaths in folderpath)
            {
                files.Add(new EmpDoc
                {
                    Filename = Path.GetFileName(folderpaths),
                    EmployeeId = getinfo.EmployeeId,

                }) ;
            }
            return View(files);

MyModel is as follows

    public int EmployeeId { get; set; }
        public string? Form1{ get; set; }
        public string? Form2 { get; set; }
        public string? EnteredBy { get; set; }
        public DateTime? EnteredDatetime { get; set; }
        public string? UpdatedBy { get; set; }
        public DateTime? UpdatedDatetime { get; set; }
        public string? ValidatedBy { get; set; }
        public string? Form3 { get; set; }
        public string? Form4 { get; set; }
        public string? Form5 { get; set; }

        [NotMapped]
        public IFormFile File { get; set; }

        [NotMapped]
        public string Filename { get; set; }

the files are stored as form1.pdf, form2.pdf

when i check a checkbox for example if i am checking form1 checkbox , in db under form1 column i am saving it as 1 and 0 for non checked .

I am able to save the data, but i am facing issue when i relogin the page , i am unable to retrieve the values and pass it to view

my view is as follows

@foreach (handbook.Data.EmpDoc files in Model)
                            {
                                @if (files.Filevalues == "1")
                                {
                                    <tr style="text-align:center;">
                                        <td>
                                  
                                        <input type="checkbox" id="@files.Filevalues" name="@files.Filevalues" value="1" checked="checked" />

                                        </td>
                                        <td>@files.Filename</td>
                                        <td class="text-nowrap">@Html.ActionLink("Download", "DownloadFile", new { fileName = files.Filename, id = files.EmployeeId })</td>
                                    </tr>
                                }
                                else 
                                {
                                    <tr style="text-align:center;">
                                        <td>

                                           <input type="checkbox" id="@files.Filevalues" name="@files.Filevalues" value="0" />

                                        </td>
                                        <td>@files.Filename</td>
                                        <td class="text-nowrap">@Html.ActionLink("Download", "DownloadFile", new { fileName = files.Filename, id = files.EmployeeId })</td>
                                    </tr>
                                }


                            }



JavaFX TableView with CheckBoxes: retrieve the rows whose checkboxes are checked

I've been searching for a while, but all I found seems very old and can't get it to work and I'm very confused.

I have a tableview with a checkbox in a column header (select all) and another checkbox for each row (select row). What I am trying to achieve is to get all the rows whose checkboxes are checked to perform an action.

Here's what it looks like:

enter image description here

And here's the code in my controller:

package com.comparador.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.comparador.ComparadorPreciosApplication;
import com.comparador.entity.Commerce;
import com.comparador.entity.Items;
import com.comparador.entity.ShoppingListPrices;
import com.comparador.repository.CommerceRepository;
import com.comparador.repository.ProductRepository;
import com.comparador.service.ShoppingService;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;
import javafx.util.converter.IntegerStringConverter;

@Component
public class ShoppingController implements Initializable {
//    @Autowired
//    @Qualifier("lblTitulo")
    private String titulo = "Productos";

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private CommerceRepository commerceRepository;
    @Autowired
    private ShoppingService shoppingService;

    @FXML
    private Label lblTitulo;
    @FXML
    private Button btBack;
    @FXML
    private TableView<Items> tvProducts;
    @FXML
    private TableColumn<Items, CheckBox> colSelected;       //THE CHECKBOX COLUMN
    @FXML
    private TableColumn<Items, String> colName;
    @FXML
    private TableColumn<Items, Integer> colAmount;
    @FXML
    private TableView<ShoppingListPrices> tvTotalPrices;
    @FXML
    private TableColumn<ShoppingListPrices, String> colCommerce;
    @FXML
    private TableColumn<ShoppingListPrices, Double> colTotal;

    private CheckBox selectAll;
    List<ShoppingListPrices> shoppingList = new ArrayList<>();
    
    
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colAmount.setCellValueFactory(new PropertyValueFactory<>("amount"));
        colAmount.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));
//      colSelected.setCellFactory(CheckBoxTableCell.forTableColumn(colSelected));
//      colSelected.setCellValueFactory(cellData -> new ReadOnlyBooleanWrapper(cellData.getValue().getChecked()));
        colSelected.setCellValueFactory(new PropertyValueFactory<>("selected"));
        colCommerce.setCellValueFactory(new PropertyValueFactory<>("commerceName"));
        colTotal.setCellValueFactory(new PropertyValueFactory<>("total"));
        lblTitulo.setText(titulo);
        tvProducts.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        reloadTableViewProducts();
        
        selectAll = new CheckBox();
        selectAll.setOnAction(event -> {
            event.consume();
            tvProducts.getItems().forEach(item -> {
                item.getSelected().setSelected(selectAll.isSelected());
            });
            
        });
        
        setShoppingList();
        
        colSelected.setGraphic(selectAll);
    }
    
    @FXML
    public void editAmount(CellEditEvent<Items, Integer> event) {
        Items item = event.getRowValue();
        if(event.getTableColumn().getText().equals("Cantidad")) {
            item.setAmount(event.getNewValue());
        }
        setShoppingList();
    }
    
    /*
     * CLICKING ON A CHECKBOX SHOULD CALL THIS METHOD AND ADD THE ROW TO "selectedItems"
     */
    @FXML
    public void setShoppingList() {
        
        List<Items> selectedItems = new ArrayList<>();

        //Before trying this I was selecting each row by Ctrl + Clicking on it
//      List<Items> selectedItems = tvProducts.getSelectionModel().getSelectedItems();
        
        //This didn't seem to work
//      List<ShoppingListItems> selectedItems = tvProducts.getItems().filtered(x->x.getSelected() == true);
        
        
        List<Commerce> commerces = commerceRepository.findByNameContaining("");
        
        ShoppingListPrices pricesMixingCommerces = shoppingService.getCheapestShoppingList(commerces, selectedItems);
        List<ShoppingListPrices> pricesByCommerce = shoppingService.getShoppingListsPerCommerce(commerces, selectedItems);
        
        shoppingList = new ArrayList<>();
        shoppingList.add(pricesMixingCommerces); 
        shoppingList.addAll(pricesByCommerce);
        
        ObservableList<ShoppingListPrices> resultOL = FXCollections.observableArrayList();
        resultOL.addAll(shoppingList);
        tvTotalPrices.setItems(resultOL);
    }
    
    
    @FXML
    public void openShoppingList() throws IOException {
        FXMLLoader loader  = new FXMLLoader(getClass().getResource("/shoppingList.fxml"));
        ShoppingListController shoppingListController = new ShoppingListController();
        loader.setControllerFactory(ComparadorPreciosApplication.applicationContext::getBean);
        loader.setController(shoppingListController);
        shoppingListController.setup(tvTotalPrices.getSelectionModel().getSelectedItem());
        try {
            Scene scene = new Scene(loader.load(), 800, 400, true, SceneAntialiasing.BALANCED);
            Stage stage = new Stage();//(Stage) btBack.getScene().getWindow();
            stage.setUserData(tvTotalPrices.getSelectionModel().getSelectedItem());
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    @FXML
    public void goBack() {
        FXMLLoader loader  = new FXMLLoader(ComparadorPreciosApplication.class.getResource("/index.fxml"));
        loader.setControllerFactory(ComparadorPreciosApplication.applicationContext::getBean);
        try {
            Scene scene = new Scene(loader.load(), 800, 800, false, SceneAntialiasing.BALANCED);
            Stage stage = (Stage) btBack.getScene().getWindow();
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    private void reloadTableViewProducts() {
        List<String> productNames = productRepository.findOnProductPerName("");
        List<Items> items = new ArrayList<>();
        for(String name : productNames) {
            //items.add(new Items(new SimpleBooleanProperty(false), name, 1));
            Items item = new Items((CheckBox) new CheckBox(), name, 1);
            item.getSelected().setSelected(false);
            items.add(item);
        }
        ObservableList<Items> itemsOL = FXCollections.observableArrayList();
        itemsOL.addAll(items);
        tvProducts.setItems(itemsOL);
    }
}



Textfield becomes not visible or invisible after checking a specific option in my checkbox in PowerApps. What do I need to correct?

It is not working ;(. Let me write it down like this

The checkbox name is: Categories Checkbox This checkbox has 4 options you can check: "clients", "employees", "consumers", "other"

I have a TextInput1 which I only want it to be visible if the option "Other" from the checkbox "Categories Checkbox" is checked.

This is why I am using this formula but it is not working : If('Categories Checkbox'.Value = "other",true,false)

What do I need to correct? Can somebody please write me down the correct formula?

I tried to change the name of my checkbox, I also tried to make the first letter a capital letter of "Other" instead of "other" I also changed the Value in the formula to text I also changed the textfield,which was text area to Single line of text in the Dataverse Table. But still if I check or uncheck "other" then the textfield does not appear.




lundi 13 février 2023

How can I improve this JS code? It seems clunky to get each checkbox by ID, then toggle 4 different classes

Thanks in advance.

I am toggling classes on a table to hide specific columns, based on checkboxes that are selected by the user above the table. The checkboxes have IDs "product_1", "product_2" etc.

There are 4 colums in the table, so I made 4 functions that do the toggling:

  const toggleFirst = document.getElementById('product_1').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-1');
  });
  const toggleSecond = document.getElementById('product_2').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-2');
  });
  const toggleThird = document.getElementById('product_3').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-3');
  });
  const toggleFourth = document.getElementById('product_4').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-4');
  });

The classes that are toggled then control the showing/hiding.

I have this working, but...

I have 4 CSS classes, and 4 JS functions, that are basically doing the same thing but with a different checkbox relating to a different class.

How can I do this in a more elegant way?




How to select all checkboxes and give that command to button in another class in Tkinter?

from tkinter import *
import tkinter as tk
class Win1(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        Label(self, text= "ISMC", font= ('Helvetica 20 bold')).pack(padx=5, pady=5)
        b1=Button(self, text="AUTO", command=lambda:controller.show_frame(Win2)).pack(padx=5, pady=5)
class Win2(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        b1=Button(self, text= "button 1", command=lambda:controller.show_frame(Win3)).pack(padx=5,      pady=5)
        b2=Button(self, text= "button 1").pack(padx=5, pady=5)
        b3=Button(self, text= "button 3").pack(padx=5, pady=5)
        b4=Button(self, text= "PROCEED").pack(padx=5, pady=5)
        b5=Button(self, text= "BACK", command=lambda:controller.show_frame(Win1)).pack(padx=5,  pady=5)
class Win3(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        val_x=0
        val_y=10
        self.vars = []
        self.array = []
        for i in range(3):
             self.array.append("RELAY " + str(i+1))
             self.vars.append(StringVar())
             self.vars[-1].set(0)
             c1=Checkbutton(self, text=self.array[i], variable=self.vars[-1], onvalue=1, offvalue=0).place(x=val_x, y=val_y)
             
             if i<=3:
                val_x=val_x+0
                val_y=val_y+50
                
        b1=Button(self, text="back", bg="red", fg="white", command=lambda:controller.show_frame(Win2)).place(x=30,y=140)
        b2=Button(self, text="proceed", bg="green", fg="white").place(x=30,y=160)
        b3=Button(self, text= "Select All").place()
class Application(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        window = tk.Frame(self)
        window.pack(side = "top", fill = "both", expand = True)
        self.frames = {}
        for F in (Win1, Win2, Win3):
            frame = F(window, self)
            self.frames[F] = frame
            frame.grid(row = 0, column=0, sticky="nsew")
        self.show_frame(Win1)
        
    def show_frame(self, window):
        frame = self.frames[window]
        frame.tkraise()
        self.title("Test") 
        self.geometry('1500x1500')
        
app = Application()
app.mainloop()       

I need to select all checkboxes in my window 3 and give that command to a button "AUTO" which is present in window 1. I tried many times but i don't know how to do that?

Can anyone please help. I am beginner of programming.




dimanche 12 février 2023

How to change checkbox to required html format in pdfmake?

I want to change the below html to required format as in below image,

<div id="pdfTable" #pdfTable style="display: none;">
 <table class="table table-borderless mb-0" style="font-size:14px;">
    <thead>
        <label for="" style="text-align: center;">Recommendation: </label>
        <tr style="">
            <td *ngFor="let recommendation of recommendations" style="border:0;width:25%">
                <span *ngIf="recoName == recommendation.listTypeValueName">
                    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYA alt="">
                    
                </span>
                <p *ngIf="recoName != recommendation.listTypeValueName"><img
                        src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAA alt=""> 
                         </p>
            </td>
        </tr>

    </thead>
 </table>
</div>

Required Format

Required Format

What I am getting from above html

What I am getting




Selecting non-input type checkboxes using javascript on console

I want to clear my google history, but I don't want everything to be cleared, so I make a search like "youtube" in the search bar, on chrome://history, page and the result url will be chrome://history/?q=youtube. There will be many results appearing like this: enter image description here As you can see there are 149 results, but in many cases there might be much more. So i want to check all the checkboxes using console using javascript.

I tried changing the tags and ids of functions like function toggle(source) { checkboxes = document.getElementsByName('foo'); for(var checkbox in checkboxes) checkbox.checked = source.checked; } but those checkboxes are written in div having id and role of checkbox enter image description here




samedi 11 février 2023

HTML change the line of the checkbox automatically

This is how the website look.enter image description here

In the first line of the checkbox, the last checkbox and its label isn't connected together, how am I going to put the checkbox and its label in the same line.

This is the css of the checkbox

.checkboxContainer {
    display: inline-block;
    padding-top: 80px;
    padding-left: 40px;
    padding-right: 30px;
    padding-inline: 50px;
}

.checkboxContainer label {
    font-size: 25px;
    padding-right: 10px;
}

The way I created the checkbox (I have shortened the data)

const checkboxContainer=document.querySelector(".checkboxContainer");

let nutritions=[{"id":1,"label":"食品分類"},...];
for (let tmp of nutritions) {
    const checkboxId="checkbox"+tmp.id;
    const checkbox='<input type="checkbox" id="'+checkboxId+'" class="checkbox-input">';
    const label='<label for"'+checkboxId+'">'+tmp.label+'</label>';
    checkboxContainer.innerHTML+=checkbox+label;
}



jeudi 9 février 2023

How to handle the check/uncheck of two checkboxes used in the filter panel for a table?

I want to show the filtered data in a table based on the checked or unchecked checkbox present in the filter panel. The two checkbox are having two value such as 'Male' and 'Female'. I need to show the row data of 'Male' when 'Male' checkbox is checked and similar for 'Female'. When both unchecked it should show all the data.

I tried 'checked' prop of checkbox input field and I am toggling it based on the 'onChange' but when I am unchecking both checkboxes it is not behaving as expected and showing the data filtered insted it should show all the data when both checkboxes are unchecked.




How do I make this checkbox be before my h3 element?

I have this HTML and CSS markup:

body {
  background-color: #f5f5f5;
}

._contain_items {
  display: block;
  width: 1000px;
  height: fit-content;
  border: 1px solid rgba(0, 0, 0, .12);
  background-color: #ffffff;
}

._inline_task {
  display: flex;
  flex-direction: row;
}

._when {
  margin-top: 0% !important;
  margin-left: auto;
  margin-bottom: 0% !important;
  align-self: flex-end;
}

._lightweighted {
  margin-top: 0% !important;
  font-size: 16px;
  font-weight: 500;
  color: #7f8ca1;
}

._title_task {
  margin-top: 0% !important;
  margin-bottom: 0% !important;
}

.checkbox-container {
  width: 50px;
  height: 28px;
  display: flex;
  align-items: center;
  margin-right: 10px;
  position: relative;
}

.checkbox-container label {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 50%;
  cursor: pointer;
  height: 28px;
  left: 0;
  position: relative;
  top: 0;
  width: 28px;
}

.checkbox-container label:after {
  border: 2px solid #fff;
  border-top: none;
  border-right: none;
  content: "";
  height: 6px;
  left: 7px;
  opacity: 0;
  position: relative;
  top: 8px;
  transform: rotate(-45deg);
  width: 12px;
}

.checkbox-container input[type="checkbox"] {
  visibility: hidden;
}

.checkbox-container input[type="checkbox"]:checked+label {
  background-color: #66bb6a;
  border-color: #66bb6a;
}

.checkbox-container input[type="checkbox"]:checked+label:after {
  opacity: 1;
}
<div class="_contain_items">
  <h3> Employee Tasks </h3>
  <hr style="border: none;height: 1px;background-color: #333;">

  <div class="_inline_task">

    <div class="checkbox-container">
      <input type="checkbox" id="checkbox" />
      <label for="checkbox"></label>
    </div>

    <h3 class="_title_task"> Title of the task </h3>
    <h3 class="_when"> Tomorrow </h3>

  </div>

  <p class="_lightweighted"> Housekeeping </p>

</div>

</body>

The problem that I'm facing is at the checkbox. I want to make a circle checkbox with this ✔️ sign. When position is absolute it works as intended but it is not before h3(Title of the task). When I change position at relative the circle appears at the right place but the sign its not there. How do I make it appear before the h3?




Matlab GUI checkbox enable or disable

I am trying to work with a GUI in MATLAB which once run, would first read through a MATLAB struct, for example, abc.checkboxStatus, having values of 1 or 0 based on earlier user input, and will load the GUI with the checkbox enabled or disabled, based on the previously saved information, i.e., whether earlier, the checkbox was enabled or disabled. Now I would also like it to be flexible for future alterations, meaning that I should be able to enable or disable the checkbox later as well and based on its latest input, the information will be saved in the abc.checkboxStatus struct.

In easier language, if today, I enabled the checkbox, the abc.checkboxStatus should store the value 1, and when I run the GUI tomorrow, it should open with the checkbox ticked. If tomorrow, I want to disable the checkbox, this info should be stored in the abc.checkboxStatus, that is abc.checkboxStatus would be equal to 0, and when I load the GUI the day after tomorrow, it should open with the checkbox unticked.

Any input is greatly appreciated. Thanks!

**I am currently unable to read through the abc.checkboxStatus and set the checkbox in the GUI accordingly. I am using the code

set(hObject,'Value',abc.checkboxStatus)

but this does not allow to alter the checkbox status later, it gets fixed to either 0 or 1, so I need help with this.**




why Check box fires 2 events c#

i have 2 checkboxes with 1 handler onLostFocus. the problem is that if i move focus from 1 check box to another it fires 2 events from checkbox1 and checkbox2

if focus moved somewhere else it fires 1 event

PS it was bubbling




How to use checkbox for 2 queries for population from DataGridView in vb.net

How to use checkbox for 2 queries for population from DataGridView in vb.net?.

I tried with the code below the population in the datagridview became empty please recommend because maybe my code implementation has something wrong.

tHANKS

 Private Sub PopulateDataGridView()
        Try
            dt = New DataTable
            If CheckBox1.Checked = False Then
Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH > 0 AND GDN = 'A.04.01.002.001'"
 Else
                If CheckBox1.Checked = True Then
                    Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH < 0 AND GDN = 'A.04.01.002.001'"
 Using adapter As New OleDbDataAdapter(query, cn.ToString)
adapter.Fill(dt)
 End Using
                    Me.GridControl1.DataSource = dt
                    Me.GridControl1.Refresh()
GridView1.Columns("SUBFOLDERP").Visible = False
                    GridView1.Columns("FILENAME1").Visible = False
                    GridView1.Columns("FILENAME2").Visible = False
                    GridView1.Columns("FILENAME3").Visible = False
                    GridView1.Columns("FILENAME4").Visible = False
                    GridView1.Columns("FILENAME5").Visible = False
                    GridView1.Columns("FILENAME6").Visible = False
 End If
            End If
        Catch myerror As OleDbException
            MessageBox.Show("Error: " & myerror.Message)
        Finally
        End Try
    End Sub



mercredi 8 février 2023

Can't store data using checkbox to database using codeigniter

I try to store some data using checkbox into my database, but it can't stored. Here is my code:

I try to store some data using checkbox into my database, but it can't stored. Here is my code:

I try to store some data using checkbox into my database, but it can't stored. Here is my code:

View:

<form method="post" action="<?php echo base_url().'igd/igd/input_airborne'?>">
                                <?php echo $this->session->flashdata('message_airborne');?>
                                <input type="text" class="form-control" name="KUNJUNGAN" value="<?php echo $igd->NOMOR ?>" readonly>
                                <input type="datetime-local" class="form-control" name="TANGGAL" value="<?php echo date("Y-m-d H:i:s") ?>">
                                <input type="text" class="form-control" name="OLEH" value="<?php echo $session_user->nip?>" readonly>
                                <input type="text" class="form-control" name="STATUS" value="1" readonly>

<div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="" name="DESKRIPSI" id="defaultCheck1">
                                    <label class="form-check-label" for="defaultCheck1">
                                        TBC AKtif
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="" name="DESKRIPSI" id="defaultCheck2">
                                    <label class="form-check-label" for="defaultCheck2">
                                        Campak
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="" name="DESKRIPSI" id="defaultCheck1">
                                    <label class="form-check-label" for="defaultCheck1">
                                        MDR TB
                                    </label>
                                </div> 
<button class="btn btn-sm btn-success mt-1 mb-1"> Masukkan</button>
                                </form>

Controller:

 public function input_airborne(){
        $DESKRIPSI = $this->input->post('DESKRIPSI');
        $TANGGAL = $this->input->post('TANGGAL');
        $OLEH = $this->input->post('OLEH');
        $STATUS = $this->input->post('STATUS');
        $KUNJUNGAN = $this->input->post('KUNJUNGAN');

        $data = array(
            'DESKRIPSI' => $DESKRIPSI,
            'TANGGAL' => $TANGGAL,
            'OLEH' => $OLEH,
            'STATUS' => $STATUS,
            'KUNJUNGAN' => $KUNJUNGAN
        );
        $this->M_Igd->input_airborne($data, 'igd_inim_airborne');
        $this->session->set_flashdata('message_airborne','<div class="alert alert-success alert-dismissible mt-1 fade show" role="alert">
                                                Airborne berhasil dimasukkan
                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                                </button>
                                                </div>');
        redirect($_SERVER['HTTP_REFERER']);

    }

the DESKRIPSI is field to storing my checkbox entry




How to Set WPF Checkbox Text Colo to Gray if Disabled?

In WPF, when a checkbox is disabled, only the box is grayed out. The text of the checkbox remains black (the default color). How do I make the text also grayed out when checkbox is disabled? The following is the style xaml I've used. The last trigger only changes the box border color, not the text. Target or property does not recognize "Textblock" or "Content". Please help!

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/LightZ;component/Palettes/Brushes.xaml" />
    <ResourceDictionary Source="/LightZ;component/Styles/FillBrush.xaml" />
</ResourceDictionary.MergedDictionaries>

<Style x:Key="CheckBoxFocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Border>
                    <Rectangle 
        Margin="15,0,0,0"
        StrokeThickness="1"
        Stroke="#60000000"
        StrokeDashArray="1 2"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="{x:Type CheckBox}" TargetType="CheckBox">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="FocusVisualStyle"    Value="{StaticResource CheckBoxFocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CheckBox">
                <BulletDecorator Background="Transparent">
                    <BulletDecorator.Bullet>
                        <Border x:Name="Border"  
          Width="15" 
          Height="15" 
          CornerRadius="0" 
          Background="Transparent"
          BorderThickness="1"
          BorderBrush="{StaticResource text}">
                            <Path 
            Width="12" Height="12" 
            x:Name="CheckMark"
            SnapsToDevicePixels="False" 
            Stroke="{StaticResource text}"
            StrokeThickness="2"
            Data="M 0 5 L 3 10 10 0" />
                        </Border>
                    </BulletDecorator.Bullet>
                    <ContentPresenter Margin="4,0,0,0"
        VerticalAlignment="Center"
        HorizontalAlignment="Left"
        RecognizesAccessKey="True"/>
                </BulletDecorator>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="false">
                        <Setter TargetName="CheckMark" Property="Visibility" Value="Collapsed"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="{x:Null}">
                        <Setter TargetName="CheckMark" Property="Data" Value="M 0 7 L 7 0" />
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="{StaticResource highlight}" />
                        <Setter TargetName="CheckMark" Property="Stroke" Value="{StaticResource highlighttext}" />
                    </Trigger>
                    <Trigger Property="IsPressed" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="{StaticResource PressedBrush}" />
                        <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource PressedBorderBrush}" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" />
                        <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" />
                        <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>



Print different results for different "checkbox" in PHP

Im doing an assignment and I got stuck.

I am preparing a project divided in 5 different .php files. The first page is an introduction page, where the user can type name and get started. 3 middle pages are for tests and quiz. The 5th and last page is a summary of the results of the previous tests. The second test is an <input type="checkbox" ...> and, according to the answer given, I want to print different results.

  • If the 2 answers are correct echo= "Correct"
  • If only 1 of the answers is correct echo= ""One of the two answers is wrong"
  • If only 1 box was checked echo= "Answer is incomplete"
  • No box was checked echo= "You did not select any option" This is the HTML
<p>Through mixing which of the following primary colors can the secondary color in the figure be obtained?</p>
<form action="quiz_3.php" method="POST">
<label><input type="checkbox" name="result_quiz_2[]" value="yellow">Yellow</label>
<label><input type="checkbox" name="result_quiz_2[]" value="red">Red</label>
<label><input type="checkbox" name="result_quiz_2[]" value="blue">Blue</label>
  
<input type="submit" value="Confirm & Go to Quiz 3"><br>

With this code in the next page I store the answers in $_SESSION

<?php
session_start();
$q_2 = $_POST;
if (array_key_exists('result_quiz_2',$q_2))
{
$_SESSION['result_quiz_2'] = $_POST['result_quiz_2'];
}
else $_SESSION['result_quiz_2'] = 0;
?>

What should i write on the final file to print out the different results?

foreach () 

doesnt work if no boxes are checked and

isset() 

will print "Correct" if just one answer of the two is correct.

really appreciate for whoever can help.




mardi 7 février 2023

c# how to show checkbox on picture and save to bitmap

How it should be

'how to show checkbox on saved bitmap?'

reality

     private void picWyslij_Click(object sender, EventArgs e) 
{int width = panel12.Size.Width; int height = panel12.Size.Height;
   Bitmap bm = new Bitmap(width, height);
        panel12.DrawToBitmap(bm, new Rectangle(0, 0, width, height));

        bm.Save(@"C:\Users\zooma\Desktop\IMAGE\TestDrawToBitmap.bmp", ImageFormat.Bmp);
  }



Checkbox Default Checked in React table is not working

I want to mark the checkbox checked inside a subComponent with the help of forwardref but i am not getting the result. I have tried defaultChecked = {true} defaultValue = {true} inside input field but didn't succeed.

Here is the checkbox component

import { forwardRef, useEffect, useRef } from "react";

export const SubRowsCheckBox = forwardRef(({ indeterminate, ...rest }, ref) => {
  const defaultRef = useRef();
  const resolvedRef = ref || defaultRef;

  useEffect(() => {
    resolvedRef.current.defaultChecked = true
    resolvedRef.current.indeterminate = indeterminate;
  }, [resolvedRef, indeterminate]);

  return (
    <>
      <div class="flex items-center">
        <input
          type="checkbox"
          ref={resolvedRef}
          {...rest}
          id="A3-yes"
          name="A3-confirmation"
          class="opacity-0 absolute h-8 w-8"
        />
      </div>
    </>
  );
});

This is how I called the checkbox Component.

= useTable(
    {
      columns,
      data,
      state : {expanded},
    },
    useExpanded,
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => {
        return [
          ...columns,
          {
            Header: "Choose Items",
            id: "selection",
            Cell: ({ row }) => (
              (details.isSelected) ? ( 
              <div>
                <SubRowsCheckBox  {...row.getToggleRowSelectedProps() }  />
              </div>
            ) : ( null 
            )
            ),
          },
        ];
      });
    }
    
 
  )

The component is rendered only if row has got some subRows. I have also tried resolvedRef.current.checked = true. It marks the checkbox checked but it doesn't works for the all rows. Here are the results First Image with subRow

These are the results of resolvedRef.current.checked = true. The defaultChecked prop isn't changing anything. Second Image

Any kind of help will be highly appreciated.

I want to mark all the subrows checkbox checked for the first render and rest of it works fine.




lundi 6 février 2023

Why panel control appear behind of the another control?

I wrote a functionality to open the panel when we click on the textbox. But the panel appears behind the other controls. The entire code should be written in C#, ASP.NET. Can anyone help me out with this?

Click here to see the reference image

When I click on the "Dev Root Cause" text box, the panel should appear before the dropdown control. But it appears on the back side of the control.

When we click on the TextBox, one panel appears with the multi-checkbox list. But this should be appear before other controls.




select user with checkbox

I want to create a checkbox for every user in the table, this my tableBody :

              <TableBody>
                {users.map((user) => {                
                  return (
                    <TableRow
                      key={user.id}
                    >
                      <TableCell padding="checkbox">
                        <Checkbox
                          checked={selectedUserIds.indexOf(user.id) !== -1} // check if the user.id is in selectedUserIds 
                          onChange={() => handleSelectUser(user.id)} // evry time I try to find the logic for this function I fail
                          value="true"
                        />
                      </TableCell>
                      <TableCell>{user.email}</TableCell>
                      <TableCell>{user.roles}</TableCell>
                      <TableCell>{user.status}</TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>

I created this variable for storing the selectedUserIds as shown in the example above

const [selectedUserIds, setSelectedUserIds] = useState([]);

the problem is that I can't create the function handleSelectUser that add/remove the user checked/unchecked in/from selectedUserIds I tried so many times and I failed. if someone can help me I will be very thankfull




Google Workspace add-on - Calendar - custom

I'm starting a new module project for Google Workspace add-ons Calendar.

So I go through App-scripts to develop my module.

I have a few questions first:

  • Is it possible to create a calendar when installing the module or do you have to go through existing calendars?
  • The module aims to generate a custom checkbox in the event creation form on the Google Calendar web application. If the checbbox is checked during the validation of the event, we retrieve some information from the event to send it to a third party service.

Do you think this is possible?

Thanks.

  • Few tests via App scripts. I can create events via App scripts in a calendar already created beforehand.



Button on click to check a particular checkbox ID with a Tampermonkey script

I would like some help with a Tampermonkey script.

I have a script that will add a button to the page and on click, it will add some text to a text area. That part is working fine. See below.

Now, I need that on click of this button, before it adds the text, I need it to check a checkbox ID="1234"

Please assist.


(function() {
 window.addEventListener("load", () => {
 addButton("Add Markdown");
 });

function addButton(text, onclick, cssObj) {
cssObj = cssObj || {
  position: "fixed",
  top: "15%",
  right: "4%",
  "z-index": 3,
  fontWeight: "600",
  fontSize: "14px",
  backgroundColor: "#00cccc",
  color: "white",
  border: "none",
  padding: "10px 20px"
};

let button = document.createElement("button"),
  btnStyle = button.style;
document.body.appendChild(button);
button.innerHTML = text;
// Setting function for button when it is clicked.
button.onclick = selectReadFn;
Object.keys(cssObj).forEach(key => (btnStyle[key] = cssObj[key]));
return button;
}

function selectReadFn() {
var txt = document.getElementById("markdown-editor").value += '\n---\n```markdown text here.\n```\n\n'

}
})();

I couldn't find a script that will check a checkbox with the click of another button




dimanche 5 février 2023

Jquery Checkbox Checked Show / Hide Div if two checkboxes is check or unchecked

I have this simple jquery code for checkbox that checks via attributes. I know that there are many similarities for this answered already but the idea here is different.

I want to show the A_B div element for the following condition:

#1: User checked checkbox A or B then shows the A_B div element

#2: If user unchecked A checkbox but checkbox B is still checked. Then A_B div element is still showing.

*Note: This can be reversal for the situation*

#3 If user uncheckeds both A or B checkbox. Then only A_B div element will hide.

Right now. When I uncheck A or B checkbox. The div element will hide, should not suppose to toggle. Is there anything here to improve. To achieve the following 3 conditions?

Any ideas / solutions would be a great help. Might be useful also to some users that encounters the same problem as mine. Thanks.

$('input[chck-type="a_b"]').click(function(){
    if (
    $(this).prop("checked") == true
  ) {
      $('.A_B').removeClass('hide');
  } else {
    $('.A_B').addClass('hide');
  }
});

$('input[chck-type="c"]').click(function(){
    if (
    $(this).prop("checked") == true
  ) {
      $('.C_Box').removeClass('hide');
  } else {
    $('.C_Box').addClass('hide');
  }
});
.hide {display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="checkbox" chck-type="a_b">A</p>
<p><input type="checkbox" chck-type="a_b">B</p>
<p><input type="checkbox" chck-type="c">C</p>


<div class='A_B hide'>
This box is for A or B.
</div>

<div class='C_Box hide'>
This box is for C.
</div>



Access VBA for checkboxes

I'm currently working on a project that gave me a lot of raw data I am trying to filter in a continuous form. I have one field that has a possibility of five letters (GRUBW) with each multiple letters per entry. The goal is to filter the form with a checkbox for each letter. Am I missing something or going about this the wrong way?

Below is the coding I'm attempting to use and when trying to debug I keep getting an error of an undefined variable. As you can see in the coding, I have a lot of ways I want to filter. I have a feeling that I'm missing some double quotes somewhere or my understanding of the way checkboxes are to be coded is totaling wrong. I've only been working with VBA for a few months, so I may be out of my depth here. Thanks

Option Compare Database
Option Explicit
    Private Sub CBTN_CLICK()
Dim ctl As Control
For Each ctl In Me.Section(acHeader).Controls
Select Case ctl.ControlType
Case acTextBox, acCheckBox
ctl.Value = Null
End Select
Next
Me.FilterOn = False
    End Sub
    Private Sub requeryform()
Dim strwhere As String
Dim lnglen As Long

If Not IsNull([Forms]![sbx]!CTB) Then
    strwhere = strwhere & "([CARD] LIKE ""*" & [Forms]![sbx]!CTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!OTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!ARTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!TTB) Then
    strwhere = strwhere & "([ctype] LIKE ""*" & [Forms]![sbx]!TTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!CTTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Me.RC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & R & "*"") AND "
End If
If Me.UC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & u & "*"") AND "
End If
If Me.BC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & b & "*"") AND "
End If
If Me.GC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & g & "*"") AND "
End If
If Me.WC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & w & "*"") AND "
End If
lng = Len(strwhere) - 5

If lnglen <= 0 Then
Else
strwhere = Left$(strwhere, lnglen)
Debug.Print strwhere
Me.Filter = strwhere
Me.FilterOn = True
End If
End Sub
Private Sub STBN_CLICK()
requeryform
End Sub



samedi 4 février 2023

How to click on checkbox filter with selenium Python?

I'm trying to click on a checkbox filter on a website with selenium python. This is a part of its HTML code linked to one of the checkbox options.

<div class="shopee-checkbox" bis_skin_checked="1">
    <label class="shopee-checkbox__control">
        <input type="checkbox" name="" value="Jabodetabek">
        <div class="shopee-checkbox__box" bis_skin_checked="1">
            <i> </i>
        </div>
        <span class="shopee-checkbox__label">Jabodetabek</span>
    </label>
</div>

I tried following, but it didn't work.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://shopee.co.id/search?keyword=baju%20laki-laki')

time.sleep(5)
driver.find_element(By.XPATH, "//input[@value='JABODETABEK']").click()

I read the answers to similar questions, mostly they suggest using 'id' and 'name' to find the element. However, in this input tag, there are only 'type' and 'value'.




Save MutableListOf

I have a problem and I don't know how I could create a function to save the state of a MutableListOf when the application is closed and another one to restore it when it is opened again. Could someone help me?

Code: class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val button = findViewById<Button>(R.id.button)
    val text = findViewById<TextView>(R.id.editTextTextPersonName)
    val layout = findViewById<ConstraintLayout>(R.id.layout)
    var numbers = 0
    var checkboxes = mutableListOf<CheckBox>()
    
    button.setOnClickListener {
        val checkbox = CheckBox(this)
        checkbox.text = text.text
        text.text = ""
        checkbox.textSize = 13f
        val font = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
        checkbox.typeface = font
        layout.addView(checkbox)
        val params = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT
        )
        params.setMargins(100, numbers * 75, 100, 100)
        params.width = 1020
        params.height = 120
        checkbox.layoutParams = params
        checkbox.id = View.generateViewId()
        val constraintSet = ConstraintSet()
        constraintSet.clone(layout)
        constraintSet.connect(
            checkbox.id,
            ConstraintSet.TOP,
            layout.id,
            ConstraintSet.TOP,
            numbers * 75
        )
        constraintSet.connect(
            checkbox.id,
            ConstraintSet.START,
            layout.id,
            ConstraintSet.START,
            0
        )
        constraintSet.applyTo(layout)
        numbers += 1
        checkboxes.add(checkbox)
        checkbox.setOnClickListener {
            checkbox.animate().alpha(1f).withEndAction {
                checkbox.isChecked = false
                layout.removeView(checkbox)
                numbers -= 1
                checkboxes.remove(checkbox)
                checkboxes.forEachIndexed { index, cb ->
                    val params = cb.layoutParams as ConstraintLayout.LayoutParams
                    params.setMargins(0, index * 75, 0, 0)
                    cb.layoutParams = params
                    val constraintSet = ConstraintSet()
                    constraintSet.clone(layout)
                    constraintSet.connect(
                        cb.id,
                        ConstraintSet.TOP,
                        layout.id,
                        ConstraintSet.TOP,
                        index * 75
                    )
                    constraintSet.applyTo(layout)
                }
            }.start()
        }
    }
}

}

I have tried many things but none of them have worked




jeudi 2 février 2023

how to update checkbox or checkbox.setSelected(true)

I dont get an error while coding but I do get an error while running in eclipse java.

I select the data from the table and then update checkbox using checkbox.setSelected(true) and it errors out.

is there any better way in Java to resolve this issue please.

Thanks

I tried saving the selected data into a variable and printed the variable and it shows the right data but while I try to change the status of the checkbox, I get an error.




mercredi 1 février 2023

Checkbox doesn't work on first click when checked by default

I have some checkboxes that doesn't work in first click when they are already checked by default.

What's happen is: When I click in te checked checkbox he fire Page_Load but doesn't fire OnCheckedChanged event and keep checked until I click again(after this all checkboxes start to work normally).

In the tests I made, I notice that if I keep the Panel witch include the checkboxes always visible this problem does not occur and if I remove the OnCheckedChanged event too

 <asp:UpdatePanel runat="server" ID="updApply">
    <ContentTemplate>
        <div class="row">
            <div class="col-md-12">
                <asp:Panel runat="server" ID="pnlApply">
                    <div class="row">
                        <div class="col-md-12">
                            <asp:Panel runat="server" ID="pnlAplicaDescontoEstabelecimento">
                                <div class="form-group">
                                    <div class="input-group">
                                        <div class="input-group-addon">
                                            <asp:CheckBox ID="cbxApply" runat="server" 
                                                onchange="loadUI();" 
                                                OnCheckedChanged="apply_CheckedChanged" 
                                                AutoPostBack="True" />
                                        </div>
                                    </div>
                                </div>                                                    
                            </asp:Panel>
                        </div>
                    </div>
                </asp:Panel>
            </div>
        </div>
    </ContentTemplate>
</asp:UpdatePanel>

I think it's important to say that in the code behind there are some functions that control whether the Panel is visible

Thanks!