mercredi 31 janvier 2024

Tkinter issue regarding dynamically uncheck CheckBoxes

In Tkinter (Python) I try to dynamically uncheck a CheckBox when an another CheckBox is checked but the behavior is rather erratic.

  1. If the first box is checked and i check the second one: the second box checks for few seconds then it unchecks. The event related to the second CheckBox doesn't trigger.
  2. If the second box is checked and i check the first one: the behavior is correct as it uncheck the second one and check the first one. The event related to the first CheckBox does trigger.
  3. If there's no single box checked and I check one box at the time the events do trigger normally.

My code :

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.frame = tk.Frame(self)
        self.frame.pack(fill=tk.BOTH, expand=True)

        self.entry1 = tk.Canvas(self.frame, width=100, height=100, highlightthickness=0, bd=0, bg="green", relief='solid')
        self.entry1.grid(row=0, column=0)

        self.entry2 = tk.Canvas(self.frame, width=100, height=100, highlightthickness=0, bd=0, bg="red", relief='solid')

        self.check_var1 = tk.BooleanVar()
        self.check_var1.set(True)
        self.check_box1 = tk.Checkbutton(self, text="Show Green", variable=self.check_var1, command=lambda: self.toggle_entries(self.check_var1))
        self.check_box1.pack()

        self.check_var2 = tk.BooleanVar()
        self.check_box2 = tk.Checkbutton(self, text="Show Red", variable=self.check_var2, command=lambda: self.toggle_entries(self.check_var2))
        self.check_box2.pack()

        self.check_var1.trace_add('write', self.check_var_changed)
        self.check_var2.trace_add('write', self.check_var_changed)

        self.toggle_entries(self.check_var1)

    def toggle_entries(self, var):
        if var is self.check_var1:
            if var.get():
                self.entry1.grid()
                self.entry2.grid_remove()
                self.check_var2.set(False) 
        elif var is self.check_var2:
            if var.get():
                self.entry2.grid()
                self.entry1.grid_remove()
                self.check_var1.set(False) 

    def check_var_changed(self, *args):
        if self.check_var1.get():
            self.check_var2.set(False)
        elif self.check_var2.get():
            self.check_var1.set(False)

if __name__ == "__main__":
    app = App()
    app.mainloop()

Any ideas of why this functiontoggle_entries doesn't work properly?




samedi 27 janvier 2024

TreeView Select parent checkbox based on children - WPF MVVM

I am new to WPF. I found a few examples and put together a tree-view example in C# WPF Mvvm. I got the children's checkboxes checked or unchecked based on parent selection. I am not sure how to access the parent binding or property to check or uncheck it based on children. If all children are selected, I expect parents to be checked, and if even one child is unchecked, I want parents to be unchecked. How do I achieve this using the MVVM viewmodel? Any suggestions would be greatly appreciated.

Xaml View

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
    <local:MainViewModel></local:MainViewModel>
</Window.DataContext>
<Window.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:CheckableItem}" ItemsSource="{Binding 
        Children, Mode=TwoWay}">
        <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, 
                                                Path=DataContext.CheckBoxCommand}" CommandParameter="{Binding}"/>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </HierarchicalDataTemplate>
</Window.Resources>

<StackPanel>
    <Label Content="Miscellaneous Imports" HorizontalAlignment="Center" />
    <ScrollViewer>
        <TreeView ItemsSource="{Binding MiscellaneousImports, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="10" Height="450"/>
    </ScrollViewer>
</StackPanel>

ViewModel

public class MainViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler? PropertyChanged;

    public ICommand CheckBoxCommand { get; set; }
    public MainViewModel()
    {
        LoadCheckableItems();
        CheckBoxCommand = new DelegateCommand<CheckableItem>(OnCheckBoxChecked);
    }

    private void OnCheckBoxChecked(CheckableItem item)
    {
        throw new NotImplementedException();
    }

    private ObservableCollection<CheckableItem> miscellaneousImports;
    public ObservableCollection<CheckableItem> MiscellaneousImports
    {
        
        get { return miscellaneousImports; }
        set
        {
            miscellaneousImports = value;
            OnPropertyChanged("MiscellaneousImports");
        }
    }
    private void LoadCheckableItems()
    {
        List<CheckableItem> lstItems = new List<CheckableItem>();

        CheckableItem item = new CheckableItem
        { Name = "Coffee", Children = new ObservableCollection<CheckableItem>() { new CheckableItem { Name="Medium" }, new CheckableItem {Name="Dark" } } };
        lstItems.Add(item);

        MiscellaneousImports = new ObservableCollection<CheckableItem> ( lstItems );
    }
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Checkbox collection class

public class CheckableItem:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
        public ObservableCollection<CheckableItem> Children { get; set; }
        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set
            {
                _isChecked = value;
                OnPropertyChanged("IsChecked");
                if (Children != null)
                {
                    foreach (CheckableItem child in Children)
                    {
                        child.IsChecked = IsChecked;
                    }
                    OnPropertyChanged(nameof(Children));
                }
            }
        }
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
     
    }



mardi 16 janvier 2024

How to have checkboxes checked by default using useFormik?

I have these components and I have 12 checkboxes in child component. I want to have them checked by default when the component loads. I can't do that. I can't use checked='true' as an attribute for my input because formik is controlling my input and it doesn't work well. Or I set checked attribute with some pre-defined values in checked array, but again it worked badly. I thought I probably can use useRef here to trigger onChange event of input to simulate changing checkboxes by checking them. something like this:

const ref = useRef();

useEffect(() => {
ref.current.change();
}, [])

and setting ref to the input. But this didn't work. How can I fix this problem with ref or something else?

    import {useFormik} from "formik";
    import CheckboxesComponent from "./CheckboxesComponent";
    
    const AddUserForm = ({handleShowForm, showForm, formTitle}) => {
        const cities = options.slice(1)
        const [textAreaString, setTextArea] = useState('')
    
        const formik = useFormik({
            initialValues: {
                tel: '', name: '', password: '', username: '', province: '', level: '', availableCities: '', city: '',
                checked: []
            },
            onSubmit: values => {
                console.log(formik.values)
            }
        })
    
        return(
            <form className='add-user-form' onSubmit={formik.handleSubmit}>
                <div className='form-flex'>
                   {/*other parts of form*/}
                </div>
                <CheckboxesComponent handleChange={formik.handleChange} />
            </form>
        )
    }
    export default AddUserForm

CheckBoxesComponent:

const fields = [
    {name: 'delNomad', label: 'حذف عشایر'},
    {name: 'editNomad', label: 'ویرایش عشایر'},
    {name: 'addNomad', label: 'افزودن عشایر'},
    {name: 'delDriver', label: 'حذف راننده'},
    {name: 'editDriver', label: 'ویرایش راننده'},
    {name: 'addDriver', label: 'افزودن راننده'},
    {name: 'rejectReq', label: 'رد درخواست ها'},
    {name: 'manualDeliver', label: 'تایید تحویل دستی'},
    {name: 'addWaterReq', label: 'افزودن درخواست آب'},
    {name: 'getExcel', label: 'دریافت فایل اکسل'},
    {name: 'seeingReport', label: 'مشاهده گزارش گیری'},
    {name: 'delReq', label: 'حذف درخواست ها'},
];

const CheckboxesComponent = ({handleChange}) => {

    return(
        <div className='checkboxes-part'>
            {fields.map((item, index) => {
                return(
                    <div>
                        <label>{item.label}</label>
                        <input type='checkbox' name='checked' value={item.name} onChange={handleChange} />
                    </div>
                )
            })}
        </div>
    )
}

export default CheckboxesComponent



dimanche 14 janvier 2024

I want to add a checkbox to Learndash checkout page

I a php and learndash beginner and need help. I would like to add a checkbox to the checkout page in learndash.

Can you have a hint which action hook will do. The checkbox should be added to the order overview page This page is shown after registration and has a buynow-button.

enter image description hereI have tried a lot of hooks without success.

Thanks a lot for your help




jeudi 11 janvier 2024

Using python, how can i check if a html checkbox is hidden, and if it's checked?

In an HTML form, I have a checkbox which class is 'hidden' or not, depending on the user's previous choices.

This is my HTML javascript code which creates the checkbox

const cityBusesLabel = document.createElement('label');
cityBusesLabel.textContent = `Use of city buses`;
const cityBusesInput = document.createElement('input');
cityBusesInput.type = 'checkbox';
cityBusesInput.name = `cityBuses ${venueNumber}-${originCounter}`;
cityBusesInput.id = `cityBusesInput ${venueNumber}-${originCounter}`;
cityBusesInput.classList.add('hidden');
cityBusesLabel.id = `cityBusesLabel ${venueNumber}-${originCounter}`;
cityBusesLabel.classList.add('hidden');
cityBusesLabel.appendChild(cityBusesInput);

And this is the HTML javascript code that shows / hides it :

document.getElementById('venue_location_' + venueNumber).addEventListener('input', function() { 
    const select_value = document.getElementById('venue_location_' + venueNumber).value;
    if (select_value === 'suburban') {
        document.getElementById('cityBusesInput ' + venueNumber + '-' + originCounter).classList.remove('hidden');
        document.getElementById('cityBusesLabel ' + venueNumber + '-' + originCounter).classList.remove('hidden');
    } else {
        document.getElementById('cityBusesInput ' + venueNumber + '-' + originCounter).classList.add('hidden');
        document.getElementById('cityBusesLabel ' + venueNumber + '-' + originCounter).classList.add('hidden');
    }
});

Now, in my app.py python code using Flask, I am trying to check first of all if the checkbox is hidden or not, and second of all if it's checked or not.

I tried writing :

cityBuses_checkbox = request.form.get(f'cityBuses {i}-{origin_counter}')
if cityBuses_checkbox :
    if cityBuses_checkbox == 'on' :
         city_buses.append(1)
    else :
         city_buses.append(0)

But it didn't give me the output I wanted. Is this the right way to do these two checks?




mardi 19 décembre 2023

Oracle Apex checkbox on the interactive report

i am trying to add checkbox column on a interactive report. https://hardlikesoftware.com/weblog/2015/07/24/apex-interactive-report-checkbox-row-selection/ this is the reference that i used. it works when i click the header and choose all the rows but when i click on a row spesifically it throws an error says : "Cannot read properties of undefined (reading 'checked')"

here is my dynamic actions:

var cb$, checked, allRows$,
    sel$ = $("#P1_SELECTED"),
    event = this.browserEvent,
    target$ = $(event.target),
    th$ = target$.closest("th"),
    tr$ = target$.closest("tr");

if (th$.length) {
    // the click was on the "select all"
    // checkbox or checkbox cell
    cb$ = th$.find("input");
    if (cb$.length && cb$.val() === "all") {
        checked = cb$[0].checked;
        if (target$[0].nodeName !== 'INPUT') {
            // only do this if the click was not on the checkbox
            // because the checkbox will check itself
            checked = cb$[0].checked = !checked;
        }
        if (sel$.val() === "") {
            sel$.val("|");
        }
        $("#seq_id").find("td input").each(function() {
            this.checked = checked;
            // give a visual style to the [un]selected row
            $(this).closest("tr").toggleClass("selected", checked);
            // update the hidden selected item
            sel$.val(sel$.val().replace("|" + this.value + "|", "|"));
            if (checked) {
                sel$.val(sel$.val() + this.value + "|");
            }
        });
    }
} else if (tr$.length) {
    // the click was on some other data row
    cb$ = tr$.find("td").first().find("input");
    checked = cb$[0].checked;
    if (target$[0].nodeName !== 'INPUT') {
        // only do this if the click was not on the checkbox
        // because the checkbox will check itself
        checked = cb$[0].checked = !checked;
    }
    // give a visual style to the [un]selected row
    tr$.toggleClass("selected", checked);
    // update the hidden selected item
    if (checked) {
        if (sel$.val() === "") {
            sel$.val("|");
        }
        sel$.val(sel$.val() + cb$.val() + "|");
    } else {
        sel$.val(sel$.val().replace("|" + cb$.val() + "|", "|"));        
    }
    // update the select all checkbox state
    allRows$ = $("#seq_id").find("td input");
    checked = (allRows$.length === allRows$.filter(":checked").length);
    $("#seq_id").find("th input")[0].checked = checked;
}

this is the after refresh script

var checked,
    allRows$ = $("#seq_id").find("td input");
allRows$.filter(":checked").closest("tr").addClass("selected");
checked = (allRows$.length === allRows$.filter(":checked").length);
$("#seq_id").find("th input")[0].checked = checked;

here is the error ss error




vendredi 8 décembre 2023

Formik library's checkbox is not working in Microsoft Edge but working in Chrome

I am using one checkbox using the formik library's Field component this check box is working fine in chrome but not in microsoft edge,

I have cleared the cache along with browser history and also the Microsoft edge is up to date. what do I do?

const useStyles = makeStyles(theme => ({
  checkBoxSize: {
    transform: 'scale(1.4)',
  },
  checkBoxDiv: {
    display: 'flex',
    alignItems: 'flex-end',
    marginBottom: theme.spacing(0.85),
  }
}))
const classes = useStyles()
   <Grid xs={1} className={classes.checkBoxDiv}>
                <Field
                  title="Update in Development Timeline"
                  type="checkbox"
                  name={`trainingGroups[${groupIndex}].trainings[${trainingIndex}].Is_centralize_duration`}
                  className={classes.checkBoxSize}
                />
              </Grid>



mercredi 6 décembre 2023

How to change the white tick color when using Material UI Checkbox (React, JS)

I'm trying to change the default white tick (not the checkbox background!) to some other color of my choice. I've found some solutions for when using an older version of MUI and React. I'm looking for a solution for MUI v5.14 and React v18

MUI checkbox for reference: https://mui.com/material-ui/react-checkbox/

Found this post, but it seems not relevant for the current versions: Change the tick color in MuiCheckbox material UI




dynamic checkbox is not showing selected value in ASP.Net core Razor Pages

I have a checkbox list where the values are loaded from a database table. When the user selects particular customer, it is updating the database value to '1', but in the razor pages view the values are showing unchecked. I am not sure where i am going wrong.

Please find my code below,

AccessRights.Cs(Model Class)

public class AccessRights
{
    [Key]
    public int Id { get; set; }
    public int EmployeeId { get; set; }

    [Display(Name = "Users")]
    public string Username { get; set; }
    public string ADUsername { get; set; }        
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public bool isSelected { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? CreatedTimeStamp { get; set; }
    public string LastModifiedBy { get; set; }
    public DateTime? LastModifiedTimeStamp { get; set; }
}

Edit.Cshtml

<div class="form-group">
                <label  class="control-label"> Access To Customers</label>
                <div class="checkbox checkboxlist">
                @{
                    foreach (var customers in Model.CustomersChecked)
                    {
                    
                        <input type="checkbox" id="@customers.Value" value="@customers.Value" name="CustomersChecked" checked="@customers.Selected" />
                        <label class="text-black">@customers.Text</label><br/>
                    //<input type="hidden" asp-for="@Model.CustomersChecked" value="@customers.Id">
                    }
                }
                </div>
                <span  class="text-danger"></span>
            </div>

Edit.Cshtml.Cs

[BindProperty]
        public List<SelectListItem> CustomersChecked { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null || _context.AccessRights == null)
            {
                return NotFound();
            }

            var accessrights = await _context.AccessRights.FirstOrDefaultAsync(m => m.EmployeeId == id);
            AccessRights = accessrights;
            CustomersChecked = (from p in _context.AccessRights.Where(m => m.EmployeeId == id)
                                                select new SelectListItem
                                                {
                                                    Text = p.CustomerName,
                                                    Value = p.CustomerId.ToString()
                                                }).ToList();
            //CustomersChecked = CustomersChecked.Where()
            return Page();
        }

        
     
        public async Task<IActionResult> OnPostAsync(string[] CustomersChecked)
        {
            List<SelectListItem> items = (from p in _context.AccessRights.Where(m => m.EmployeeId == AccessRights.EmployeeId)
                                          select new SelectListItem
                                          {
                                              Text = p.CustomerName,
                                              Value = p.CustomerId.ToString()
                                          }).ToList();
            foreach (SelectListItem item in items)
            {
                if (CustomersChecked.Contains(item.Value))
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }
                AccessRights.LastModifiedBy = HttpContext.Session.GetString("DisplayName").Trim();
                AccessRights.LastModifiedTimeStamp = DateTime.Now;
                await _context.Database.ExecuteSqlInterpolatedAsync($"UPDATE [AccessRights] SET [isSelected] = {item.Selected}, [LastModifiedBy] = {AccessRights.LastModifiedBy}, [LastModifiedTimeStamp] = {AccessRights.LastModifiedTimeStamp} WHERE [EmployeeId] = {AccessRights.EmployeeId} AND [CustomerName] = {item.Text}");

            }
            return RedirectToPage("./Index");
        }

Appreciate your help! Thanks!




get value with if condition in codeigniter form checkbox [closed]

i want to get the checkbox that value 1 if checked and 0 if unchecked

heres my form.php code

<?= form_open('What/yougot') ?>
<table>
<tr><td>
<input name="id" type="text">
</td></tr>
<tr><td>
<input name="method1" type="checkbox" value="valuee">
<input name="method2" type="checkbox" value="valuee">
<input name="method3" type="checkbox" value="valuee">
</td></tr>
<tr><td>
<input name="show" type="submit">
</td></tr>
</table>
<?= form_close() ?>

i DO NOT know how to put it in controller but i want something like this

public function yougot (){

if (isset($_POST['show'])) {
$data = [
'id'=>$this->model_yougot->showYougot(id)->result_array(), //to select name and id based on id

if ('method1' = 'valuee'){
'metode1' => 1 } else {
'metode1' => 0 },
if ('method2' = 'valuee'){
'metode2' => 1 } else {
'metode2' => 0 },
if ('method3' = 'valuee'){
'metode3' => 1 } else {
'metode3' => 0 },
];

}

$this->load->view('view_yougot',$data);

}

this is the model

public function showYougot($id){
return $this->db->get_where('data',['id'=>$id]);
}

and then in the view_yougot.php i want these variables

$id = $data['id'];
$name = $data['name'];
$metod1 = $data['metode1'];
$metod2 = $data['metode2'];
$metod3 = $data['metode3'];

and use them to show the value somewhere like

name = <?= $name; ?><br>
id =  <?= $id; ?><br>
mehhod 1 = <?= $metod1; ?><br>
mehhod 2 = <?= $metod2; ?><br>
mehhod 3 = <?= $metod3; ?>

each $metod1 $metod2 $metod3 is showing 1 if checked or 0 if unchecked

i know im doing the select name and id wrong please help me correct it too. i have looked on google and can't find tutorials. alternatives way is okay. this is my first time please kindly teach me thank you




mardi 5 décembre 2023

Blazor FluentValidation and invalid class on checkboxes

I am working with Blazor WASM and FluentValidation project. The validation works, but for checkboxes, the invalid class is not added to invalid checkboxes, when that object isnt valid.

For my radio button groups, the validation invalid class works fine, and the validation updates when you select a radio button making it valid. This is because I am binding to SelectedValues in the InputRadioGroup.

My validator has the following rule.

 RuleFor(r => r.SelectedValues).NotEmpty().NotNull().When(r => r.IsRequired).WithMessage(r => $" XXX is required.");

Then on my razor page, I have this..

<InputCheckbox class="form-check-input" @bind-Value="@x.Selected" CurrentValue="@x.Value" />

When viewing the page, the InputCheckbox has "form-check-input valid" which may not be correct. Again if I dont select anything, and click the submit button, the validation message appears, but it doesnt disappear when I check/select a checkbox making it valid, as well as the invalid css class isn't applied to the checkboxes.

Is it because I am validating SelectedValues, which in this case is a comma separated list, but the checkboxes aren't bound at all to that property? There isnt a grouping component like there is InputRadioGroup.

There may be a simple solution for this, but I havent figured it out yet.




Save multiple checkbox value to database in ASP.NET Core MVC

I am using checkboxes to save data in database. It can save only one value at a time. When multiple values are selected, it only stores the first selected value.

I have Googled my problem. Multiple solutions suggested the use of List<string> Name in Model. I tried to do so but my controller gave me error CS0029.


  • Database Table (CollectionCategories):
Id CategoryName
1 First Category
2 Second Category
... ...

Code-

  • Model:
public class PostModel
{
    // Code before

    public string? CollectionCategory { get; set; }
}
public class CollectionCategoryModel
{
    [Key]
    public int Id { get; set; }
    public string CategoryName { get; set; }
}
  • ViewModel:
public class CreatePostViewModel
{
    // Code before
    
    // Category
    public string? CollectionCategory { get; set; }

    // Category List
    public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}
  • Controller:
public async Task<IActionResult> CreateAsync()
{
    // Category List
    var CreatePostCategoryVM = new CreatePostViewModel
    {
        CollectionCategoryList = await _context.CollectionCategories.ToListAsync()
    };

    return View(CreatePostCategoryVM);
}

[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
    if (ModelState.IsValid)
    {
        var post = new PostModel
        {
            // Code before             

            // Category
            CollectionCategory = postVM.CollectionCategory,
        };

         return RedirectToAction("Index");
    }
    else
    {
        // Error
    }
    return View(postVM);
}

  • View:
<div class="form-check">
    @foreach (var list in Model.CollectionCategoryList)
    {
        <input type="checkbox" asp-for="CollectionCategory" id="@list.CategoryName" value="@list.CategoryName">
        <label asp-for="CollectionCategory" for="@list.CategoryName"> @list.CategoryName </label>
    }
</div>

Edited

Error:

(JsonReaderException: 'S' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 1.)

  • Controller
[HttpGet]
public async Task<IActionResult> Index()
{
    var CardPostVM = new CardsViewModel
    {
        PostCard = await _context.Posts.ToListAsync()
    };

    var cached = _cache.TryGetValue("post", out var post);
    if (cached)
    {
        return View(post);
    }

    return View(CardPostVM);
}
  • ViewModel
public class CardsViewModel
{
    public List<PostModel>? PostCard { get; set; }
    public List<CollectionModel>? CollectionCard { get; set; }
}

Error Image


Thank you




lundi 4 décembre 2023

how to ask multiple selected question radio button/checkbox

There should be three checkboxes/radiobuttons. When I click on one, the others should be grayed out. For example, when I click on someone, I have to make different selections. When I click on the other, different selections. How can I do that. For example, when I click on the first radio button. There should be a file upload button at the bottom. When you click on the second radio button, there should be text for writing. How can I do this with html css?

There should be a file upload button at the bottom. When you click on the second radio button, there should be text for writing. How can I do this with html css?




How do I Write a Google Sheets Custom Conditional Format that Applies to Multiple Two-Column Sets in a Single Formula?

I want to make many columns of checklists that can be moved around without messing up the conditional formatting ranges. I know this can be done with multiple rules but if i want to move things around, I dont want the ranges to start acting up so a single rule would work best.

In Column A, there are checkboxes and the tasks in column B. There will be more checkboxes in column C and more tasks in column D and so on. If A2 is true, I only want to format cells A2 and B2. If C3 is true, I only want to format cells C3 and D3. Can this be done with a single formula? I'm trying to avoid app scripts, but maybe its the only way. I'm not sure. Thanks!

I've tried using separate rules for sets of two columns and that only works if you're not actively copying tasks back and forth which users will be doing a lot of.




dimanche 3 décembre 2023

updating a state inside a map, causes to push new elements to state that I don't want

here I have data state which I'm trying to loop over it with map function, and print out checklist which I called myChecklist.

import React, { useState } from 'react'

const App = () => {

  const [data, setData] = useState([
    {
      id:0,
      isChecked: true
    },
    {
      id:1,
      isChecked: false
    },
    {
      id:2,
      isChecked: false
    },
  ])
  

  const myCheckList = data.map((checkbox, index) => {
    return (
      <div key={index}>
        <input type="checkbox" 
          checked={checkbox.isChecked} 
          onChange={e => {setData(prev => [...prev, prev[index].isChecked = e.target.checked])}} 
          id={index} />
        <label htmlFor={index}>{checkbox.id}</label>
      </div>
    )
  })

  console.log(data)

  return (
    <div>{myCheckList}</div>
  )
}

export default App

every time I click my any of the checkboxes, it updates to isChecked Boolean referring to that checkbox. the problem is pushes new elements to the data state which cause the to map function to create a new checkbox I don't want. when ever I click the my checkboxes the log of **data **state should look like this:

[
    {
        "id": 0,
        "isChecked": true
    },
    {
        "id": 1,
        "isChecked": false
    },
    {
        "id": 2,
        "isChecked": false
    }
]

but after changing the checkbox a couple of times it would look like this:

[
    {
        "id": 0,
        "isChecked": true
    },
    {
        "id": 1,
        "isChecked": false
    },
    {
        "id": 2,
        "isChecked": false
    },
    false,
    true
]

noticed some true false values pushed to the state. I am NOT pushing anyThing so why this happens ????

I'll appreciate your help. thanks

I tried to separate the state that I am mapping throw and the state I want to update like this

import React, { useState } from 'react'

const App = () => {

  const [isChecked, setIsChecked] = useState([
    {isChecked: false},
    {isChecked: false},
    {isChecked: false}
  ])

  const data = [
    {
      id:0,
    },
    {
      id:1,
    },
    {
      id:2,
    },
  ]


  const myCheckList = data.map((checkbox, index) => {
    return (
      <div key={index}>
        <input type="checkbox" 
          checked={isChecked[index].isChecked} 
          onChange={e => {setIsChecked(prev => [...prev, prev[index].isChecked = e.target.checked])}} 
          id={index} />
        <label htmlFor={index}>{checkbox.id}</label>
      </div>
    )
  })

  console.log(isChecked)

  return (
    <div id='my-id'>{myCheckList}</div>
  )
}

export default App```

no new checkboxes would be printed to DOM but the issue of pushing elements I don't to the state, still remains



samedi 2 décembre 2023

Save PDF FormFields using VBA Excel

I've been writing values in the form fields from cell values in excel using VBA The problem is when it comes to checkbox, I have two checkbox, say checkbox 1 and checkbox 2. In order fot the checkbox1 to be marked the values of them must be 1 and 1 respectively For Checkbox2 to be marked, the values of the two checkbox must be 0 and 2 respectively I also have checkbox that is either 0 and 1 for it to be marked or not.

Whenever the program is done, you can check from the preview of the generated PDF file that markings are done correctly, but when you try to open it, values are there for text fields but the checkmarks are back to its default markings.

Is there something wrong with the values i stored for the checkbox.? I check the identification of the form field their type and values to get the right I.D. for the checkbox.

I tried writing it to 0 and 1 for on and off. Didn't solve the problem.

I tried going to PDF's Edit>Preferences>Documents> Checked "Save As Optimizes for Fast Web View"

I tried bringing it to front, automate left click and ctrl S, but it didn't work out

I simulated click on the boxes, and it is working fine.

Is there a way to get it right without simulating click?, because users might be using different dimensions in the screen, so it would be different target point for the click.




vendredi 1 décembre 2023

Assign code to multiple commandbuttons via loop

I am currently working on a vocabulary programm. That includes choosing which chapters (1-35) should be checked. I have a userform with 35 checkboxes. I have assigned the properties for the checkboxes via loop. Now I have to give every checkbox a induvidial code, the code is:

Privat Sub Checkbox1()
Chapters_checked(Chapter_number)=true
End sub

Chapters_checked is an array which stores, wheather a chapter needs to be checked or not. As you can see the code can be written with a loop, but I do not know how to give every checkbox a code with a loop. Anyone has an idea? Conrad

I did not try anything, since I did not found the tag "code"




MudBlazor checkboxes in tables being independent from one another

I want the user to be able to check only one Element at a time. If they check another element then that becomes checked any the others are false. I'm using MudBlazor and I tried to control this via a method but I've failed horribly.

<MudTable T="Element" Items="@Elements" Hover="true">
    <HeaderContent>
        <MudTh>checkbox</MudTh>
        <MudTh>Nr</MudTh>
        <MudTh>Name</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="checkbox">
            <MudCheckBox Value="@context.Checked" T="bool" CheckedChanged="CheckedChanged" Color="Color.Warning" CheckedIcon="@Icons.Material.Filled.PersonPinCircle" UncheckedIcon="@Icons.Material.Outlined.PersonPinCircle"></MudCheckBox>
        </MudTd>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
    </RowTemplate>
    <PagerContent>
        <MudTablePager PageSizeOptions="new int[]{50, 100}" />
    </PagerContent>
</MudTable>



@code {
    private IEnumerable<Element> Elements = new List<Element>()
    {
        new Element("helium", 1),
        new Element("borium", 45),
        new Element("argon", 346),
        new Element("oxygen", 51),
        new Element("radium", 467),
    };

    protected void CheckedChanged(object sender, EventArgs e)
    {
        // Set every other elements checked to false
        foreach (var item in Elements)
        {
            item.Checked = false;
        }   

        // set this elements checked value to what is is not
        CheckBox3 = !CheckBox3;
    }

    public class Element
    {
        public string Name { get; set; }
        public int Number { get; set; }
        public bool Checked { get; set; }

        public Element(string name, int number)
        {
            Name = name;
            Number = number;
            Checked = false;
        }
    }
}



jeudi 30 novembre 2023

Wix website: How to have a section of a profile (user ID) page collapsed, until the user checks a checkbox on their "update profile" page?

When a user signs up, multiple pages are created (because of how I'm working with Wix Dynamic pages and their Content Management System). Among those pages are the public profile page and the private update profile info page.

How do I keep a section of the public profile page collapsed until the user decides to check a checkbox on the "update profile info" page?

I've already managed to set the default value of the section as collapsed. It was an option that didn't require code.

I'm new to coding, btw, but not a complete noob.

I don't know exactly how to get checking the checkbox to expand the collapsed section.

And in this case, section and checkbox are on two different pages, which complicates things even further.

I hope you guys have some ideas and I appreciate any time you take to look into this.




Powershell implementing checkboxes within a table of data

Currently writing a PowerShell script to query DB & convert that info to a DataTable. Then output all to HTML file. I want 3 columns of the table to be outputted as checked checkboxes instead of T/F. Meaning instead of a value in table being true, it will appear as a check box.

I have tried writing a While loop to loop through the elements.