dimanche 30 avril 2023

Mark updated checkbox of a many-to-many relationship in laravel

I am trying to show the updated checkboxes that are fetched from a many-to-many relationship.

Model Candidato:

public function estadox()
    {    
        return $this->hasMany(CandidatoEstadoPostulacion::class, 'status_id', 'user_id');
    }

Model Estado Postulacion

public function estados()
    {
        return $this->hasMany(CandidatoEstadoPostulacion::class, 'status_id', 'id');
    }

Model CandidatoEstadoPostulacion

    public function candidatos()
    {
        return $this->hasMany(Candidato::class,  'status_id', 'user_id');
    }

    public function estados()
    {
        return $this->hasMany(EstadoPostulacion::class, 'id', 'status_id');
    }

Controller Candidatos

public function index( Vacancy $vacante, Candidato $candidato )
    {
        $estados = EstadoPostulacion::pluck('status', 'id');

        $ca = Candidato::with('estadox')->get();

        return view('candidatos.index', compact('vacante', 'estados', 'candidato') );
    }

table Candidatos :

| id | user_id| vacancy_id|

table estado_postulaciones :

| id | status |

table candidato_estado_postulaciones : | status_id | user_id |

view candidatos/index.blade.php

 @forelse ($estados as $id => $estado)
     <div>
          <input type="checkbox" name="status[]" id="-" class="peer hidden" value=""  onchange="this.form.submit()">
          <label for="-" class="block cursor-pointer select-none rounded-xl p-2 text-center peer-checked:bg-blue-500 peer-checked:font-bold peer-checked:text-white">
          <i class="fas fa-folder fa-2x"></i>
          <div class="w-full text-xs">Está en:</div>
          <div class="w-full text-xs text-gray-800 font-semibold uppercase"></div>
          </label>
   </div>
   @empty
      <li>No existe ningun estado en la BD</li>
   @endforelse

Image of what I need it to show: enter image description here




samedi 29 avril 2023

How to save checkbox value from list in flutter?

I have listview with checkbox, I saved different products with ids in the list.

When checkbox value is true, product will save in that list and when checkbox value is false, product will remove from that folder.

I want to save the checkbox value is true if the product id is already inside list folder.

Is there any way to do it?

This is some part of the code-

List<int> _selected_box = [];
List<int> selectedProductIds = [];

Listview builder-

'snapshot.data!.data[index].id' = id of folder in list

'widget.prod' = id of products which save in folder

ListView.builder(
                                  itemCount: snapshot.data!.data.length,
                                  itemBuilder: (context, index){
                                    bool isSelected = selectedProductIds.contains(snapshot.data!.data[index].id);
                                    return CheckboxListTile(
                                      title: Text(
                                        snapshot.data!.data[index].name,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(color: kblue, fontSize: 20.sp, fontWeight: FontWeight.bold),
                                      ),
                                      activeColor: kblue,
                                      value: _selected_box.contains(index),
                                      onChanged: (value) {
                                        setState(() {
                                          // Check if index is already selected
                                          if (_selected_box.contains(index)) {
                                            _selected_box.remove(index);
                                            selectedProductIds.remove(int.parse(snapshot.data!.data[index].id));
                                            futureRemoveMenuData = fetchRemoveMenuData(snapshot.data!.data[index].id, widget.prod);
                                            futureDeleteMenu = fetchDeleteMenu(widget.prod);
                                            futureCreateMenu = fetchCreateMenu();
                                            Fluttertoast.showToast(
                                              msg: "Item Removed from Menu!", // your toast message
                                              toastLength: Toast.LENGTH_SHORT, // duration of the toast
                                              gravity: ToastGravity.BOTTOM, // toast gravity
                                              backgroundColor: Colors.black54, // bFackground color of the toast
                                              textColor: Colors.white, // text color of the toast
                                            );
                                          } else {
                                            _selected_box.add(index);
                                            selectedProductIds.add(int.parse(snapshot.data!.data[index].id));
                                            futureAddMenuData = fetchAddMenuData(snapshot.data!.data[index].id, widget.prod);
                                            futureCreateMenu = fetchCreateMenu();
                                            Fluttertoast.showToast(
                                              msg: "Item Added to Menu!", // your toast message
                                              toastLength: Toast.LENGTH_SHORT, // duration of the toast
                                              gravity: ToastGravity.BOTTOM, // toast gravity
                                              backgroundColor: Colors.black54, // background color of the toast
                                              textColor: Colors.white, // text color of the toast
                                            );
                                          }

                                          // Update the futureAddMenuData based on the new selection
                                          if (value == true) {
                                            futureAddMenuData = fetchAddMenuData(snapshot.data!.data[index].id, widget.prod);
                                          }
                                          else{
                                            futureRemoveMenuData = fetchRemoveMenuData(snapshot.data!.data[index].id, widget.prod);
                                            futureDeleteMenu = fetchDeleteMenu(widget.prod);
                                          }
                                        });
                                      },
                                      contentPadding: EdgeInsets.zero,
                                      controlAffinity: ListTileControlAffinity.leading,  //  <-- leading Checkbox
                                    );
                                  }
                              );

Here is the output-

enter image description here




vendredi 28 avril 2023

Using javascript to create a checkbox with a label to the right

I'm using Javascript to construct a html, I'm trying to put a label to the right of the checkbox.

I tried different line order with the Javascript code and different appendChild order, but I never get the result I want.

    const div_recordar_login = document.createElement("div");
    div_recordar_login.classList.add("remember-forgot");
    form_login.appendChild(div_recordar_login);

    const label_chk_rec_log = document.createElement("label");
    div_recordar_login.appendChild(label_chk_rec_log);

    const input_chk_rec_log = document.createElement("input");
    input_chk_rec_log.type = "checkbox";
    label_chk_rec_log.textContent = "Recordar usuario ";
    label_chk_rec_log.appendChild(input_chk_rec_log);

This is what I expect in html

    <div class="remember-forgot">
    <label><input type="checkbox">Recordar usuario</label>

This is what I'm getting

    <div class="remember-forgot">
         <label>
         Recordar usuario 
         <input type="checkbox">
         </label>



How to fix this emoji appearing in place of a checkbox while using checkbox from react native paper?

I'm using the Checkbox component from react-native-paper and this emoji is appearing instead of a checkbox

Baby emoji instead of checkbox screen

Import

import { Checkbox } from "react-native-paper";

Code

<Checkbox  
    status={isVisible?'checked':'unchecked'}
    onPress={()=>{
        setVisible(!isVisible);
    }}
/>



Is it possible to set property we are binding a TextBox value to in WPF?

I have a checkbox and a textbox. When checkbox is unticked I would like the textbox to be disabled and cleared, so when the user hits save, an empty string should be saved to the property the textbox is bound to. Currently however only the content itself gets erased. Is there a way I can change my code to the property bound gets changed too? I would like the same effect uppon unchecking the checkbox, as if the user erased the textbox contents by hand.

<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
    <Setter Property="Text" Value="{Binding Path=Data.SomeValue, Mode=TwoWay}" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=SomeCheckBox, Path=IsChecked}" Value="False">
            <Setter Property="IsEnabled" Value="False" />
            <Setter Property="Text" Value="{Binding x:Null}" />
        </DataTrigger>
    </Style.Triggers>
</Style>
</TextBox.Style>



jeudi 27 avril 2023

Microsoft Access Checkboxes are behaving like radio buttons

I have a form in MS Access that I am developing. I have two checkboxes that are not mutually exclusive - CANCELLED and SUBMITTED. The checkboxes are not bound to any data table or query. I want the checkboxes to behave like you would expect checkboxes to behave - I can select them independently - zero, one or two of the controls can be checked. Very oddly though, they are behaving as if they were grouped radio buttons - if I choose one checkbox the other is unchecked. Like a radio button, I can't unselect it at all. This all seems related to the OptionValue property. I tried unsetting the value, but Access won't allow that and gives an error! I have also tried setting them to different values including 0 or -1 hoping that was a magic value to indicate that my checkbox should behave like a checkbox. How do I get checkboxes to behave like checkboxes?

Access checkbox property editor

Checkboxes should not be mutually exclusive options




mercredi 26 avril 2023

Python PySimpleGui and tkinter CheckBox question on text flashing

I have a specific question on the Checkbox object in pySimplegui and Tkinter.

For reference on I'm a Windows 10 computer. Python version 3.9.2 PySimpleGUI version 4.57.0 tkinter 8.6.9

Here are 2 coding examples

First is tKinter:

import tkinter as tk
window = tk.Tk()
window.title('My Window')
window.geometry('100x100')
c1 = tk.Checkbutton(window, text='Checkbox Text', onvalue=1, offvalue=0, pady=40)
c1.pack()
window.mainloop()

Second is pySimplegui:

import PySimpleGUI as sg
layout = [[sg.Checkbox('Checkbox Text')]]
window = sg.Window("Small Checkbox", margins=(40,40), layout=layout, finalize=True) 
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
window.close()

When using tKinter and clicking on the Checkbox, the text remains on the screen (non flashing).

When using pySimplegui and clicking on the Checkbox, the text turns on and off quickly (flashes).

I'm trying to eliminate that flashing when using the Checkbox in pySimplegui. Any suggestions?

I have not been able to solve this.




mardi 25 avril 2023

Why am I getting "you cannot call a method on a null-valued expression?"

I have an xaml with this structure

<Grid>
   <TreeView ItemsSource="{Binding Source={StaticResource xmlData},XPath=//@Name}">
      <TreeView.ItemTemplate>
         <DataTemplate>
            <CheckBox Name="Check1">
               <TreeViewItem Header="{Binding XPath.}"/>
            </CheckBox>
         </DataTemplate>
      </TreeView.ItemTemplate>
   </TreeView>
</Grid>

that I am attempting to add a handler to with the code

 $var_Check1.addhandler([System.Windows.Controls.Checkbox]::CheckedEvent,$check_checked)

Note: I have all of my variable set to var_ when they are captured from the xaml, hence the discrepancy

The idea and thought behind this entire program is to have the treeview with checkboxes so I can perform an action on only the selected items. The code for the xml is

<Foods>
    <UnhealthyFoods Name ="Candy"/>
        <Food Foodname = "MMs" >
        </Food>
        <Food Foodname = "Skittles" >
        </Food>
        <Food Foodname = "Starburst" >
        </Food>
    </UnhealthyFoods>
    <HealthyFoods>
        <FoodGroup1 Name ="Vegetables"/>
        <Food Foodname = "Spinach" >
            </Food>
            <Food Foodname = "Brocolli" >
            </Food>
            <Food Foodname = "Greens" >
            </Food>
    </FoodGroup1>
    </HealthyFoods>
    <HealthyFoods>
        <FoodGroup2 Name ="Fruits"/>
        <Food Foodname = "Apples" >
            </Food>
            <Food Foodname = "Pears" >
            </Food>
            <Food Foodname = "Cherries" >
            </Food>
    </FoodGroup2>
    </HealthyFoods>
</Foods>

So the three checkboxes should show up as (pretend these are checkboxes)

  • Candy
  • Vegetables
  • Fruit

Ideally I click a button that performs an action on the selected groups, alas I can't make it that far




lundi 24 avril 2023

Why do we need an invisible input when we make a custom checkbox?

I am going to customize an checkbox.

Generally, we create it by adding an invisible input and control value with it. Here is my mock code.

import "./styles.css";
import { useState } from "react";

function Checkbox() {
  const [isChecked, setIsChecked] = useState(false);

  return (
    <label>
      <input
        type="checkbox"
        onChange={() => {
          setIsChecked(!isChecked);
        }}
      />
      <svg
        className={`checkbox ${isChecked ? "checkbox--active" : ""}`}
        aria-hidden="true"
        viewBox="0 0 15 11"
        fill="none"
      >
        ...
      </svg>
      Check me!
    </label>
  );
}

But I think we can do it without the invisible input. Here is my mock code.

function Checkbox() {
  const [isChecked, setIsChecked] = useState(false)

  return (
    <div
      className={`checkbox ${isChecked ? 'checkbox--active' : ''}`}
      onClick={() => { setIsChecked(!isChecked) }}
    >
      <svg .../>
      Check me!
    </div>
  )
}

Are there will be side effect when we use div instead of input. If we use an invisible input, we should align 100% with the custom icon.




jquery slider of checkbox options and get values

I have some checkbox options with values and I need to transform it to slider from first value to last value, like a price filter slider. As the slider moves, options that are out of range become unselected. Exactly like the price slider.

<ul class="filter_group sub38" data-feature="38" data-feature_url="memmorysize">
                    
                    <li class="filter_list first">
                        <label class="filter_label">
                            <input class="filter_input cb2" data-feature_url="" type="checkbox" checked="">
                            <span data-language="83">All</span>
                        </label>
                    </li>
                    
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="4096" type="checkbox">
                                <span>4096</span>
                            </label>
                        </li>
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="8192" type="checkbox">
                                <span>8192</span>
                            </label>
                        </li>
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="12288" type="checkbox">
                                <span>12288</span>
                            </label>
                        </li>
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="16384" type="checkbox">
                                <span>16384</span>
                            </label>
                        </li>
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="32768" type="checkbox">
                                <span>32768</span>
                            </label>
                        </li>
                                            <li class="filter_list">
                            <label class="filter_label">
                                <input class="filter_input cb3" data-option_url="40960" type="checkbox">
                                <span>40960</span>
                            </label>
                        </li>
                                                        <div class="show_hide_list sub38" data-feature="38" style="display: none;">Show all</div>
                
                </ul>

I have tried to use this - https://api.jqueryui.com/slider/. But, I can't get this to work. Help me, please.




dimanche 23 avril 2023

I'm looking to use string split to access comma separated data in this vue 3 array using checkbox filtering but I can't work it out

I have an array of data and I have checkboxes to filter the array. The search section works fine but when I try to select the filters, none of them work due to the data being a comma separated string.

Here is a link to the codesandbox where you can find the code: MusicView Link

Here is the page: Music Page

This is something that I am struggling to work out and any help would be great!




vendredi 21 avril 2023

How to delete Google sheet rows if two checkboxes o the row are true

i have a Google spreadsheet that we use to support our helpdesk

I'm trying to make a macro, on event, so that when two checkboxes in the row (column A and column H) are both true, the row is deleted. I'm trying to figure how to do but with no sucess. Anyone can help? Thanks a lot

I tried some scripts available on web, to delete a single row on checkbox state, but i can't make them work.




Update Angular 14 to 15: mat-pseudo-checkbox no more visible

I have to update my web application from Angular 14 to 15 but I have a strange problem, my mat-pseudo-checkbox (code below) is not more visible.

<div>
   <mat-pseudo-checkbox (click)="itemSelect()" [state]="isItemSelected()"></mat-pseudo-checkbox>
Test

In Angular 14 the "mat-pseudo-checkbox" was visible. If I change the code with "mat-checkbox" the checkbox appears. I have not CSS relative the "mat-pseudo-checkbox" and I'm not able to find any informations about the porting from 14 to 15 for the "mat-pseudo-checkbox". Can someone help me?

Thanks in advanced




jeudi 20 avril 2023

Select and deselect radio buttons in swift

I've been trying to program these buttons. but these two functions can't work in same time, How can I fix this?

    @IBAction func buttonPressed(sender: AnyObject) {
        if let radioIn = sender as? UIButton {
            if radioIn.isSelected {
                // set deselected
                radioIn.isSelected = false
            } else {
                // set selected
                radioIn.isSelected = true
            }
        }
    }
    
    @IBAction func radioSelect(_ sender: UIButton) {
        if sender == radioIn{
            radioIn.isSelected = true
            radioOut.isSelected = false
        }else{
            radioIn.isSelected = false
            radioOut.isSelected = true
        }
    }



Is there a way to dynamically name/control checkboxes in visual basic?

I have xaml code that creates a list view with two columns; the first column is checkboxes based on the number of items that are in the second column. The issue with the way the code is written is the checkboxes do not have their own names (as far as I can tell). If i rename the object then all 15 of the checkboxes will be named the same thing not allowing me control over what happens if any one is checked (I think). Is there a way I can code it to where they have independent control from one another?

This is what I used to create this far

<Grid>
   <ListView Grid.Row="2" Grid.Column="2" ItemsSource="{Binding XPath=..//@ParentAttribute}">
      <ListView.View>
         <GridView>
            <GridViewColumn Header="Selection">
               <GridViewColumn.CellTemplate>
                   <DataTemplate>
                      <CheckBox Name="Check"/>
                   </DataTemplate>
               </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn>
            </GridViewColumn>
         </GridView>
      </ListView.View>
   </ListView>
</Grid>



How to get single selected item from multiple listview? [closed]

I want to implemented the below UI design. There are two options available as a payment option i.e. Saved cards and regular(COD/Credit Card) Payment. User need to choose any either of them.

enter image description here

To achieve this,I have added recyclerview for each payment option i.e. One Recycler view for Saved Cards and one for the Other Payment Options.

As i said, user can select any one payment option from both the recyclerviews. On selection of any item(payment option), other items of should be deselected. So how to get the selected item from recyclerviews ?

Other possible solution is that I can try the multi-section recycler view to build the same UI. My only worry is that can we get only single item selection in multi-section recycler view?

Any help/guidance/samples will be really appreciated.




mercredi 19 avril 2023

uncheck child checkboxes in another groups when checking multiple child checkboxes in current group

I have created a parent child checkbox setup. When the parent checkbox is checked, the child checkboxes will be visible where multiple checkboxes can be checked.

But I want to uncheck the child checkboxes in the other groups. So you are only allowed to check multiple checkboxes in a certain group at a time. As I only want to save a subgroup of checkbox values.

See setup below for the parent child checkbox setup

<ul class="acf-checkbox-list acf-bl">
<li data-id="354"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="354"> <span>topic 1</span></label><ul class="children acf-bl" style="display: block;">
<li data-id="377"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="377"> <span>subtopic a </span></label></li>
<li data-id="361"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="361"> <span>subtopic  b</span></label></li>
<li data-id="366"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="366"> <span>subtopic  c</span></label></li>
</ul>
</li>
<li data-id="372"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="372"> <span>topic 2</span></label><ul class="children acf-bl">
<li data-id="389"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="389"> <span>subtopic x</span></label></li>
<li data-id="399"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="399"> <span>subtopic  y</span></label></li>
</ul>
</li>
<li data-id="373"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="373"> <span>Topic 3</span></label><ul class="children acf-bl">
<li data-id="410"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="410"> <span>subtopic 1</span></label></li>
<li data-id="412"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="412"> <span>subtopic 2 </span></label></li>
<li data-id="409"><label><input type="checkbox" name="acf[field_63fb5f54847a5][]" value="409"> <span>subtopic 3</span></label></li>
</ul>
</li>
</li>
</ul>

const checkbox = document.querySelectorAll('.acf-checkbox-list > li > label > input');
checkbox.forEach(function(checkitem){
var value = checkitem.value;
checkitem.addEventListener('click', (event) => {
const parentli = document.querySelector('[data-id="'+value+'"]').querySelector('.children');
if (checkitem.checked) {
parentli.style.display = "block";
}
else {
parentli.style.display = "none";
}
})
});

.children {
  
  display:none;
}

Thank in advance!




Checkbox disabel

I have created several checkboxes (4) in html. Now I want to program with javascript that there is basically only 1 option, so only one checkbox can be ticked with it. Probably not that difficult. Problem: I only worked with Java during my training and now I have to do it for a colleague who is currently ill. Since I currently have Corona and during the Easter holidays in Germany I feel like I'm the only one who works, I can't ask a colleague how it is to do.

I tried what would be logical for me and what I knew with my little javascript knowledge. So:

if (getElementById("Haken1")==true) { getElementById("Haken2")==false; } I thought that might work, but didn't.




checkbox checked when dark mode is activated / control checkbox via js or other solution

made a html/css website with a toggle switch checkbox that activates dark mode via :root / body:has(.toggleclass:checked)... toggle works fine, but now i want dark mode to appear when someone has enabled dark mode on his device. i know i could put the dark mode values in @media (prefers-color-scheme: dark) {...} and it would work, but then the toggle doesn't work anymore. is there a possibility to check the checkbox when dark mode is activated on a device?

        <div id="toggle-switch">
            <input id="toggle" type="checkbox" class="darkmode">
            <label for="toggle" >
            </label>  
        </div>

i think it only works with js, but my js skills are very poor...




mardi 18 avril 2023

How to use Checkbox checked value in C# ASP.Net MVC

I'm new to ASP.Net so any help greatly appreciated.

I've added a checkbox to a page, to choose between including archived customers or not:

    <form>
            <div class="form-group">
                <label class="col-lg-3 control-label">Include Archived Customers</label>
                <div class="col-lg-9">
                    <input class="form-control" style="transform:scale(0.5)" type="checkbox" ng-model="includeArchived" ng-change="includeFlagsChanged()" />
                </div>
            </div>
        </form>

This is the script that I've tried to add to:

<script>
    var app = angular.module("InvAggApp", ['angular-loading-bar']);
    app.controller("customerLinkController", function ($scope, $http) {
        $scope.includeArchived = false;
        $http.get("/DataLink/CheckForXeroToken")
            .then(function (response) {
                $scope.response = response;
                if (response.data.Success) {
                    $scope.hasXeroToken = response.data.hasXeroToken;
                    if ($scope.hasXeroToken) initialise();
                } else {
                    $scope.error = response.data.Exception;
                }
            }, function (response) { $scope.error = response });

        var initialise = function () {
            $http.post("/DataLink/GetCustomerLinks")
                .then(function (response) {
                    includeArchived: $scope.includeArchived
                    $scope.error = null;
                    $scope.response = response;
                    if (response.data.Success) {
                        $scope.customers = response.data.customers;
                        $scope.wcCustomers = response.data.wcCustomers;
                    } else {
                        $scope.error = response.data.Exception;
                    }
                }, function (response) { $scope.error = response });
        }

        debugger;
        $scope.includeFlagsChanged = function () {
            $scope.includeArchived = includeArchived;            
        };

Then this where I need to use it, I'm wanting to replace the .Where(xc => xc.archived == false) to use the includeArchived value of checkbox

public async Task<JsonResult> GetCustomerLinks() {
            try {
                var xeroSession = new XeroSessionManager();
                var xeroData = new XeroData(xeroSession);
                var xeroCustomers = await xeroData.GetAllCustomers();
                
                using (var cx = new BillingAssistantContext()) {
                    var wcCustomers = cx.Companies.Select(c => new { wcId = c.ID, wcName = c.Name }).OrderBy(c => c.wcName).ToArray();
                    var customers = xeroCustomers.Select(xc => {
                        var cl = cx.CustomerLinks.SingleOrDefault(l => l.XeroContactID == xc.ContactID);
                        return new {
                            xeroId = xc.ContactID, xeroName = xc.Name,
                            wcCustomerId = cl?.WCompanyID,
                            archived = cl?.Archived
                        };
                    }).Where(xc => xc.archived == false).OrderBy(xc => xc.xeroName).ToArray();

                    return new JsonResult {
                        Data = new {
                            Success = true,
                            customers = customers,
                            wcCustomers = wcCustomers,
                        }
                    };
                }



lundi 17 avril 2023

I need help getting this checkbox filter and search to work in Vue 3 Composition API

Thank you to the people who've helped me so far. Here is a link to the code in question: Link

Here is the code that I can't get to work properly:

const trackFilter = (tracks, type) =>
state.checkboxFilter[type].length > 0
? tracks.filter((track) => {
    let length = state.checkboxFilter[type].length;
    while (length--) {
      if (track[type].indexOf(state.checkboxFilter[type][length]) !== -1) {
        return true;
      }
    }
  })
: tracks;
const state = reactive({
search: "",
checkboxFilter: {
genre: [],
moods: [],
tempo: [],
theme: [],
},
tracks: [],
filteredTracks: computed(() =>
["genre", "moods", "tempo", "theme"]
  .reduce((tracks, item) => trackFilter(tracks, item), state.tracks)
  .filter(
    (track) =>
      track.keywords.toLowerCase().match(state.search.toLowerCase()) ||
      track.title.toLowerCase().match(state.search.toLowerCase()) ||
      track.description.toLowerCase().match(state.search.toLowerCase())
  )
 ),
 });
 const { search, checkboxFilter, filteredTracks } = toRefs(state);

I am trying use checkboxes to return tracks that contain the matching genres, moods, tempos, and themes in the array of tracks. They are stored in the array as strings so it has been suggested to use string split maybe? They are stored like this:

"tracks": [

        {
          "id": 1,
          "name": "Don't Give Up",
          "description": "Epic, cinematic and climactic orchestral trailer track that will lift any action, drama or thriller.",
          "path": "./songs/Don't%20Give%20Up.mp3",
          "cover_art_path": "./images/epic-music.png",
          "license_path":"",
          "keywords":"Armageddon, Battle, Big Ending, Bomb, Break Out, Busy, Chase, Chilled, Covert Ops, Detective, Discovery, Dramatic, Edgy, Electricity, End Of The World, Enemy Approaching, Escape, Exciting, Expedition, Extreme Sports, Fear, Fight scene, Foreboding, Grinding, Hectic, Hollywood Action Adventure Movie, Hyperactive, Interrogation, Investigation, Jailbreak, Lightning, Mean, Motorbike, Nervous, Panic, Patriotic War Movie, Pensive, Pirates, Pressure, Prison, Pulsating, Search, Showdown, Super Hero, Tension, Threat, Thriller, Ticking Bomb, War, War Film, medium tempo",
          "genre":"Funk, Epic Trailer",
          "moods":"Dramatic, Soaring, Hopeful, Inspirational, Tense",
          "tempo":"Moderate, Slow",
          "theme":"Sport, Science Fiction, Landscape"
          
        },
  
        {
          "id": 2,
          "name": "Emily's Song",
          "description": "Starts of with an acoustic nature but develops into a full blend of 
    guitars and sweet percussive elements. A playful uplifting track. Great for furniture 
    adverts or corporate use.",
          "path":"./songs/Emilys%20Song.mp3",
          "cover_art_path":"./images/indie-music.png",
          "license_path": "",
          "keywords": "achievement, advertising, background, beautiful, beauty, business, business music, commercial, company, confident, corporate, corporate background, corporate presentation, corporate presentations music, corporate video, corporation, corporative, happy, high tech, hopeful, innovation, inspiration, inspirational, inspiring, light, lively, marketing, modern, motivate, motivation, motivational, music for presentation, optimistic, piano, positive, presentation, presentation music, progress, promotional, smooth, soft, strings, success, sweet, technology, uplifting, uplifting corporate",
          "genre":"Funk, Pop, Rock",
          "moods":"Uplifting, Upbeat, Playful, Childish",
          "tempo":"Moderate, Fast",
          "theme":"Corporate"
           
        },

I want to be able to not only search the array for keywords, but also to check each box (genre, mood etc. and return all tracks that have a match with each single checkbox.

I almost had it working with this code: initial checkbox code

However, this code will only return tracks that have a single string value. Comma separated values won't return.

I really do appreciate the help I have received from you all so far! @yoduh @tao

Thanks for any help in advanced.




check all checkbox by class name

I´m trying to check and unchex all check boxes with javascript and vue.

const checkAll = () => {
        var array = document.getElementsByClassName("assign_register");
        for(var i = 0; i < array.length; i++){
            if(array[i].type == "checkbox"){
                if(array[i].className == "assign_register"){
                    array[i].checked = true;
                }else if(array[i].checked){
                    array[i].checked = false;
                }
            }
            
        }
    }

This function it´s called from my principal checkbox:

<template v-for="item in valor" :key="item.id">
                    <tr>
                        <td><input type="checkbox" class="assign_register" name="assign_register" style="width: 20px; height: 20px;"></td>

i want to do, that when i click in this check box check all my child checkboxes and if it´s checked and uncheck this check box, unchecked all. i tryed with event.

const checkAll = () => {
        var array = document.getElementsByClassName("assign_register");
        for(var i = 0; i < array.length; i++){
            array[i].addEventListener('change', e => {
                if(e.target.checked === true) {
                    console.log("Checkbox is checked - boolean value: ", e.target.checked)
                }
                if(e.target.checked === false) {
                    console.log("Checkbox is not checked - boolean value: ", e.target.checked)
                }
            });
        }
    }

but not show anything in console and not checked my inputs...

UPDATE

const checkAll = () => {
        var array = document.getElementsByClassName("assign_register");
        for(var i = 0; i < array.length; i++){
            if(array[i].type == "checkbox"){
                if(array[i].className == "assign_register"){
                    array[i].checked = true;
                    if(array[i].checked == true){
                        array[i].checked = false;
                    }
                }
            }
        }
    }

UPDATE 2

<td><input type="checkbox" class="assign_register" name="assign_register" v-model="checked" style="width: 20px; height: 20px;"></td>

const checkAll = () => {
        return {
            checked: true
        }
    }

Thanks for readme and sorry for my bad english




dimanche 16 avril 2023

The problem with android studio jave code com.example.myapplication.mainActivity.onCreate

The problem on i run app it come

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 13080
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.myapplication.mainActivity.onCreate(mainActivity.java:31)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
        at android.app.ActivityThread.access$800(ActivityThread.java:151) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5254) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

my java code is

package com.example.myapplication;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
    @SuppressLint("SuspiciousIndentation")
    public class mainActivity extends AppCompatActivity {
        Button create, login, enter, clear;
        RadioGroup gender;
        RadioButton Male, Female;
        private String msg;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            gender = (RadioGroup) findViewById(R.id.gender);
            Male = (RadioButton) findViewById(R.id.Male);
            Female = (RadioButton) findViewById(R.id.Female);
            create = (Button) findViewById(R.id.Create);
            login = (Button) findViewById(R.id.Login);
            create = findViewById(R.id.Create);
            login = findViewById(R.id.Login);
            gender.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //Get the selected RadioButton
                    int checkId = gender.getCheckedRadioButtonId();
                    // compare selected's Id with individual RadioButtons ID
                    if (checkId == -1) {
                            Message.message(getApplicationContext(), msg + "It's done");
                    } else {
                        findRaqdioButton(checkId);
                    }
                }
            });
            clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    gender.clearCheck();
                }
            });
            gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                    gender = findViewById(checkedId);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        Message.message(getApplicationContext(), gender.getTooltipText().toString());
                    }
                }
            });
        }
        private void findRaqdioButton(int checkId) {
            switch (checkId) {
                case R.id.Male:
                    Message.message(getApplicationContext(), msg + "Male");
                    break;
                case R.id.Female:
                    Message.message(getApplicationContext(), msg + "Female");
                    break;
            }
        }
    }

this xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/b1"
    tools:context=".mainActivity"
    tools:ignore="ExtraText">
    <TextView
        android:id="@+id/title_textview"
        android:text="Create your new account"
        android:textSize="30sp"
        android:textColor="#FFFFFF"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <ImageView
        android:id="@+id/smile_imageview"
        android:src="@mipmap/icons"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/firstname"
        android:layout_width="match_parent"
        android:text="Frist name"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <EditText
        android:id="@+id/Name_edit"
        android:hint="@string/first_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:background="#FAF8F8" />
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/lastname"
        android:layout_width="match_parent"
        android:text="Last name"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <EditText
        android:id="@+id/lastname_edit"
        android:hint="Last name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:background="#FAF8F8" />
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/Email"
        android:layout_width="match_parent"
        android:text="Email"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <EditText
        android:id="@+id/Email_edit"
        android:hint="Enter your Email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:background="#FAF8F8" />
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/Passwoed"
        android:layout_width="match_parent"
        android:text="Password"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <EditText
        android:id="@+id/Password_edit"
        android:hint="Enter your Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:background="#FAF8F8" />
    <RadioGroup
        android:id="@+id/gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <RadioButton
            android:id="@+id/Male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/male"
            android:textColor="#FFFFFF"/>
        <RadioButton
            android:id="@+id/Female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/female"
            android:textColor="#FFFFFF"/>
    </RadioGroup>
   <TableLayout
    android:id="@+id/table1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*">

    <TableRow>
        <Button
            android:id="@+id/enter"
            android:text="choose"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/clear"
            android:text="@string/clear"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
           />
    </TableRow>
   </TableLayout>
    <CheckBox
        android:id="@+id/ch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I agree with Terms of Service"
        android:textStyle="bold"
        android:textColor="#FFFFFF" >
    </CheckBox>
    <CheckBox
        android:id="@+id/ch2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=
            "@string/i_understand_that_if_i_loss_my_password_i_may_lose_my_data_read_more_information_on_help"
        android:textStyle="bold"
        android:textColor="#FFFFFF">
    </CheckBox>
    <TableLayout
        android:id="@+id/t1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="*">
    <TableRow>
    <Button
        android:id="@+id/Create"
        android:text="Create account"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/Login"
        android:text="Log in"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    </TableRow>
        <TableRow>
            <TextView
                android:text="Help"
                android:id="@+id/help"
                android:textColor="#FFFFFF"
                android:padding="5dp"/>
            <TextView
                android:text="How you can use it"
                android:id="@+id/how"
                android:textColor="#FFFFFF"
                android:padding="5dp"/>
        </TableRow>
    </TableLayout>
</LinearLayout>

My app always stopped i can't run




gSheets checkbox value sometimes 'true' or true - what gives?

I have inserted multiple checkboxes in a Google sheet. I then use code to read the value and do things if it is true.

The line in question reads if (variable == true){ then blah blah but sometimes I have to have if (variable == 'true'){ with single quotes for the IF statement to read as TRUE and go do the thing.

There doesn't seem to be a rhyme or reason as to which I have to have. I just have to play with it. I'd really like all my checkboxes (will be 52) to be the same and consistent but currently, that's not the case. I inserted and then did a copy/paste of the boxes but since went back and did insert for all. No change. Has anyone seen this and any suggestions? I don't care if it is with or without the quotes, would just like it consistent.




vendredi 14 avril 2023

Styling Contact Form 7 checkbox when checked

I want to change out the visual of the checked checkbox from blue background to match my theme. I cant seem to get it to show and have tried several options for the checked status. Any help for what selector to use on this would be very helpful.

Selectors that didn't work out.

.wpcf7-list-item > label:after > input[type=checkbox]:checked + span {}
.wpcf7-form .wpcf7-checkbox input[type=checkbox]:checked + span:after {}
span.wpcf7-list-item.first > input[type=checkbox]:checked {}
input[type="checkbox"]:checked {}



how to uncheck few checkboxes from already checked list of checkboxes in javascript/playwright

Im new to Javascript/Playwright, I have a scenario where I want to uncheck few checkboxes( e.g 1,3,5 8 checkboxes ) from already pre-selected checkbox list(10 checkboxes)

I tried to uncheck all checkboxes and check only required, this approach is working fine but would like to know if there is a better way to achieve this in javascript

let role ='checkbox';
    async uncheckAll(role)
    {
      const checkboxes = this.page.getByRole(`${role}`);
      for (const checkbox of await checkboxes.all())
      await checkbox.uncheck();
     }



jeudi 13 avril 2023

How To Change Background Color on CheckBox in Kendo Grid Column

We have a JavaScript/Angular web app that uses many "checkbox" controls on many web page forms.

We also use the Kendo grid (k-grid) in several places with checkbox columns that display the checkmark icon in the column. (Note these are "checkbox" and not "k-checkbox.)

Outside of the k-grid, the checkboxes show with a color background when the box is checked.

Inside the grid, the background color does not change between the checked and unchecked boxes.

Is there some way to get the background in the checkbox to be a given color when the checkbox is in the k-grid and is checked?

I tried setting the "accent-color" for the checkbox, but that didn't change anything when it is in the k-grid.

    input[type='checkbox']:checked {
        vertical-align: sub;
        -webkit-box-shadow: 0px 0px 0px 1px rgba(0,0,0,1);
        -moz-box-shadow: 0px 0px 0px 1px rgba(0,0,0,1);
        box-shadow: 0px 0px 0px 1px rgba(0,0,0,1);
        accent-color: #00ff00;
    }

This is in the .css file. I know the code is used, because I can change the color of the checkbox border and that shows up in the k-grid. But the accent-color does not show up.

Any suggestions?




Excel macOS: Checkbox to hide/unhide rows based on cell value

I'm trying to find a solution to do the following in Excel on macOS: A checkbox should hide/unhide rows based on the cell value in a certain row. In concrete: When clicking the checkbox "closed" I want to hide all rows with the value "closed" in row D. When deselecting the checkbox the rows with the value "closed" in row D should be unhidden.

My coding abilities are quite limited and I searched the web for an answer in vain. I'd appreciate help with this!




mercredi 12 avril 2023

Creating a text string in MS Word using VBA UserForm check boxes

I have created a UserForm which contains several check boxes. My goal is to use the check boxes to select various text strings (specific to a particular check box) that will eventually comprise a paragraph in a standardized report. The user can select only the pertinent check boxes. The selected boxes would then insert text associated the check box into the new paragraph. I am looking for help with the VBA coding as I am a very new VBA user.

I have created the User Form but have not conducted any coding yet. I need a starting point or some example code that I can modify to my specific form. Thanks!




How to exclude click event for CheckBox widget?

I have a container and listener "click" on it. Inside this container I have a checkbox. If I click on the checkbox the listener function of the container is called. Is there a way to not trigger a listener of the container clicking on the checkbox?

There is code which could be executed on qooxdoo playground:

// Create a button
var button1 = new qx.ui.form.CheckBox();
const container = new qx.ui.container.Composite(new qx.ui.layout.Canvas);
container.setDecorator("main");
container.addListener("click", function(){
    console.log("aaaa");
}, this);
container.setWidth(50);
container.setHeight(50);
container.add(button1);

// Document is the application root
var doc = this.getRoot();

// Add button to document at fixed coordinates
doc.add(container,
{
  left : 100,
  top  : 50
});



Change the label when a checkbox is checked

I want to implement a static checkbox (without query/script/function) like this:

enter image description here

By clicking the checkbox box, it should change to that brown color (like the name box), and by clicking again it goes to normal (like price)

my code:

.checkbox-round {
  width: 45px;
  height: 30px;
  /*background-color: white !important;*/
  border-radius: 5px !important;
  /*background-color: white;*/
  vertical-align: middle;
  /*border: 3px solid #ddd;*/
  appearance: none;
  -webkit-appearance: none;
  outline: none;
  cursor: pointer;
}

.checkbox-round:checked {
  background-color: #A97B47 !important;
}
<label>
<input id="filterByName" type="checkbox" checked class="col-md-4 col-sm-6 col-12 button checkbox-round" name="filterByName"  value="name" placeholder="name">
name
</label>



lundi 10 avril 2023

Modify label_attr field in Symfony 6 form builder

I can change the class of my inputs, but not for my labels. How can I change class of my dynamics labels . I can't when I use 'label_attr', because it's a type Closure.

$builder
        ->add('skill', EntityType::class, [
            'class' => Skill::class,
            'query_builder' => function (SkillRepository $r) {
                return $r->createQueryBuilder('i')
                    ->orderBy('i.color', 'ASC');
            },
            'label' => 'Mes compétences',
            // input OK !
            'choice_attr' => function (?Skill $color) {
                return $color ? ['class' => 'color_'.$color->getColor()] : [];
            },
            // ERROR
            'label_attr' => function (?Skill $color) {
                return $color ? ['class' => 'color_'.$color->getColor()] : [];
            },

            'attr' => [
                'class' => 'btn'
            ],
            'choice_label' => 'name',
            
            'multiple' => true,
            'expanded' => true,
        ])

An error has occurred resolving the options of the form "Symfony\Bridge\Doctrine\Form\Type\EntityType": The option "label_attr" with value Closure is expected to be of type "array", but is of type "Closure".

            // ERROR
            'label_attr' => function (?Skill $color) {
                return $color ? ['class' => 'color_'.$color->getColor()] : [];
            },



Shape.OLEFormat and its position in the excel sheet

I wanted to create a simple macro that simply checked if a check box is checked or not and based on that, hide or show the row.

But there are some catches, I cannot link the chackbox to the cell, otherwise another bigger macro generates an error.

I did researcha bit and found that you can do:

sheets(1).shapes("Checkbox 88").topleftcell.row

to get the row of the shape.

So I tried to implement this to my code:

    Dim sh As Shape    
    For Each sh In Sheets(1).Shapes
        If TypeOf sh.OLEFormat.Object Is CheckBox Then
            If sh.OLEFormat.Object.Value = -4146 Then
                'sh.OLEFormat.Object.TopLeftCell.Row.EntireRow.Hidden = True
                MsgBox "Hi"
            End If
        End If
    Next sh

I know that the:

sh.OLEFormat.Object.TopLeftCell.Row.EntireRow.Hidden = True

is wrong, because if I run the macro as I posted it, the macro returns the msgbox "Hi", because the wrong part is commented.

The strange part for me is that if I do:

    Dim aux As Byte
    Dim sh As Shape
    
    aux = Sheets(1).Shapes("Checkbox 88").OLEFormat.Object.TopLeftCell.Row
    'checkbox 88 is one of the checkboxes/shapes in the excel document
    MsgBox aux

it works to get the row...

I am thinking that the error has to do with the OLEFormat.object or something, but my google researches came empty handed.




VBA : Autofiltering with checkbox userform

I would to filter some elements from a column and I am using userform. I used the checkboxes to select values (to be filtered) and used 'if' condition to check for status(true and false). A command box as okey button. But it is filtering only first value. Pls help me with. Sharing the code herewith. I just want the column 2 to be filtered. Possible outcomes are A1 or A2 or A3 or B1 or B2 or B3 or E or L1. I would be happy if I can convert the if output to arrays.

enter image description here




dimanche 9 avril 2023

Cant display selected objects with checkbox in Spring boot application

Hello my friends I have a problem with my Spring boot application, When I select activities in my add_activities layout and hit the submit button it doesn't display the selected items in my activities layout, So here is my controller

@Controller
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    public ActivityController(ActivityService activityService) {
        super();
        this.activityService = activityService;
   }

    @GetMapping("/activities")
    public String listSelectedActivities(Model model){
        List<Activity> selectedActivities = (List<Activity>) model.getAttribute("selectedActivities");
        model.addAttribute("selectedActivities", selectedActivities);
        return "activities";
    }

    @PostMapping("/activities/new")
    public String listActivities(@RequestParam(value = "selectedActivities", required = false) List<Long> selectedActivityIds, Model model){
        List<Activity> selectedActivities = new ArrayList<>();
        if (selectedActivityIds != null) {
            for (Long id : selectedActivityIds) {
                selectedActivities.add(activityService.getActivityById(id));
            }
        }
        model.addAttribute("selectedActivities", selectedActivities);
        return "activities";
    }

    @GetMapping("/activities/new")
    public String createActivityForm(Model model, @RequestParam(name = "place", required = false) String place, @RequestParam(name = "name", required = false) String name){
        List<Activity> activities = activityService.getAllActivities();
        if (place != null && !place.isEmpty()) {
            activities = activities.stream()
                    .filter(a -> a.getPlace().toLowerCase().contains(place.toLowerCase()))
                    .collect(Collectors.toList());
        }

I was expecting to see selected activites in my activities layout not an empty table Thank you for helping me




samedi 8 avril 2023

checkboxes in streamlit not working as intended, changes the boolean value only of last element in list

When I check the checkbox, I want the "checked" value to become True and if I uncheck it, it becomes False. However, when I run my code, when I check a checkbox, the checkbox of the last element of my list checks/unchecks too and only that last element's value changes. I don't know where my problem lies. Here's the code:

import streamlit as st

st.write("# Practice Test Maker!")

if 'question' not in st.session_state:
    st.session_state.question = []

if 'answer' not in st.session_state:
    st.session_state.answer = []

textbox_question = st.text_input("Write a question: ")

textbox_answer = st.text_input("Write the answer of your question: ")

def add_question():
    st.session_state.question.append({"text" : textbox_question, "checked" : False})

def add_answer():
    st.session_state.answer.append(textbox_answer)

def add_on_click():
    add_question()
    add_answer()

def clear_all():
    st.session_state.question = []
    st.session_state.answer = []

enter_button = st.button("Add", on_click = add_on_click)

for i, question in enumerate(st.session_state.question):
    def update_question():
        st.session_state.question[i]['checked'] = not st.session_state.question[i]['checked']
    st.checkbox(question['text'], value = question['checked'], on_change = update_question, key = i)

def remove_question():
    for question in st.session_state.question:
        if question['checked'] == True:
            index = st.session_state.question.index(question)
            st.session_state.question.remove(question)
            del st.session_state.answer[index]
            

remove_button = st.button("Remove", on_click = remove_question)

clear_button = st.button("Clear", on_click = clear_all)

st.write(st.session_state.question)
st.write(st.session_state.answer)

I expect that when I check the checkbox, the st.session_state.question['checked'] changes the boolean value to the element corresponding to the checkbox and not the last one of the element. Probably the important parts of the code that have problem are:

if 'question' not in st.session_state:
    st.session_state.question = []

def add_question():
    st.session_state.question.append({"text" : textbox_question, "checked" : False})

for i, question in enumerate(st.session_state.question):
    def update_question():
        st.session_state.question[i]['checked'] = not st.session_state.question[i]['checked']
    st.checkbox(question['text'], value = question['checked'], on_change = update_question, key = i)

Thank you very much in advance!




vendredi 7 avril 2023

Xaml(WPF) checkbox not reflecting text field content. ivalueprovider conflict

I am creating a form which is having some checkboxes ,
the issue is :
**checkbox** textfield **content** is not appearing on screen while i am setting ivalue provider in webconfig as **LocalFirstValueProvide**, it is showing namespace name , on the other hand the content appears fine with ivalueprovider=**configValueProvide** .

reference images are attaching with query,
Hoping that I can have solution to my problem .

Code: XAML

  <controls:CheckBox  Name="chkStructuredRentalsAvailableatRestructuring" Grid.ColumnSpan="2"  Grid.Row="4" Grid.Column="2"  IsChecked="{Binding Target.RentalTemplate.STRC_RNTL_ALVB_RSTR_IND, Mode=TwoWay}" HorizontalAlignment="Stretch" >
<controls:TextBlock Text="Structured Rentals Available at Restructuring" Name="txtStructuredRentalsAvailableAtRestructuring" TextWrapping="Wrap" HorizontalAlignment="Left" LineHeight="1" Height="Auto" Grid.ColumnSpan="2"/>
</controls:CheckBox>

     

 

View on localfirstvalueprovider Image 1 , View on ConfigValueprovider Image 2




I have an enormous Excel file with hundreds of checkboxes - what can I do?

One of our former colleagues created a big Excel with many items and multiple checkboxes (kind of a checklist), one for each item, even some of them have multiple checkboxes, grouped visually with merging cells, formats etc. but nothing standard.

The issue comes when, now, we need to manipulate that file, we need to delete some tables, because we need to adapt that Excel and share it with other employees that do not need to know the other part of the document, but this would be done dynamically, let's say that the document that we already have it's the base and from that one many will be derived each of one with a slightly different content.

The issue comes when we try to manipulate that file, there is no way to keep that checkboxes working outside that document. We have tried using openpyxl with Python we manage to copy everything except for the checkboxes, we have tried exporting the file to html and managing and editing that file, but the checkboxes are exported as images and obviously not working.

We run out of ideas and we do not know which approach would let us do what we are looking for.

I would like to point that redoing the file would not be an option, we are talking about thousands of items and that would be too time consuming. We know that doing this as an Excel have been a mistake but now it is too late to change it :_)

Thank you for your time and help, really appreciate it.




jeudi 6 avril 2023

I am trying to get checkbox value using flask. i below code

i trying this code these code in html like.

<div class="button-container">
<form action="/get_Exp" method="GET">
    <button onclick="getData()">Get Selected Values</button>
</form>
</div>

and in flask like this

@app.route('/web_page_1')
def web_page_1():
    global table_html
    soup_web = BeautifulSoup(table_html, "html.parser")
    # print(soup_web)
    # get a reference to the table element
    table = soup_web.table

    # loop through each row and add a checkbox input element
    for i, row in enumerate(table.find_all("tr")[1:]):
        if row is not None:
            cell = soup_web.new_tag("td")  # create a new td element
            checkbox = soup_web.new_tag("input",type="checkbox",value=i,
                                id=f'checkbox_{i}') # create a new input element with type="checkbox" and id custom id

            cell.append(checkbox)  # add the checkbox to the new td element
            row.append(cell)  # add the new td element to the end of the row
    global table_html_add_checkbox
    table_html_add_checkbox = str(soup_web)
    return render_template('web_page_1.html', table_html=table_html_add_checkbox)


@app.route('/get_Exp', methods=['GET'])
def get_Exp():
    checkbox_values = request.form.getlist('checkbox')
    print(checkbox_values)
    return "Get Submitted successfully Run!"

but i am getting empty list. i also try this checkbox = soup_web.new_tag("input", type="checkbox", id=f'checkbox_{i}',attrs={'name':'checkbox'})




mercredi 5 avril 2023

Property 'checked' does not exist on type 'EventTarget | (EventTarget & HTMLInputElement)' React

I have parent component SelectBoxGroup and child component SelectBox. I wanted to add the select all option to the SelectBoxGroup. But i got this error;

Property 'checked' does not exist on type 'EventTarget | (EventTarget & HTMLInputElement)'. Property 'checked' does not exist on type 'EventTarget'

.

function SelectBox({
  ...
}: React.HTMLAttributes<HTMLInputElement> & SelectBoxProps) {

  const { register } = useFormContext();
  const { ref, ...rest } = register(name, {
    onChange,
  });

  return (
    <div>
      <input
            type="checkbox"
            checked={isChecked}
            value={value}
            {...props}
            {...rest}
       />
          <label>{label}</label>
    </div>
  );
}
export function SelectBoxGroup({
  ...
}: React.HTMLAttributes<HTMLInputElement> & SelectBoxGroupProps) {
  
  const [checkAllChecked, setCheckAllChecked] = useState(false);

  function handleCheckAll(checked: boolean) {
    setCheckAllChecked(checked);
    onChangeHandler?.(
      options.map(option => ({
        ...option,
        isChecked: checked,
      }))
    );
  }
  return (
    <div>
      {showCheckAll && (
        <SelectBox
          id={'check-all}
          isChecked={checkAllChecked}
          onChange={e => handleCheckAll(e.target.checked)} ////ERROR IS HERE
          label="Check all"
          value="Check all"
          name={""}
        />
      )}
      <div
        role="group"
      >
        {options?.map((option, index) => (
          <SelectBox
            key={option.value}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              onChangeHandler?.(e);
            }}
            name={name}
            label={option.label}
            value={option.value}
          />
        ))}
      </div>
    </div>
  );
}



mardi 4 avril 2023

Reset checkboxes to false after a certain time in day on a sheet in google sheets

I'm new to this but can someone help me write a script to uncheck all checkboxes in a sheet by 7AM in the morning everyday automatically.

I tried the toggle button method but I want the reset done on all the checkboxes automatically.




dimanche 2 avril 2023

checkbox only in that row

when the checkbox is checked, something must only happen in that row. namely column 5 and column 7 are added and the result is in column 5 . and it changes color to white. but this must be just before the row containing the checkbox. how to do this i tried this now ma get an error and don't know why. the bold is the error.

i hope that it can fixed




Changing the checkbox square box from square to rounded with WPF

I have successfully created the rounded corner for the checkbox, right now I have issues connecting the control template with other checkboxes, is there anyway to connect the control template to the checkbox generated from the back end?

the first part is the control template modified to change the square box to rounded box

the second part is the checkbox generated from backend and added to the front end

<Window.Resources>
        <Style x:Key="OptionMarkFocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="14,0,0,0" StrokeDashArray="1 2" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" SnapsToDevicePixels="true" StrokeThickness="1"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="OptionMark.Static.Glyph" Color="#FF212121"/>
        <SolidColorBrush x:Key="OptionMark.MouseOver.Background" Color="#FFF3F9FF"/>
        <SolidColorBrush x:Key="OptionMark.MouseOver.Border" Color="#FF5593FF"/>
        <SolidColorBrush x:Key="OptionMark.MouseOver.Glyph" Color="#FF212121"/>
        <SolidColorBrush x:Key="OptionMark.Pressed.Background" Color="#FFD9ECFF"/>
        <SolidColorBrush x:Key="OptionMark.Pressed.Border" Color="#FF3C77DD"/>
        <SolidColorBrush x:Key="OptionMark.Pressed.Glyph" Color="#FF212121"/>
        <SolidColorBrush x:Key="OptionMark.Disabled.Background" Color="#FFE6E6E6"/>
        <SolidColorBrush x:Key="OptionMark.Disabled.Border" Color="#FFBCBCBC"/>
        <SolidColorBrush x:Key="OptionMark.Disabled.Glyph" Color="#FF707070"/>
        <ControlTemplate x:Key="CheckBoxTemplate1" TargetType="{x:Type CheckBox}">
            <Grid x:Name="templateRoot" Background="Transparent" SnapsToDevicePixels="True">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Border x:Name="checkBoxBorder" Background="{TemplateBinding Background}" CornerRadius="15" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                    <Grid x:Name="markGrid">
                        <Path x:Name="optionMark" Data="F1 M 9.97498,1.22334L 4.6983,9.09834L 4.52164,9.09834L 0,5.19331L 1.27664,3.52165L 4.255,6.08833L 8.33331,1.52588e-005L 9.97498,1.22334 Z " Fill="{StaticResource OptionMark.Static.Glyph}" Margin="1" Opacity="0" Stretch="None"/>
                        <Rectangle x:Name="indeterminateMark" Fill="{StaticResource OptionMark.Static.Glyph}" Margin="2" Opacity="0"/>
                    </Grid>
                </Border>
                <ContentPresenter x:Name="contentPresenter" Grid.Column="1" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="HasContent" Value="true">
                    <Setter Property="FocusVisualStyle" Value="{StaticResource OptionMarkFocusVisual}"/>
                    <Setter Property="Padding" Value="4,-1,0,0"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.MouseOver.Background}"/>
                    <Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.MouseOver.Border}"/>
                    <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.MouseOver.Glyph}"/>
                    <Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.MouseOver.Glyph}"/>
                </Trigger>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Disabled.Background}"/>
                    <Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Disabled.Border}"/>
                    <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.Disabled.Glyph}"/>
                    <Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.Disabled.Glyph}"/>
                </Trigger>
                <Trigger Property="IsPressed" Value="true">
                    <Setter Property="Background" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Pressed.Background}"/>
                    <Setter Property="BorderBrush" TargetName="checkBoxBorder" Value="{StaticResource OptionMark.Pressed.Border}"/>
                    <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource OptionMark.Pressed.Glyph}"/>
                    <Setter Property="Fill" TargetName="indeterminateMark" Value="{StaticResource OptionMark.Pressed.Glyph}"/>
                </Trigger>
                <Trigger Property="IsChecked" Value="true">
                    <Setter Property="Opacity" TargetName="optionMark" Value="1"/>
                    <Setter Property="Opacity" TargetName="indeterminateMark" Value="0"/>
                </Trigger>
                <Trigger Property="IsChecked" Value="{x:Null}">
                    <Setter Property="Opacity" TargetName="optionMark" Value="0"/>
                    <Setter Property="Opacity" TargetName="indeterminateMark" Value="1"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Window.Resources>

----------------------------------------------

 private void GenerateCheckbox()
        {
            CheckBox checkBoxTest = new CheckBox();
            checkBoxTest.Content = "Test";
            grid.Children.Add(checkBoxTest);
        }



how to get value of checkbox from react-hook-form?

I am trying to deliver the value of the checkbox using react-hook-form.

I am delivering the register function of react-hook-form to the props of the component.

But here's a problem.

<CheckboxInput
  type="checkbox"
  id={id}
  value="BAD"
  checked={isChecked[1]}
  onChange={handleCheckbox}
  {...register}
/>

If I deliver the props in the above order, the value value of the checkbox is well shown through the watch function of react-hook-form, but the check mark in the checkbox is not appear.

But,

<CheckboxInput
  {...register}
  type="checkbox"
  id={id}
  value="BAD"
  checked={isChecked[1]}
  onChange={handleCheckbox}
/>

If I pass the props in the above order, the check mark in the checkbox appears well, but if I check the value of the checkbox through the watch function in the react-hook-form, only the value 'false' appears.

How can I make sure that the check marks on the checkbox come out well and the exact value comes out?




samedi 1 avril 2023

copying an existing row which also copies the checkbox with its code

when I press a button my table has to be expanded with 1 row. but also a checkbox has to be copied and its code behind it. How do I do this because it doesn't work this way? the line in bold is the error. enter image description here

Private Sub CommandButton2_Click() Dim lastRow As Long Dim lastColumn As Long Dim chkBox As CheckBox 'Determine the last row in the active worksheet lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row 'Determine the last column you want to expand lastColumn = 7 'Insert a row above the last row Rows(lastRow + 1).Insert 'Copy the formulas from the last row to the new row Range(Cells(lastRow, 1), Cells(lastRow, lastColumn)).Copy Range(Cells(lastRow + 1, 1), Cells(lastRow + 1, lastColumn)) 'Copy the last checkbox with his VBA code Set chkBox = ActiveSheet.CheckBoxes(ActiveSheet.CheckBoxes.Count) chkBox.Copy ActiveSheet.CheckBoxes.Add(chkBox.Left, chkBox.Top + chkBox.Height + 5, chkBox.Width, chkBox.Height).Select ActiveSheet.Paste End Sub




selecting subcategories based on categories in php using ajax error

i have a form where a user can select categories which are checkboxes and when they select category, respective sub categories will display, while adding data this is working fine, now i am editing the data, so i did the following code:

$(document).on('click','.country',function(){
var cat_id = [];
var opt_html = '';
$('input[name="user_category[]"]:checked').each(function(){
    cat_id.push($(this).val());
});
if(cat_id.length > 0){
    jQuery.ajax({
        url: "<?php echo base_url('/homecontroller/getSubcategories');?>",
        data:{'cat_id':cat_id},
        type: "POST",
        success:function(data){
            var response = JSON.parse(data);
    console.log(response);
            if(response.length > 0){
                $.each(response, function(i,l){
                    opt_html += '<div class="form-group col-md-3"><input type="checkbox" class="service_subcat " name="user_subcategory[]"  value="'+l+'"> <label style="font-weight:normal" class="checkbox-inline">'+l+'</label></div>';
                });
                $('#state').html(opt_html);    
                // $('#sub_cat').attr('required','true');
            }
            else{
                $('#state').html('');
                $('#state').removeAttr('required');
            }
        }
    });    
}else{
    $('#state').html('');
    $('#state').removeAttr('required');
}
})

<div class="form-group col-md-12">
                            <label  style="font-size:large">Serviceable Category:</label>
                            <div class="row" >
                            <?php foreach ($listcategory as $liz){ ?>

                              <?php $HiddenProducts2 = explode(',',$val->scategory);?> 
                              <div class="form-group col-md-3">
                              
                            <input type="checkbox" name="user_category[]"  value="<?=$liz->id?>" class="country"  id="country" <?php if(in_array($liz->id, $HiddenProducts2)) { echo 'checked'; }?>>
                            <label style="font-weight:normal" ><?=$liz->name?></label>  
                          </div>
                         <?php } ?>
                            </div>
                          </div>

                          <div class="form-group col-md-12">
                            <label  style="font-size:large">Serviceable Sub Category:</label>
                            <div class="row" id="state">

                            <?php $HiddenProducts3 = explode(',',$val->ssubcategory);?>
                            <?php if($val->ssubcategory){?> 
                              <?php foreach($HiddenProducts3 as $hi){?>
                            <div class="form-group col-md-3"><input type="checkbox"  name="user_subcategory[]"  value="<?=$hi?>" checked> 
                            <label style="font-weight:normal" class="checkbox-inline">
                            <?=$hi?>
                          </label>
                        </div>
                        <?php } } ?>
                        
                            </div>
                          </div>

now the issue is there is some glitch while selecting any category in edit, all the existing subcategories dissapears, can anyone please tell me how to fix this, thanks in advance