vendredi 30 octobre 2020

Creating a checkbox group with React Native

Good Morning! I am wanting to create a selection box where the user has several options of items to choose from and when clicking on a button, it triggers a function that shows all the values that the user chose in the form of an array, json or even arrays ( hard task).

In the React Native documentation, only simple examples of checkboxes using the component are provided and I wanted to go much further than the documentation provides me. What are the possible solutions to this problem? (from a simpler example to an advanced one) and what (s) ways can I explore this problem in order to solve it in the most practical and uncomplicated way?

Definitions and examples of official documentation:
https://reactnative.dev/docs/checkbox/ (CheckBox)
https://reactnative.dev/docs/button/ (Button)

With this problem, another one came up: build an application where the user selects shopping options (items) and a subtotal is displayed in the lower corner of the application as he selects or deselects the items he is going to buy, and there is also an option to reset the subtotal by returning it to the zero value.

From the problem mentioned at the beginning, what are the possible solutions to create this application previously mentioned in a practical and simple way?




Bookmarklet to check elements on a page

I'm trying to create a bookmarklet that would check every tick on a page. I created a similar one before, but failed at the the first hurdle because I think I used getElementById. And this doesn't have an ID...

Checkboxes Image




Easiest way to change checkbox's background color? [duplicate]

I know there is no background-color property for checkboxes and there are some workarounds for custom checkboxes, but I just need to change it to a solid color. Is there an easy way to do so?




How to validate a checkbox group in Angular template-driven forms?

I have a form inside my app. I defined the form inside a page component and the form elements are all a separate component (input, checkbox, radio).

Now I want to validate all this components and this worked for the input fields, single checkbox and group radio buttons but I can't get the group checkbox working.

I have an array object, consisting of multiple objects (options), in these options you will find the value, label, and whether it is selected. The value of the selected option will be added to the value property.

When I do this in the same way as with the group radio buttons, the selected values are not correct, he immediately sets them to true and adds the values as true / false instead of the real value of the checkbox.

Below my code:

Object:

{
    id: "checkboxID",
    value: [],
    options = [
        {
            value: "checkboxvalue1",
            selected: false,
            label: "Checkbox1"
        },
        {
            value: "checkboxvalue2",
            selected: false,
            label: "Checkbox2"
        }
    ],
    disabled: false,
    readonly: false,
    required: false
}

Form component:

<form #myForm="ngForm">
    <checkbox></checkbox>
</form>

<pre></pre>

Group checkbox component

<div *ngFor="let option of options; let i = index">
    <input type="checkbox"
    #formItem="ngModel"
    class="checkbox-input"
    id="-"
    [name]="id"
    [(ngModel)]="value"
    [value]="option.value"
    [checked]="itemIsChecked(option, value)"
    [required]="required"
    [disabled]="disabled"
    [readOnly]="readonly"
    (change)="onChange(option.selected, formItem.value)"
  />

    <label class="label" for="-">
    
  </label>

    
</div>

Used ControlContainer, NgForm for controlling the forms. See Stackblitz for more

The checkbox option values are coming from the options array, and the model for the checkbox is the value property which is an array (possible to check multiple boxes).

The value of the group radio is updating well in the myForm.value, but the checkbox doesn't work well. Both options are checked on load, which is not correct and when I make an change the value appears as true / false instead of the real value.

When I remove the ="ngModel" and [(ngModel)]="value" inside the template, the checkbox works well (see stackblitz Group checkbox 1) but this time I can't do the validation.

How to solve this issue and make validation for the group checkbox inside a template-driven possible?

Stackblitz




uncheck material checkbox after closing modal

In an application I've a checkbox that filters a table. In that table you have a button to return a product. After closing the confirmation modal I want to uncheck the checkbox.

The ngModelChange is working well if I check/uncheck box manually.

I've tried (ngModelChange), (change), [checked]

angular version:8

HTML:

<mat-checkbox (ngModelChange)="changeSeeOnlyInUse()" [(ngModel)]="seeOnlyInUse">Show Only Products in use.</mat-checkbox>
<div class="table-container"> 
    <table>
        ...
    </table>
</div>

TS:

ngOnInit() {this.seeOnlyInUse=false;}

public returnProduct(registration) {
    //do some stuff and open modal
    modalRef.afterClosed().subscribe (response => {
        // do some stuff
        this.seeOnlyInUse = false; //<- now I want to uncheck box})
}

public changeSeeOnlyInUse(){
    this.seeOnlyProductsInUse = !this.seeOnlyProductsInUse;
    // do some stuff }  
    




How do we set dynamic checkboxes to checked based on the value from the database in angular reactive forms?

I am new to reactive forms and struggling to set the value of the checkboxes to true dynamically. Here's an example: I am getting the pre-selected fruit values for a particular user from the db and those fruits need to be checked when the user loads the page.

I am using the below html code:

<ng-container>
<div class="form-check form-check-inline" style="display: block;" *ngFor="let control of fruitsArray.controls; let i = index;">
  <input *ngIf="i<11" class="form-check-input" [formControl]="control" type="checkbox" id="inlineCheckbox" [checked]="fruitsCheck[i].checked">
  <label *ngIf="i<11" class="form-check-label" for="inlineCheckbox"> <br /></label>
</div>

fruitsCheck is an array of object which contains the label and the checked value as below:

fruitsCheck : Array<{label: string, checked: boolean}> = [];

fruitsCheck would hold values such as:

0: {label: "Apple", checked: true},
1: {label: "Orange", checked: false},
2: {label: "Pineapple", checked: true},
3: {label: "Kiwi", checked: false}

Using the above code, I am able to just set the appropriate checboxes as checked, but however upon checking the value of the specific checkbox control, it is still shown as false.I would like the checkbox not only to be checked, but also the control's value to be set to true.

I read about patchValue but unsure of how to use it to set the value to dynamic checkboxes. Thanks in advance for any help!




check Box Item Table Widget Item

i need just i check the checkbox it run the fun check_color_green directly without refresh ??help

#chkBoxItem = QTableWidgetItem()

#chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)

#chkBoxItem.setCheckState(Qt.Checked)

#self.tableWidget_4.setItem(row_number, column_number, chkBoxItem)

#self.check_color_green(row_number)




Unable to uncheck the checkbox

I am making a react application where checkboxes for jobtitles are populated from the dynamic data from api and it will be exactly like given snippet.

const departments = 
[
   {
      "sectorId":29,
      "sectorName":"Building Materials Mfg. & Distribution",
      "departments":[
         {
            "deptName":"Manufacturing",
            "jobTitles":[
               {
                  "453":false,
                  "JobTitleID":453,
                  "DepartmentID":101,
                  "JobName":"Consultant",
                  "Deleted":false,
                  "SortOrder":5
               },
               {
                  "323":true,
                  "JobTitleID":323,
                  "DepartmentID":101,
                  "JobName":"Quality Control",
                  "Deleted":false,
                  "SortOrder":1
               }
            ]
         },
         {
            "deptName":"Warehouse",
            "jobTitles":[
               {
                  "326":false,
                  "JobTitleID":326,
                  "DepartmentID":98,
                  "JobName":"Warehouse Supervisor",
                  "Deleted":false,
                  "SortOrder":1
               }
            ]
         },
         {
            "deptName":"Administration",
            "jobTitles":[
               {
                  "384":true,
                  "JobTitleID":384,
                  "DepartmentID":115,
                  "JobName":"Controller",
                  "Deleted":false,
                  "SortOrder":1
               }
            ]
         }
      ]
   }
]

  const handleJobTitle = (event, job) => {
    const { checked } = event;
    if (checked) {
      document.getElementById(job.JobTitleID).checked = true;
    } else {
      document.getElementById(job.JobTitleID).checked = false;
    }
    console.log(document.getElementById(job.JobTitleID));
  };


const App = () => (
 <div> {departments && departments.map((levelOne, i) => (
            <div
              key={i}
            >
              <p> {levelOne.sectorName} </p>
              {levelOne.departments.map((levelTwo, j) => (
                <div key={j}>
                  <p >
                    {" "}
                    {levelTwo.deptName}{" "}
                  </p>
                  {levelTwo.jobTitles.map((job, l) => (
                    <div
                      key={l}
                    >
                      <input type="checkbox" id={job.JobTitleID} onChange={(e) => {handleJobTitle(e, job)}} name={job.JobName} checked={job[job.JobTitleID]}/>
                      <span>{job.JobName}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          ))} </div>
)

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Here the jobTitles data will be like,

"jobTitles":[
   {
      "453":false,
      "JobTitleID":453,
      "DepartmentID":101,
      "JobName":"Consultant",
      "Deleted":false,
      "SortOrder":5
   },
   {
      "323":true,
      "JobTitleID":323,
      "DepartmentID":101,
      "JobName":"Quality Control",
      "Deleted":false,
      "SortOrder":1
   }
]

And I make the checkbox checked based on the value of "453":false like,

<input type="checkbox" ...... checked={job[job.JobTitleID]}/>

And the checkboxes are checked here but when I try to uncheck the checkbox in onChange handler like,

const handleJobTitle = (event, job) => { 
 document.getElementById(job.JobTitleID).checked = false;
}

The checkboxes are not unchecked.. If I console/inspect the input element then the checked atribute is not removed.

Kindly go through the above given snippet and provide me a solution of unchecking the checked checkbox.

Additional Info: It is also not possible to check the checkbox with is in unchecked state.. So in common I couldn't make any change to checkbox..

Big thanks in advance.




jeudi 29 octobre 2020

Display selections in CheckBox ComboBox

I have a comboBox which get populated by an XML. It lists every item as checkbox item I would like the ComboBox to display the checked selections, like the image below

enter image description here

This is my XML

<?xml version="1.0" encoding="utf-8" ?>
<ComboBox>
  <Customer name="John">
    <Data>
      <System>Linux</System>
    </Data>
  </Customer>
  <Customer name="Fernando">
    <Data>
      <System>Microsoft</System>
      <System>Mac</System>
    </Data>
  </Customer>
</ComboBox>

This is my XAML

<ComboBox x:Name="customer_comboBox" HorizontalAlignment="Left" Margin="83,259,0,0" VerticalAlignment="Top" Width="172" SelectionChanged="customer_comboBox_SelectionChanged" >
     <ComboBox.ItemTemplate>
         <DataTemplate>
                <CheckBox Content="{Binding}"/>
        </DataTemplate>
     </ComboBox.ItemTemplate>
</ComboBox>

And this is the code that is used to populate the customer_comboBox

 XmlDocument doc = new XmlDocument();
 doc.Load(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\comboBox.xml");
 XmlNodeList customerList = doc.SelectNodes("ComboBox/Customer");
 List<string> customers = new List<string>();

 foreach (XmlNode node in customerList)
 {
     customers.Add(node.InnerText);
 }
 customer_comboBox.ItemsSource = customers;



WPF - Issue to preserve binding while styling a checkbox with a template

I've an issue while styling a checkbox. I was inspired by the original checkbox style.

The problem is, I can't find a way to apply the original binding (into the property IsSelected). When I remove the style, the binding works. What should I add inside the Content Presenter to preserve the checkbox binding ? Thanks for help.

<DataGridCheckBoxColumn Binding="{Binding IsSelected}" ElementStyle="{StaticResource DataGridCheckBoxStyle}" MinWidth="6">
<Style x:Key="DataGridCheckBoxStyle" TargetType="{x:Type CheckBox}">
    <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="CheckBox">
                    <BulletDecorator Background="Transparent">
                        <BulletDecorator.Bullet>
                            <Border   x:Name="Border"  
                                      Width="13" 
                                      Height="13" 
                                      CornerRadius="0" 
                                      Background="White"
                                      BorderThickness="1"
                                      BorderBrush="{StaticResource Blue}">
                                <Path Width="8" Height="8" 
                                        x:Name="CheckMark"
                                        SnapsToDevicePixels="False" 
                                        Stroke="White"
                                        StrokeThickness="2"
                                        Data="M 0 3.5 L 3.5 7 M 3.5 7 L 8 0" />
                            </Border>
                        </BulletDecorator.Bullet>
                            <ContentPresenter Margin="4,0,0,0"
                                            VerticalAlignment="Center"
                                            HorizontalAlignment="Left"
                                            RecognizesAccessKey="True"/>
                     </BulletDecorator>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="false">
                            <Setter TargetName="CheckMark" Property="Visibility" Value="Collapsed"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter TargetName="Border" Property="Background" Value="{StaticResource Blue}" />
                        </Trigger>
                        <Trigger Property="IsChecked" Value="{x:Null}">
                            <Setter TargetName="CheckMark" Property="Data" Value="M 0 7 L 7 0" />
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <!--<Setter TargetName="Border" Property="Background" Value="{StaticResource DarkGray}" />-->
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter TargetName="Border" Property="Background" Value="White" />
                            <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource LightGray}" />
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

    </Style>



Summary of Selected Radio Buttons

I am interested in producing a summary of the selected radio buttons and checkboxes on an HTML form. I've figured out how to produce a summary of the input for text fields, but not radio buttons or checkboxes. (Sorry this is very basic, I'm very new to JavaScript.) I tried approaching the radio buttons in a similar way to how I produced the order summary for the text fields, but that didn't work.

function calcOrder() {
    var firstName = document.getElementById ("firstName").value; 
    var lastName = document.getElementById ("lastName").value; 
    var userName = firstName + " " + lastName;
    var phone = document.getElementById ("phone").value;
    var email = document.getElementById ("email").value;
    
    
    document.getElementById ("orderConfirm").innerHTML = "<h4>Order Summary:</h4>";
    document.getElementById ("orderConfirm").innerHTML += "<p>" + userName + "<br>" + phone + "<br>" + email + "</p>";

 
}  
<form>
    <table border="0">
        <tr> <!--First Name-->
            <td class="lable_col">First Name:</td>
            <td class="input_col"><input name="firstName" id="firstName" type="text" placeholder="John" onblur="validateFirstName();"></td>
            <td class="feedback_col"><span id="firstNamePrompt">&nbsp;</span></td>
        </tr>
        <tr> <!--Last Name-->
            <td class="lable_col">Last Name:</td>
            <td class="input_col"><input name="lastName" id="lastName" type="text" placeholder="Smith" onblur="validateLastName();"></td>
            <td class="feedback_col"><span id="lastNamePrompt">&nbsp;</span></td>
        </tr>
        <tr> <!--Phone Number-->
            <td class="lable_col">Phone:</td>
            <td class="input_col"><input name="phone" id="phone" type="text" placeholder="xxx-xxx-xxxx" onblur="validatePhone();"></td>
            <td class="feedback_col"><span id="phonePrompt">&nbsp;</span></td>
        </tr>
        <tr> <!--Email-->
            <td class="lable_col">Email:</td>
            <td class="input_col"><input name="email" id="email" type="text" placeholder="johnsmith@gmail.com" onblur="validateEmail();"></td>
            <td class="feedback_col"><span id="emailPrompt">&nbsp;</span></td>
        </tr>
    </table>
            
    <h3>Order</h3>
    Burrito or Bowl? <br><input type="radio" name="burritoorbowl" value="Burrito" checked>Burrito<br>
    <input type="radio" name="burritoorbowl" value="Bowl">Bowl<br>
    Rice <br><input type="radio" name="rice" value="White" checked>White<br>
    <input type="radio" name="rice" value="Brown">Brown<br>
    <input type="radio" name="rice" value="None">None<br>
    Beans <br><input type="radio" name="beans" value="Black" checked>Black<br>
    <input type="radio" name="beans" value="Pinto">Pinto<br>
    <input type="radio" name="beans" value="None">None<br>
    Protein <br><input type="radio" name="protein" value="Steak" checked>Steak<br>
    <input type="radio" name="protein" value="Pork">Pork<br>
    <input type="radio" name="protein" value="Chickn">Chicken<br>
    <input type="radio" name="protein" value="TofuChorizo">Tofu Churizo<br>
    <input type="radio" name="protein" value="None">None<br>
    Toppings <br><input type="checkbox" name="toppings" value="VeggieFajitas">Veggie Fajitas<br>
    <input type="checkbox" name="toppings" value="Lettuce">Lettuce<br>
    <input type="checkbox" name="toppings" value="Cheese">Cheese<br>
    <input type="checkbox" name="toppings" value="SourCream">Sour Cream<br>
    <input type="checkbox" name="toppings" value="Corn">Corn<br>
    <input type="checkbox" name="toppings" value="Tomatoes">Tomatoes<br>
    <input type="checkbox" name="toppings" value="Salsa">Salsa<br>
    <input type="checkbox" name="toppings" value="Guacamole">Guacamole<br>
            
    <h3>Additional Instructions</h3>
    <input type="text" name="additional" id="additional" inblur="validateAdditional();" placeholder="Your message here...">
    <br>
    <span class="button" onclick="calcOrder();">Place Order</span>
    <br>
    <span id="orderConfirm">&nbsp;</span>
</form>



how to display checkbox multi-select in django

if I select all checkbox then my checkbox display only one thing
i want display multi select checkbox in django. what is problem in my code?

in html

<form action="" method="GET">
        <label style="color: gray;" >&nbsp; 확장자 -</label> 
            
    </form>

in views.py

if request.method == 'GET':
        png = {'name' : '.png'}
        jpg = {'name' : '.jpg'}
        gif = {'name' : '.gif'}
        
        file_extention = [png, jpg, gif]
        
        context = {}
        context['file_extention'] = file_extention

        extention_name = request.GET.get('extention_name',None)
        
        
        context['extention_name'] = extention_name
        
        return render(request, 'home/index.html',context)```



How to decrease the padding between my checkbox and text next to it in xaml?

I'm writing code for a task pane with limited real estate. There is a select all checkbox and other checkboxes on the left side that are invisible until mouseover. There is too much space between the checkbox and the text and I'd like to reduce it. Have tried horizontal alignment, margin, padding, manually setting the width. What else is there to try?

            <DataGridTemplateColumn>
                <DataGridTemplateColumn.HeaderTemplate>
                    <DataTemplate>
                        <Border x:Name="cbkBorder" Background="Transparent" HorizontalAlignment="Left" Margin="-1" Width="15">
                        <CheckBox IsChecked="{Binding DataContext.SelectAll, Mode=TwoWay,
                                   RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
                                <CheckBox.Style>
                                    <Style TargetType="CheckBox">
                                        <Setter Property="Visibility" Value="Hidden"/>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding ElementName=cbkBorder, Path=IsMouseOver}" Value="True">
                                                <Setter Property="Visibility" Value="Visible"/>
                                                <Setter Property="Cursor" Value="Hand" />
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </CheckBox.Style>
                            </CheckBox>
                        </Border>
                    </DataTemplate>
                </DataGridTemplateColumn.HeaderTemplate>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox Name="cbkSelect" HorizontalAlignment="Left" Margin="-1" Width="15" Padding="0"
                           IsChecked="{Binding Path=IsSelectedForOrder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                            <CheckBox.Style>
                                <Style TargetType="{x:Type CheckBox}">
                                    <Setter Property="Visibility" Value="Hidden"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" Value="True">
                                            <Setter Property="Visibility" Value="Visible"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </CheckBox.Style>
                        </CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>



How to fill color inside of checkbox in flutter?

Here is what I am using for checkbox in flutter. But I can set only border color for unchecked state, not method found for fill color inside of the checkbox. Please help me with this.

Theme(
    data: ThemeData(unselectedWidgetColor: Colors.white),
    child: Checkbox(
        checkColor: Colors.blue,
        activeColor: Colors.white,
        value: rememberMe,
        onChanged: (value) {
            setState(() {
                rememberMe = value;
            });
        },
    ),
)



How can we disable antd table's checkboxes based on conditions?

For example there are 10 records I want to enable only first two records reamining all records should be disabled automatically? Simple antd table please check this below codeSandbox link

I wanted to disable only 4 rows the remaining all rows should be enabled and the numbers in getCheckboxProps this method would be coming from props Can anyone help me in right direction?




CheckboxInput with Edit table in DT R Shiny

I tried to combine editing table by adding, deleting row in DT table with checkboxInput(). It is not quite correct.

If I didn't add editing feature, it returned correct, but if I added editing feature,it didn't response after I added another row. I got stuck for a while, I will appreciate any help from you guys

library(shiny)
library(shinyjs)
library(DT)

# Tab 2 UI code.
tab2UI <- function(id) {
  ns <- NS(id)
  tabPanel(
    "Tab 2",
    fluidRow(
      #uiOutput(ns('cars')),
      h2('The mtcars data'),
      DT::dataTableOutput(ns('mytable2')),
      uiOutput(ns("edit_1")),
      h2("Selected"),
      tableOutput(ns("checked"))
    )
  )
}


# Tab 2 server code.
tab2Server <- function(input, output, session) {
  ns <- session$ns
  
  # Helper function for making checkboxes.
  shinyInput = function(FUN, len, id, ...) {
    inputs = character(len)
    for (i in seq_len(len)) {
      inputs[i] = as.character(FUN(ns(paste0(id, i)), label = NULL, ...))
    }
    inputs
  }
  

  # Update table records with selection.
  subsetData <- reactive({
    sel <- mtcars[1:5,]
     
  })
  
  values <- reactiveValues(df = NULL)
  
  observe({
    values$df <- subsetData()
   })
  
 
  
  # Datatable with checkboxes.
  output$mytable2 <- DT::renderDataTable(
    datatable(
      data.frame(values$df,Favorite=shinyInput(checkboxInput,nrow(values$df), "cbox_", width = 10)),
      editable = TRUE,
      selection = 'single', 
      escape = FALSE,
      options = list(
        paging = FALSE,
        preDrawCallback = JS('function() {Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() {Shiny.bindAll(this.api().table().node()); }')
      )
    )
  )
  
  
  
  observeEvent(input$add.row_1,{
    
   # print(paste0("Row selected",input$mytable2_rows_selected))
    
    if (!is.null(input$mytable2_rows_selected)) {
      
      td <- values$df
      
      
      tid_n = as.numeric(input$mytable2_rows_selected)
      tid = as.numeric(input$mytable2_rows_selected) + 1
      
      
      if(tid_n == nrow(td)){
        td<- rbind(data.frame(td[1:tid_n, ]),
                   data.frame(td[tid_n, ]))
      }else{
        td<- rbind(data.frame(td[1:tid_n, ]),
                   data.frame(td[tid_n, ]),
                   data.frame(td[tid: nrow(td), ]))
      }
       
 
      td <- data.frame(td)
      print(td)
      values$df <- td
      
    }
  })
  

  output$edit_1 <- renderUI({
    tagList(
      actionButton(inputId = ns("add.row_1"), label = "Add Row", icon = icon("plus"),class = "example-css-selector",style = "background-color:gray; border-color:gray;color:white;height:31px;"),
      actionButton(inputId = ns("delete.row_1"), label = "Delete Row", icon = icon("minus"),class = "example-css-selector",style = "background-color:gray; border-color:gray;color:white;height:31px;"),br(),br()
    )
  })
  
  # Helper function for reading checkbox.
  shinyValue = function(id, len) {
    values <- unlist(lapply(seq_len(len), function(i) {
      value = input[[paste0(id, i)]]
      if (is.null(value)) NA else value
    }))
    return(values)
  }
  
  # Output read checkboxes.
  observe({

    len <- nrow(values$df)
  
    output$checked <- renderTable({
      data.frame(selected=shinyValue("cbox_", len))
    })
  })
  

}

# Define UI for application.
ui <- fluidPage(
  useShinyjs(),
  navbarPage(
    'Title',
    tab2UI("tab2")
  )
)

# Define server.
server <- function(input, output, session) {

  # Call tab2 server code.
  callModule(tab2Server, "tab2")
}

# Run the application
shinyApp(ui = ui, server = server)



How to make the checkbox checked default?

I am making a react app where I need to populate dynamic checkboxes from the data.

  const sectors = [
    {
      SectorID: 5,
      Name: "Wood Truss/Panel/Building Components"
    },
    {
      SectorID: 33,
      Name: "LBM Retail/Pro Contractor"
    },
    {
      SectorID: 24,
      Name: "Light Gauge Steel Truss/Panel"
    }
  ];

Then I do have a list of selected checkboxes here,

  const selectedSectors = [
    {
      SectorID: 5
    },
    {
      SectorID: 24
    }
  ];

So here using SectorID, we can find a match.

Expected result: Need to make the selected sector to be checked on load.

Solution I tried:

  const [checkedItems, setCheckedItems] = useState({});

  React.useEffect(() => {
    const newData = sectors.map((sector) => {
      return selectedSectors.map((selected) => {
        if (selected.SectorId === sector.SectorId) {
          setCheckedItems((prev) => {
            const checkedItems = {
              ...prev.checkedItems,
              [sector.Name]: true
            };
            return { ...prev, checkedItems };
          });
        }
      });
    });
  }, []);

The above one doesn't make the selected sectors checked and I think I am doing something wrong here.

Populating checkboxes like:

      {sectors &&
        sectors.map((sector, index) => (
          <React.Fragment key={index}>
            <label className="block mr-4">
              <input
                className="mx-2 leading-tight"
                name={sector.Name}
                checked={checkedItems[sector.Name]}
                onChange={(e) => handleInputChange(e, sector)}
                type="checkbox"
              />
              <span className="text-sm">{sector.Name}</span>
            </label>
          </React.Fragment>
        ))}

Codesandbox:

Edit React Functional Component (forked)

Requirement: Please help me to make the checkboxes get checked by default on comparing with selectedSectors..




mercredi 28 octobre 2020

Trying to convert list group to checkboxes

I'm Building a shopping App . I'm trying to convert list group to get multiple inputs and filter them .

app.component.html

<div >
  <div class="list-group">
    <a class="list-group-item list-group-item-action"
    [class.active]="!category"
    routerLink="/products"
    >All Categories</a>
    
    <a class="list-group-item list-group-item-action"
    routerLink="/products" 
    *ngFor="let c of categories$ | async"
    [queryParams]="{ category: c.key }" 
    [class.active]="category === c.key"></a>
  </div>
</div><br>



CheckboxTreeview() - scale size of checkboxes, change colors

CheckboxTreeview() for Python's Tkinter is a remarkable class. Unfortunately on HDPI monitors (like my 4K TV) the checkbox can be hard to read:

existing checkboxes

How can the checkboxes be easier to discern on HDPI monitors? Can colors be changed?




Changing order of flexbox when input is checked?

I was was wondering if it's possible to change the order of my flexbox if the checkbox gets checked. I can get it to work if I don't use the form or div wrapper. Is it possibe to order the whole form container to order 4 once checkbox is checked? I am currently targeting -

input:checked+label, input:checked {
  order: 4;
}

How can I add form element to the css selectors?

    <div class="list__container">
      <form>
        <input id="item1" type="checkbox" />
        <label for="item1">Create a to-do list</label>
      </form>
     /* Or DIV*/
      <div>
        <input id="item2" type="checkbox" />
        <label for="item2">Prepare for <strong>the test</strong></label>
      </div>
      
      <h1 className="todo"></h1>
      <h1 className="completed"></h1>

    </div>
.list__container {
  display: flex;
  flex-direction: column;
}

.todo {
  order: 1;
}

.done {
  order: 2;
}

input:checked+label, input:checked {
  order: 4;
}

input:not(checked)+label, input:not(checked) {
  order: 2
}

Thanks!




How to display data on top of others instead of simultaneously with React checkboxes?

I am new to React and trying to build a TODO app. What I'm trying to achieve is: 1) after each checkbox's click, I would like to show its associated data on top of what is already displayed rather than simultaneously (i.e checkbox 2 displaying its data instead of replacing another checkbox's data).

I guess it has something to do with the way I'm storing and filtering my items but I'm struggling to find the way out.

Also, and for it to be perfect, 2) I'd like to remove the behaviour that checking/unchecking my checkboxes is performing the same action (i.e when all checkboxes are clicked, unticking one will call again its associated function rather than doing nothing and keep its data displayed on the screen) and 3) allowing the fact that some checkboxes cannot be both ticked at the same time (the Clear and Show all checkboxes for example).

Thanks in advance

CODE

import React from "react";
import ReactDOM from "react-dom";
import Items from "./Items.js"

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    Data: Items,
    storeData: Items,
    }
  }

  myFunction = (category) => {
    const filterData = this.state.Data.filter(elem => elem.category === category);
    this.setState({storeData: filterData});
  }

  myFunctionAll = () => {
    this.setState({storeData: Items});
  }

  render() {
    console.log(this.state.storeData)
    console.log(this.state.Data)
    return(
      <div>
        <label>
          Filter A
          <input type="checkbox" onClick={() => this.myFunction("A")} />
        </label>
        <label>
          Filter B
          <input type="checkbox" onClick={() => this.myFunction("B")} />
        </label>
        <label>
          Filter C
          <input type="checkbox" onClick={() => this.myFunction("C")} />
        </label>
        <label>
          Clear All
          <input type="checkbox" onClick={() => this.myFunction(null)} />
        </label>
        <label>
          Show All
          <input type="checkbox" onClick={() => this.myFunctionAll()} />
        </label>

        <br />
        {this.state.storeData.map(elem => (
          <li key={elem.id}>
            Id: {elem.id} Category: {elem.category}
          </li>))}
      </div>
    )
  }
}

ReactDOM.render(<Checkbox />, document.getElementById("root"))

DATA

const Items = [
    {
      "id": 1,
      "name": "First item",
      "category": "A"
    },
    {
      "id": 2,
      "name": "Second item",
      "category": "B"
    },
    {
      "id": 3,
      "name": "Third item",
      "category": "C"
    },
    {
      "id": 4,
      "name": "Fourth item",
      "category": "A"
    },
  ]
  
  export default Items



Is there a way to "freeze" the state of a checkbox in PyQt5?

I want a checkbox being automatically checked when I check another checkbox and not being uncheckable until I uncheck the other checkbox. I thought "freezing" would be an easy way to do this but I'm also interested in other solutions. An example program try this out would be:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QCheckBox

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(500, 50, 500, 500)
        self.box1 = QCheckBox('Box1', self)
        self.box1.setGeometry(250, 10, 50, 50)
        self.box1.stateChanged.connect(self.dothething)
        self.box2 = QCheckBox('Box2', self)
        self.box2.setGeometry(10, 10, 50, 50)
        self.show()
    
    def dothething(self):
        if not self.box2.isChecked():
            self.box2.toggle()
            self.box2.freeze()
        else: 
            self.box2.unfreeze()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = Window()
    sys.exit(app.exec_())

Obviously the .freeze() and .unfreeze() functions don't exist.

I also tried .setCheckable but with this the CheckBox can only be frozen in an unchecked state so that's the opposite of what I want.




Handle nested object useState with multiple checkboxes React hooks

I've got useState object like this

export const dataService = () => {
const [data,setData] = useState([
{
dataName:'name1',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/41gfdg-rewr-432fdsg'
},
{
dataName:'name2',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/gfd6765-hf34-hgf34'
},
{
dataName:'name3',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/hgfhbv-dsad-jy675j'
},
{
dataName:'name4',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/lokg12-jg9d-hgf'
}])

 const handleChange = (e) => {
        setData(prevState => ({
            ...prevState,
              [e.target.name]: e.target.checked
        }))
    }

return(
<div>
 {data.map((item,index) => {
                            return(
                                <Grid>
                                    <Checkbox
                                        name={item.dataName}
                                        onChange={handleChange}
                                        checked={item.dataVisible}
                                        />
                                    <label>{item}</label>
                                </Grid>
                            )
                        })}
<div>
)

}

I want to update dataVisible in time when I click on specify checkbox. But when I click then this data struct don't update this field but add new field with this target checked. Have any idea to solve this problem. I cant invent direction to this fields...




Bootstrap's v4.5 checkbox cannot be aligned Horizontally or Vertically when next to an input

just like the title says: Bootstrap's checkbox cannot be aligned Horizontally or Vertically when next to an input.

Problem Rendering:

enter image description here

I have tried the following with no good results that code Snippet.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
    
<div class="container mt-5">
<form>
        <div class="form-group row">
            <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
            <div class="col-sm-4">
                <input type="email" class="form-control" id="inputEmail3">
            </div>
            <div class="col-sm-2">Checkbox</div>
            <div class="col-sm-4">
                <div class="form-check orm-check-inline">
                    <input class="form-check-input" type="checkbox" id="gridCheck1">
                    <label class="form-check-label" for="gridCheck1">
                        Example checkbox
                    </label>
                </div>
            </div>
        </div>
</form>
</div>



Angular Firebase Checkbox Using For Loop

I'm Trying to get data from firebase to a checkbox using for loop , I've tried using dropdown list box but i need them in checkbox

DROPDOWN Method

<div class="form-group">
    <label for="size">Size</label>
    <select #size="ngModel" [(ngModel)]="product['size']" name="size" id="size" class="form-control" required>
      <option value=""></option>
      <option *ngFor="let s of size$ | async" [value]="s.key"></option>
    </select>
    <div class="alert alert-danger" *ngIf="size.touched && size.invalid">
      You have to select size.
    </div>
  </div>



How to display data on top of others instead of simultaneously with React checkboxes?

I am new to React and trying to build a TODO app. What I'm trying to achieve is: 1) after each checkbox's click, I would like to show its associated data on top of what is already displayed rather than simultaneously (i.e checkbox 2 displaying its data instead of replacing another checkbox's data).

I guess it has something to do with the way I'm storing and filtering my items but I'm struggling to find the way out.

Also, and for it to be perfect, 2) I'd like to remove the behaviour that checking/unchecking my checkboxes is performing the same action (i.e when all checkboxes are clicked, unticking one will call again its associated function rather than doing nothing and keep its data displayed on the screen) and 3) allowing the fact that some checkboxes cannot be both ticked at the same time (the Clear and Show all checkboxes for example).

Apologies if the question has been asked before but did not find anything suiting my need

Thanks in advance

CODE

import React from "react";
import ReactDOM from "react-dom";
import Items from "./Items.js"

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    Data: Items,
    storeData: Items,
    }
  }

  myFunction = (category) => {
    const filterData = this.state.Data.filter(elem => elem.category === category);
    this.setState({storeData: filterData});
  }

  myFunctionAll = () => {
    this.setState({storeData: Items});
  }

  render() {
    console.log(this.state.storeData)
    console.log(this.state.Data)
    return(
      <div>
        <label>
          Filter A
          <input type="checkbox" onClick={() => this.myFunction("A")} />
        </label>
        <label>
          Filter B
          <input type="checkbox" onClick={() => this.myFunction("B")} />
        </label>
        <label>
          Filter C
          <input type="checkbox" onClick={() => this.myFunction("C")} />
        </label>
        <label>
          Clear All
          <input type="checkbox" onClick={() => this.myFunction(null)} />
        </label>
        <label>
          Show All
          <input type="checkbox" onClick={() => this.myFunctionAll()} />
        </label>

        <br />
        {this.state.storeData.map(elem => (
          <li key={elem.id}>
            Id: {elem.id} Category: {elem.category}
          </li>))}
      </div>
    )
  }
}

ReactDOM.render(<Checkbox />, document.getElementById("root"))

DATA

const Items = [
    {
      "id": 1,
      "name": "First item",
      "category": "A"
    },
    {
      "id": 2,
      "name": "Second item",
      "category": "B"
    },
    {
      "id": 3,
      "name": "Third item",
      "category": "C"
    },
    {
      "id": 4,
      "name": "Fourth item",
      "category": "A"
    },
  ]
  
  export default Items



can anyone help me with the below Css format. is it possible to have single checkbox for multiple values to the below design?

I have tried searching in the internet but couldn't find appropriate solution to this, Can anyone help me out




Sorting with select tag and checkbox staying checked

I have two questions:

1) I would like to sort an array of products with select tag using controller. This is the controller:

public async Task<ViewResult> Index(string sortOrder,List<int> checkedTypes)
    {
        var products = from p in _db.Products
        select p;
        ViewData["PriceDesc"] = string.IsNullOrEmpty(sortOrder) ? "priceDesc" : "";
        ViewData["NameDesc"] = string.IsNullOrEmpty(sortOrder) ? "nameDesc" : "";

        switch(sortOrder)
        {
            case "priceDesc":
            products = products.OrderByDescending(p => p.Price);
            break;
            case "nameDesc":
            products = products.OrderByDescending(p => p.Name);
            break;
            default:
            products = products.OrderBy(p => p.Name);
            break;
        }

        return View(products);
    }

When I used the code below, it works as intended:

<a asp-action="Index" asp-route-sortOrder="@ViewData["PriceDesc"]">
        <button >Price desc</button>
    </a>
    <a asp-action="Index" asp-route-sortOrder="@ViewData["NameDesc"]">
        <button >Name desc</button>
    </a>

However, I want the sorting to be displayed as a dropdown(with tag),and without submit button, something like this:

<select name="sorting" id="sorting">
            <option disabled selected>Select option</option>
            <a asp-action="Index" name="priceDesc" asp-route-sortOrder="@ViewData["PriceDesc"]">
                <option >Price: high to low</option>
            </a>
    <a asp-action="Index" name="nameDesc" asp-route-sortOrder="@ViewData["NameDesc"]">
                <option>Name: descending</option>
            </a>
        </select>

But for some reason the code above just ignore tag and the tag just disappear. And nothing happens when I choose one of the options.

2) I also have checkbox that works. But when the products are filtered with the checkboxes, the checkboxes stay unchecked. This is the controller code:

if(checkedTypes.Count != 0){
            products = products.Where(p => checkedTypes.Contains(p.TypeId));  
          
        }

and this is the view code:

 @foreach(var type in types)
            {  
                <input type="checkbox" name="checkedTypes" value="@type.id"/>
                <label>@type.Name</label>
                <br>    
            }   

Is there a way to keep the checked checkboxes stay checked even after the filtering on controller is done?




Aligning and Positioning Checkbox and Text in HTML and CSS

I am trying to align some check boxes and text using HTML and CSS - the current result I have achieved is this: enter image description here

However, the positioning moves depending on the length of the text. I'm wanting to achieve something like this (ignore the competition name differences):

enter image description here

My current code is as followed (The HTML also contains AngularJS code, which you can ignore as I'm specifically looking at the HTML):

HTML:

<div ng-repeat="option in $ctrl.options">
<div class="acca-builder-header"></div>
<div class="acca-builder-content">
    <div class="acca-builder-option-item" ng-repeat="optionItem in option.options">
        <div class="acca-builder-option-item-checkbox">
            <input type="checkbox" id="test" value="test">
            <label for="test">
                <span class="acca-builder-option-item-text">
                    <!--If there is a text key, use that with translations, if not then use the competition stuff.-->
                     
                </span>
            </label>
        </div>
    </div>
</div>

CSS (including the custom checkbox code):

.acca-builder-content {
width: 100%;
background-color: white;
margin-bottom: 10px;
border: 1px solid #c8c8c8;
padding: 2px 2px;
}

.acca-builder-option-item {
width: 100%;
text-transform: uppercase;
color: #29235c;
border-bottom: 1px solid #c8c8c8;
height: 30px;
padding: 2px 5px;
font-size: 13px;
text-align: center;
}

.acca-builder-option-item-text {
    vertical-align: middle;
}

.acca-builder-option-item:last-child {
    border-bottom: none;
}

.acca-builder-option-item-checkbox {
input[type=checkbox] + label {
    display: block;
    margin: 0.2em;
    cursor: pointer;
    padding: 0.2em;
  }
  
  input[type=checkbox] {
    display: none;
  }
  
  input[type=checkbox] + label:before {
    content: "\2714";
    border: 0.1em solid #000;
    border-radius: 0.2em;
    display: inline-block;
    width: 1em;
    height: 1em;
    padding-left: 0.2em;
    padding-bottom: 0.3em;
    margin-right: 0.2em;
    vertical-align: bottom;
    color: transparent;
    transition: .2s;
  }
  
  input[type=checkbox] + label:active:before {
    transform: scale(0);
  }
  
  input[type=checkbox]:checked + label:before {
    background-color: MediumSeaGreen;
    border-color: MediumSeaGreen;
    color: #fff;
  }
  
  input[type=checkbox]:disabled + label:before {
    transform: scale(1);
    border-color: #aaa;
  }
  
  input[type=checkbox]:checked:disabled + label:before {
    transform: scale(1);
    background-color: #bfb;
    border-color: #bfb;
  }
}

What would the best way be to achieve this?

Should I just use a table with two columns and align the first column (checkbox) to the right and the second column (the competition names) to the left? Or is there a better way to do this using the display css attribute?

Or should I just align all of the text/checkbox left - then add a container around it and center the container?

Apologies if there is something exactly like this existing - I did search but could not find specifically to what I wanted.

Thank you.




Using for loop on where() method

So I have a search-input and checkboxes that passes the values to the controller when there are inputs. And I want to use these values to get something back from the database. The search-input is a string and it works and intended. Here is the code for the search-input:

public async Task<ViewResult> Index(string searchString, List<int> checkedTypes)
{
    var products = from p in _db.Products select p;

    ViewData["CurrentFilter"] = searchString;
    
    if (!string.IsNullOrEmpty(searchString))
    {
        products = products.Where(p => p.Name.ToLower().Contains(searchString));
    }
    
    return View(products);
}

However the checkboxes values are stored in a list. So basically I want to do the same as the code above, but with a list. So basically an idea is like this:

if(checkedTypes != null)
{
    foreach (var i in checkedTypes)
    {
        products = products.Where(p => p.TypeId == i));
    }              
}

If I do it like the code above, I just get the last (i) from the loop. Another solution I did was this:

if(checkedTypes != null)
{
    var temp = new List<Product>();
    
    foreach (var i in checkedTypes)
    {
        temp.AddRange(products.Where(p => p.TypeId == i));
    }
    products = temp.AsQueryable();
}

But when I did it like that I get this error:

InvalidOperationException: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations.

So anyone have a solution that I can use? Or is there a better way to handle checkboxes in the controller?




mardi 27 octobre 2020

parent and child checkbox selection

I am working in a page to assig permissions to different roles so, I have a parents and child list for each section present in my nvbar. I am trying to do: When the user select a parent section, all the checkbox should be selected When the user select a parent section but, deselect one of the group should be deselect the parent When the user deselect a parent should be deselected all the childs checkbox.

I was trying with check attribute, change the state(true or false) Asigned one specific and dinamic id to check it but is not working for me. I am so confuse about how to implement it. If someone can help me I really will apreciated it

 <!-- Here will go the sections -->
                        <nz-collapse>
                          <nz-collapse-panel
                            *ngFor="let parent of this.userMngmtService.getNvBar() let i = index"
                            [nzHeader]="parent.Section"
                            [nzActive]="parent.is_active"
                            [nzExtra]="extraTpl"
                            [nzDisabled]="parent.disabled">
                            <p style="margin:0;">
                              <label class="checkbox-inline">
                                <input type="checkbox" [value]="parent.parentId" (change)="viewParentSelected($event, i)">View
                              </label>
                              <label class="checkbox-inline">
                                <input type="checkbox" value="">Edit
                              </label>
                              <label class="checkbox-inline">
                                <input type="checkbox" value="">Delete
                              </label>
                            </p>

                            <!-- SubSection -->
                            <nz-collapse>
                              <nz-collapse-panel
                                *ngFor="let child of this.userMngmtService.getNvBar()[i].Sub"
                                [nzHeader]="child.permission"
                                [nzActive]="child.is_active"
                                [nzExtra]="extraTpl"
                                [nzDisabled]="child.disabled"

                              >
                                <p style="margin:0;">
                                  <label class="checkbox-inline">
                                    <input type="checkbox" [value]="child.permission_id" (change)="viewChildSelected($event, i)" id="'checkedBox'+i">View
                                    <!-- <input type="checkbox" [value]="child.permission_id" (change)="viewChildSelected($event)" >View -->
                                  </label>
                                  <label class="checkbox-inline">
                                    <input type="checkbox" value="">Edit
                                  </label>
                                  <label class="checkbox-inline">
                                    <input type="checkbox" value="">Delete
                                  </label>
                                </p>
                              </nz-collapse-panel>
                            </nz-collapse>
                            <!-- SubSection End -->

                          </nz-collapse-panel>
                        </nz-collapse> 

enter image description here




Checkbox data handling

All. I'm trying to set a condition where the chosen checkbox after answering a form, appears not only the data but also the checkbox itself on the list of answers upon submission.

For example there are 3 checkboxes, if I choose Checkbox 1, that checkbox together with the data also appears on the submitted form and cannot be altered.

Any idea/s or suggestion/s how? Thanks.




lundi 26 octobre 2020

Checkbox Data handling

I'm trying to set a condition where the chosen checkbox upon answering a form, appears not only the data but also the checkbox itself on the list of answers. Any idea/s or suggestion/s how?




How to create a reactive data frame and table from user input checkboxes in shiny

so basically I am trying to develop a user interface where a person could select yes or no if they have the disease in the checkbox. Then it will take that yes/no answer for each corresponding disease and create a data frame so that a date table can be rendered and the person can see their responses. I've been struggling with trying to take what is clicked in the checkbox and putting it into a data frame with the diseases that I created another date frame for in the coding. I've tried several things and right now it keeps saying that the object 'data1', 'smoking', and 'diabetes' can't be found when I try to create the data frame from what the user would select. It seems my if/else statement is not working. Below is my code

library(shiny)
library(DT)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("IVD"),

    
    sidebarLayout(
        sidebarPanel(
            checkboxGroupInput("Diabete", "Diabetes:",
                              choices =  c("Yes" = "yes0",
                                 "No" = "no0")),
            checkboxGroupInput("Smoke", "Smoking:",
                               c("Yes" = "yes1",
                                 "No" = "no1"))),

        
        mainPanel(
            fluidRow(actionButton("button", "Click for Risk Prediction")),
            dataTableOutput("summary_table")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

 
observeEvent(input$button, { 
output$summary_table<-renderDataTable({
    a<- eventReactive(input$Diabete, {   
        if (input$Diabete == "yes0") {
            a=1
        } else {
            a=0
        }})
    b<- eventReactive(input$Smoke, {   
        if (input$Diabete == "yes1") {
            b=1
        } else {
            b=0
        }})
    ivd<-c('Diabetes','Smoking')
    #data<- c(11,10,sugar,8,7,6,5,4,3,2,1)
    values <- reactiveValues()
    values$ivd <- data.frame()
    eventReactive(input$Diabete, {
        diabetes <- a
        smoking <- b
        
        da <- data.frame(diabetes, smoking)
        
        data1 <- rbind(values$ivd, da)
    })
    ivd_data<-data.frame(ivd,data1,stringsAsFactors=FALSE )
    print(ivd_data)   
})
})
}

# Run the application 
shinyApp(ui = ui, server = server)



checkbox not displayed in futureBuilder

I have no idea what is going wrong here. I have two checkbox, one wrap with futureBuilder. But the checkbox wrap with FutureBuilder always can't displayed. If I change to return Text(snapshot.data);, I can see it display as 1 or 0.

But if I change to this, it not displayed anything.

 return Checkbox(
       onChanged: null, 
       value: snapshot.data == "0"
        ? false
        : true,
   );

Full code

 ...item['questions']
                                        .asMap()
                                        .entries
                                        .map((items) {
                                      return TableRow(children: [
                                        Padding(
                                            padding: EdgeInsets.all(10),
                                            child: Text(items.value['name'])),
                                        FutureBuilder(
                                            future: _workOrderBloc.selectAnswer(
                                                items.value['id']),
                                            builder: (context, snapshot) {
                                              if (snapshot.hasData) {
                                                return Checkbox(    // it display empty!!
                                                  tristate: true,
                                                  onChanged: null,
                                                  value: snapshot.data == "0"
                                                      ? false
                                                      : true,
                                                );
                                              } else {
                                                return Text("No data");
                                              }
                                            }),
                                        Checkbox(
                                          tristate: true,
                                          value: answers[items.value['id']] ??
                                              false,

                                          onChanged: (answer) {
                                            setState(() {
                                              answers[items.value['id']] =
                                                  answer;
                                            });
                                          },
                                          // onChanged: _onRememberMeChanged,
                                        ),
                                      ]);
                                    }).toList()



Need to add data in database using php [closed]

I have a contact.html form. I need to add it to database using php and mySQL. (I have checkboxes too in the contact form). I need help with feeding the data in database.




Adding and subtracting values based on checkboxes

I am creating a sheet to calculate points earned throughout the week and then subtract at the end of the week based on if a checkbox is marked. So the columns represent days 1-7 of the week. I want it to add 10 pts to the total every time a checkbox is marked in days 1-7. Then when the "end of week" box is checked, it subtracts 70 points.

I did countif but that adds ones. Not the value of 10. I could not get a sumif to work. Thank you!




Cannot Resolve symbol 'isChecked()'

enter image description here I am trying to check whether the radio button is checked or not. On basis of that , I will trigger some actions . I searched and found out "isChecked" is the method to do so. I use that method but the android studio says Cannot Resolve symbol 'isChecked()'.

<CheckBox
        android:id="@+id/cream"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:checked="false"

        android:paddingLeft="26dp"
        android:text="Whipped Cream"
        android:textSize="16sp" />

final CheckBox box = (CheckBox) findViewById(R.id.cream);
     if (box.isChecked())
     {
    box.setChecked(false);
}

Thank you in advance.

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

Having similar problem now , with v

final CheckBox whipped_cream_variable = (CheckBox) findViewById(R.id.whipped_cream);
boolean whipped_cream_has = whipped_cream_variable.isChecked();
Log.v("MainActivity", "Has whipped cream:" + whipped_cream_has);



Display checkbox in listView flutter

Please help ! I have two checkbox in table row. First checkBox is clickable but the second are not clickable.

 ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: widget.checklist['sections'].length,
                    itemBuilder: (context, index) {
                      final item = widget.checklist['sections'][index];

                      String s = item['applicable'];
                      var a = s.split(",");

                      return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Table(
                                columnWidths: {
                                  0: FixedColumnWidth(
                                      250.0), // fixed to 100 width
                                  1: FlexColumnWidth(),
                                  2: FlexColumnWidth(), //fixed to 100 width
                                },
                                defaultColumnWidth: FixedColumnWidth(120),
                                border: TableBorder.all(),
                                children: [
                                  TableRow(children: [
                                    TableCell(
                                        child: Container(
                                            color: Colors.grey.shade300,
                                            child: Padding(
                                                padding: EdgeInsets.all(10),
                                                child: Text(item['name'])))),
                                    for (var i in a)
                                      TableCell(
                                          child: Container(
                                              color: Colors.grey.shade300,
                                              child: Padding(
                                                  padding: EdgeInsets.all(10),
                                                  child: Text(i))))
                                  ]),
                                  ...item['questions']
                                      .asMap()
                                      .entries
                                      .map((items) {
                                    print(items.key);
                                    return TableRow(children: [
                                      Padding(
                                          padding: EdgeInsets.all(10),
                                          child: Text(items.value['name'])),
                                      Checkbox(
                                       tristate: true,
                                       value: true,
                                        onChanged: (bool value) {
                                          setState(() {
                                            widget.checklist['sections']
                                                [items.keys] = value;
                                          });
                                        },
                                      ),
                                      Checkbox(onChanged: null, value: false)
                                    ]);
                                  }).toList()
                                ])
                          ]);
                      // );
                    })

But I get this error

'package:flutter/src/material/checkbox.dart': Failed assertion: line 76 pos 15: 'tristate || value != null': is not true.



Adding a Checkbox to each Pivot Table Row in Google Sheets

Does anyone know how to automatically add a checkbox to the beginning of each result row in a pivot table in Google Sheets?

On this Google page: https://support.google.com/a/users/answer/9308622?hl=en, it seems to say that it is possible, but doesn't say how to:

  • "Use checkboxes to make Google Sheets more interactive. You can use checkboxes with charts, filters, pivot tables, and formulas."

I would like to allow the user to select one or more rows from the pivot table result, and then have a script run over the rows, doing something with each selected (checked) row.

You could add a checkbox beside the pivot table in a huge number of rows (so there would be a checkbox no matter how long the pivot table is), then allow the pivot table to fill in beside each of these checkboxes, but that would be a brute force approach and look bad.




dimanche 25 octobre 2020

Adding a Checkbox to each Pivot Table Row in Google Sheets

Does anyone know how to automatically add a checkbox to the beginning of each result row in a pivot table in Google Sheets?

On this Google page: https://support.google.com/a/users/answer/9308622?hl=en, it seems to say that it is possible, but doesn't say how to:

  • "Use checkboxes to make Google Sheets more interactive. You can use checkboxes with charts, filters, pivot tables, and formulas."

I would like to allow the user to select one or more rows from the pivot table result, and then have a script run over the rows, doing something with each selected (checked) row.

You could add a checkbox beside the pivot table in a huge number of rows (so there would be a checkbox no matter how long the pivot table is), then allow the pivot table to fill in beside each of these checkboxes, but that would be a brute force approach and look bad.




Use a field of a table as an object name in pyqt5

I got my db table like this

table

As you see i have an "elemento" column, so i want to use the value of that column as an object name of a checkbox and then obtain if it is checked or not, is it possible?




VBA code to send e-mail by check values in checkboxes

I have a problem with the code I wanted to convert it to check all checkboxes in userform. Each checkbox is numbered from 2 to 15. When a checkbox is checked, it sends an email from excel cells.

E.g. Checkbox2 reads data from A2 in the sheet

I tried to make loops, unfortunately I have a problem with implementing it. Is someone able to look at the code below and help? I would be very grateful

Sub MailExcelVbaOutlookDisplay()
    Dim zm1 As Variant
    Dim ctl As Control
    Dim i As Variant
    For i = 2 To 15
    Set ctl = Me.Controls("CheckBox" & i)
    If ctl.Visible = True Then
    zm1 = i
    Dim kola As Variant
    kola = Sheets("DataBase").Range("A" & zm1.Value).Value
    Dim kolb As Variant
    kolb = Sheets("Database2").Range("B" & zm1.Value).Value
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .To = kolb
        .CC = ""
        .Subject = "subject"
        .HTMLBody = "body"
        .Attachments.Add Attachment_Box.Value
        .Display
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
    End If
    Next i
Unload Me
End Sub



How to change a list depending on tkinter checkbutton

I have been trying to use tkinter CheckButton widget to edit items in a list - each item of the list is a new checkbutton. I want a save method to save the data to a text file, and a load method to load the info from the text file and mark the checkbutton boxes depending on the items in the list.

Here is my code so far, but the list doesn't seem to change when I check the buttons and update the list/file

Here is my code, I need to know why the list isn't updating when I check the boxes:

import tkinter.messagebox as box

modulesMain = Tk()
modulesMain.title("Edit OinK Modules")

moduleChecks = []

def SaveChanges():
    # Clear the text file
    modules = open("modules.txt", "w") #Write mode to overwrite the whole file
    modules.write("") # Put in blank text
    modules.close()

    modules = open("modules.txt", "a") # Append mode to append the file
    for item in moduleChecks:
        modules.write(item + "\n")
    print(moduleChecks)


def ReadModules():
    modules = open("modules.txt", "r")
    for line in modules:
        moduleChecks.append(line.strip())
    print(moduleChecks)

ReadModules()


appButton = Checkbutton(modulesMain, text = "Test", variable = moduleChecks[0]).grid()
searchButton = Checkbutton(modulesMain, text = "Test", variable = moduleChecks[1]).grid()






Save = Button(modulesMain, text = "Save Changes", command = SaveChanges).grid()



Why my checkbox is is not checked in laravel?

I have a checkbox on the marker if it is checked it should check its own row (only) but on the check, it performs no action.

enter image description here

the code i used for checkbox on marker

 locations = ["Naqshbandi store muneer sahab moman pura", 31.5959959, 74.4222583, 597];
    for (i = 0; i < locations.length; i++) {  
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
          });
    
          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
               
              infowindow.setContent(locations[i][0] + locations[i][3] + " <input type='checkbox' class='map-checked-box mr-1' data-id='"+ locations[i][3] +"' >");
              infowindow.open(map, marker);
            }
          })(marker, i ));
        }

this code should check checkbox of user row

$("body").delegate('.map-checked-box', "click", function(){
      var dataID = $(this).data('id');
      console.log(dataId);
      var status = true;
      if($(this).prop('checked') == false){
        status = false;
      }
      $(".chk-by-map[value='"+dataID+"']").prop('checked', status);
    });

but it is not working any help?




how i should manipulate that? Thank you

i have a fragment contains A-->Z checkboxes. and other fragments in each fragment there is a letter. after i check a box i need to call there fragment

ex : if i checked A i want fragment A to show up




samedi 24 octobre 2020

PHP / WP How to save checkbox status after refresh?

I have a filter that is list of country looped using foreach, I want to be able to save the checkbox's status when I refresh the page. So for example if Japan is checked, it should stay checked when I refresh the page. How should I do it, I have seen some posts about using localstorage but does it work with my code that doesn't have an "id"? Is it possible to do it by "name="filter_country[]"? I also have a filter that is using "Radio" I am not sure if it works for both radio and checkbox.

<ul class="filter-country">
        <?php foreach($countries as $country):?>
        <li class="filter-child filter-item">
        <div class="checkbox">
          <label>
            <input type="checkbox" class="dir-filters filter-checkbox" name="filter_country[]" value="<?php echo $country;?>">
            <?php echo $country;?>
          </label>
        </div>
        </li>
        <?php endforeach;?>



Pass a list of checkboxes to controller in ASP.NET MVC to get a list of related items

In my project, I have generated a list of related filter options to each product category and shown them as a partial view named AdvancedSearch in the Index view:

@model IPagedList<fardashahr.Models.ProductModel>
@using PagedList.Mvc;
@using PagedList;
<link href="~/Content/PagedList.css" rel="stylesheet" />
<div class="w-100">p
</div>
<div class="row w-100">
    <div class="col-md-3 bg-light">
            @Html.Partial("AdvancedSearch")
    </div>
    <div class="col-md-9">
            @foreach (var item in Model)
            {
                <div class="col-md-3">
                        <a href="@Url.Action("Details","Home",new { name = item.ProductUrl })">
                        </a>
                </div>
            }
        <div class="row">
            @Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page = page, name = ViewBag.categoryName,search=ViewBag.Search , pageSize=ViewBag.PageSize }))
        </div>
    </div>
</div>

And in AdvancedSearch partial view, I need to send chechboxes, their value and whther they are checked or not to the controller. Here is the partial view:

    @using fardashahr.Models;
@model FilterVM
@{
    List<SpecItemsModel> options = ViewBag.filters as List<SpecItemsModel>;
}
@if (options != null)
{
    <h3>Advanced Search</h3>
    <form action="Home/Index" method="get">
        @foreach (SpecItemsModel spec in options)
        {
            string label = spec.Name;
            int id = spec.Id;
            string name = spec.LatinName + "_" + id;

            object val = spec.SpecValue != null ? spec.SpecValue : string.Empty;

            <div class="w-100 form-group">
                <h4 class="active">
                    @Html.Label("", label, new { @class = "w-100 p-2" })
                </h4>
                <div class="w-100 p-2">
                    @switch (spec.SpecType.TechCode)
                    {
                        //some other cases
                          
                        case "SelectList":
                            SelectList selectList = SelectLists.GetDynamicList(spec.ListType.TechCode, val);
                            List<CodingItemModel> checkboxes = SelectLists.GetOptions(spec);
                            foreach (CodingItemModel item in checkboxes)
                            {
                                <div class="checkbox">
                                    @Html.CheckBox(item.Name, false, new { @id = id, @name = item.TechCode, @class = "" })
                                    @Html.Label(item.Name)
                                </div>
                            }
                            break;
                        default:
                            break;
                    }
                    @Html.ValidationMessage(name, "", new { @class = "text-danger" })
                </div>
            </div>
        }
        <div class="">
            <input type="submit" class="btn btn-danger btn-block btn-lg" value="Search" />
        </div>
    </form>
}

The action method should be something like this:

public ActionResult Index(string name, int? page, string search = null, int pageSize = 5)
        {
//some code
}

The problem is: I don't know how to send selected checkboxes by user to the controller. I tried FormCollection which only sends values. And since I cannot include isCheched property to CodingItemModel (representing every filter item), I tried a ViewModel including an IsCheched property but in this case such error appears: the Index view needs an IpagedList of ProductModel not a ViewModel. Any Ideas? I appretiate that.




vendredi 23 octobre 2020

Select all checkbox for each item on a list and update visually xaml using xamarin forms and syncfusion

I have a very complicated collection view of items and I would like to have the option to select all or select by skipping items from the binding list. Visually the first select all option is outside of the list. How can I select each item from the list and obtain its properties for example item id?

What I want enter image description here

XAML

 <StackLayout x:Name="editview" Grid.Row="3" IsVisible="false">
    <CollectionView ItemsSource="{Binding ListData}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
               
                <Label Grid.Column="1"
                       Text="{Binding subject}"
                       FontAttributes="Bold" />
                <Label Grid.Row="1"
                       Grid.Column="1"
                       Text="{Binding body}"
                       FontAttributes="Italic"
                       VerticalOptions="End" />
             <syncfusion:SfCheckBox x:Name="_checkbox"  IsThreeState="True" StateChanged="CheckBox_StateChanged" CornerRadius="5.0"/>
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>
  </StackLayout>

C#

void SelectAll_StateChanged(System.Object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs e)
        {
            if (!skip)
            {
                skip = true;
                New_ListData = vm.ListData;
                foreach (var item in New_ListData)
                {
                  NOTE: I DONT HAVE ACCESS TO _checkbox INSIDE THIS. I DONT KNOW WHY?
                  _checkbox.IsChecked = e.IsChecked;
                }

//THEN UPDATE THE COLLECTION VIEW WITH ALL CHECKBOXES TO TRUE

                 skip = false;
            }
        }



Ayuda con checkbox de yii2 [closed]

Estoy programando con yii2, y tengo 10 checkboxs en mi _form, pero necesito que la selección sea limitada, es decir, si hay 10 checkbox, que sólo puedan elegir cierta cantidad y los demás se desabiliten, alguien ha hecho algo parecido?




Problem with set initialValues for checkboxes in react-hook-form

here is my example: https://codesandbox.io/s/frosty-bush-pmc5f?file=/src/CheckboxDisplay.js

I have problem, because i want set initialParameters members.fields to checkboxes that these tags will choosed at the beginning and will display in our input.

For the moment it work, that we can choose tags and save what we choosed.

I want display tags which are in object members in data.js file

Anyone know answer to this question?




VBA Checkbox: Remove mark when information is missing

In the file I'm working on, I have set a checkbox that needs to be ticked to confirm that your boss has read the report. If information is missing, you will get a warning message telling you to fill all the data. Now I noticed that if you tick the checkbox after filling the whole template and then you delete some information, the ckeckmark does not disappear. Is there a way to make the checkmark go away if you delete some data afterwards, followed by a message to fill the whole info again and also tick the checkbox again?

This is the code I'm using:

Private Sub CheckBox1_Click()

Dim c As Range

For Each c In

ActiveSheet.Range(("D12:E20,C22:E22,D26:D27,F26,D30:D33,D35:D36,E31,D39,D40:E42,D45:D46,D49,D52,D53:F58,D61,C64:F65,C67:F67,D68,C71:F72,C74:F74,D75,C78:F79,C81:F81,D85"))

If c = "" Then

MsgBox "Please fill-out the missing cells!"

Cancel = True

If CheckBox1.Value = True Then CheckBox1.Value = False

Exit For

End If

Next

End Sub

Thank you!




jeudi 22 octobre 2020

How to capture whether a checkbox has been checked or not?

I have a Bootstrap form modal being used for a webinar signup. I've removed the other fields, but I have multiple text fields that are being captured and pushed to a CMS.

It's just these 3 checkboxes that I can't seem to get to push data across correctly. The checkboxes are recording all as "on" if the form is submitted once, but if the form is submitted a second time then the checkboxes that are checked/not checked will push through "on" and "off" accordingly. So it works on the second submit, but not on the first. Any help would be greatly appreciated. I'm new to javascript and jquery, so i'm now at the point of guessing.

$(document).ready(function() {
  $('.register-webinar').click(function() {
    checked = $("input[type=checkbox]:checked").length;

    if (!checked) {
      alert("You must select at least one session.");
      return false;
    }
  });

  $('input.webinar').change(function() {
    if ($(this).is(":checked")) {
      $(this).val("on")
    } else {
      $(this).val("off")
    }
  });

  $('#railway_form').on("submit", function(e) {
    e.preventDefault();
    setTimeout(AoProcessForm(this), 200);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

<div class="form-popup-bg">
  <div class="form-container">
    <button id="btnCloseForm" class="close-button">X</button>
    <h1 style="text-align:center;">Register your attendance</h1>
    <p style="text-align:center;">Please select which session/s you wish to attend.</p>
    <form name="railway_webinar" id="railway_form" class="railway_webinar" action="">
      <div class="form-group">
        <input type="checkbox" id="Webinar_1" name="Webinar_1" class="webinar">
        <label for="Webinar_1">webinar 1</label><br/>
        <input type="checkbox" id="Webinar_2" name="Webinar_2" class="webinar">
        <label for="Webinar_2">webinar 2</label><br/>
        <input type="checkbox" id="Webinar_3" name="Webinar_3" class="webinar">
        <label for="Webinar_3">webinar 3</label>
      </div>
      <input type="submit" value="Reserve my seat!" class="form-block-cta register-webinar" />
    </form>
  </div>
</div>



How can I dispatch a checkbox click programmatically?

I've tried several javascript functions here and there but it seems that none of them worked for me. What I'm doing is displaying a tower, that has as much stages as the user wish. This is basically creating html tags using Js for every stages and the last one is a checkbox. The thing I'd like to do is that when I click on a checkbox, all the other ones that are over this one would check programmatically also. So this is what I did:

    let event = new Event('click');

    //Here, q is the maximum stage that the user set.

    document.addEventListener('click', function(e) {
        let readStr = e.target.id;
        if (readStr.startsWith("checkboxFan") && e.isTrusted) {
            for (let r=parseFloat(readStr.substr(-1))+1; r<=q; r++) {
                document.getElementById("checkboxFan"+r).dispatchEvent(event);
            }
        }
    }, false);

And it's finding the IDs well and doing what I want, but the dispatchEvent isn't working as expected. In fact, it's not working at all. Also, the "click()" function works but the isTrusted is triggered, which is not what I want because the checkbox has to be clicked by the user.

Any solutions ?

Many thanks, have a nice day !




mercredi 21 octobre 2020

Change dropdown to multi-select checkbox in asp.net

I'm completely new to asp and I have a from in which the user has to select so many features from a dropdown list one in a time. It's frustrating and takes a lot of time. Now I'm thinking of changing this dropdown to a multi-select checkbox. This way user can choose all the features at once.

Here's my code:

    <div class="form-group row">
        <label class="control-label col-md-2" for="Title">Features</label>
        <div class="col-md-12 row">

            @Html.DropDownList("FeatureID", (SelectList)ViewBag.FeatureID, "-- Select ---", new { id = "FeatureID", @class = "form-control col-md-7" })

            <div class="col-md-5"  style="display: none">
                <input class="form-control" type="text" placeholder="Enter Feature Value" id="txtvalue"/>
                @*<textarea class="form-control" rows="5" type="text" placeholder="Enter Feature Value" id="txtvalue"></textarea>*@
            </div>
            <div class="col-md-2">
                <a class="btn btn-success " onclick="addFeature()">
                    <i class="zmdi zmdi-plus"></i>
                </a>
            </div>
        </div>
    </div>
    <div id="showfeaturelist">
        @Html.Action("ShowFeature")
    </div>

Any help would be much appreciated!




How can i remember the previsiously selected item of a QlistWidget

Is there another way to remember previously selected items of a QlistWidget without making lists? in the example below I tried to do it, only I can't check the items while reading the dictionary list. here is my sample code:

from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import (QWidget, QListWidget, QVBoxLayout, QApplication) from datetime import date, timedelta

class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(532, 292) self.lists={} self.itm=0 self.pushButton_ok = QtWidgets.QPushButton(Dialog) self.pushButton_ok.setGeometry(QtCore.QRect(336, 251, 88, 34)) self.pushButton_ok.setObjectName("pushButton_ok") self.pushButton_anulla = QtWidgets.QPushButton(Dialog) self.pushButton_anulla.setGeometry(QtCore.QRect(426, 251, 88, 34)) self.pushButton_anulla.setObjectName("pushButton_anulla") self.widget = QtWidgets.QWidget(Dialog) self.widget.setGeometry(QtCore.QRect(5, 13, 520, 221)) self.widget.setObjectName("widget") self.gridLayout = QtWidgets.QGridLayout(self.widget) self.gridLayout.setContentsMargins(10, 10, 10, 10) self.gridLayout.setObjectName("gridLayout") self.listWidgetdate = QtWidgets.QListWidget(self.widget) self.listWidgetdate.setObjectName("listWidgetdate") self.gridLayout.addWidget(self.listWidgetdate, 0, 1, 1, 1) self.listWidgetlav = QtWidgets.QListWidget(self.widget) self.listWidgetlav.setObjectName("listWidgetlav") item = QtWidgets.QListWidgetItem() self.listWidgetlav.addItem(item) self.gridLayout.addWidget(self.listWidgetlav, 0, 0, 1, 1)

    self.listWidgetlav.currentItemChanged.connect(self.itemActivated_event)
    self.list1=["B","C","D"]
    for i in range(len(self.list1)):
        item = QtWidgets.QListWidgetItem()
        self.listWidgetlav.addItem(item)
        item.setText(self.list1[i])
    self.listWidgetlav.setCurrentRow(0)
     

    self.retranslateUi(Dialog)
    QtCore.QMetaObject.connectSlotsByName(Dialog)

def retranslateUi(self, Dialog):
    _translate = QtCore.QCoreApplication.translate
    Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
    self.pushButton_ok.setText(_translate("Dialog", "Ok"))
    self.pushButton_anulla.setText(_translate("Dialog", "Anulla"))
    __sortingEnabled = self.listWidgetdate.isSortingEnabled()
    self.listWidgetdate.setSortingEnabled(False)
    self.listWidgetdate.setSortingEnabled(__sortingEnabled)
    __sortingEnabled = self.listWidgetlav.isSortingEnabled()
    self.listWidgetlav.setSortingEnabled(False)
    item = self.listWidgetlav.item(0)
    item.setText(_translate("Dialog", "A"))
    self.listWidgetlav.setSortingEnabled(__sortingEnabled)

     

def load_item(self): 
    self.list2=self.dates(date(2019,5,3),date(2019,5,6))
    self.listWidgetdate.clear()
    for i in range(0,self.listWidgetdate.count()):
        self.listWidgetdate.takeItem(i)
    for i in range(len(self.list2)):
        item1 = QtWidgets.QListWidgetItem()
        self.listWidgetdate.addItem(item1)
        item1.setText(self.list2[i])
        item1.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
        item1.setCheckState(QtCore.Qt.Unchecked)
             

def itemActivated_event(self):
    self.make_settigs(self.listWidgetlav.currentRow())
    self.load_item()
    print(self.listWidgetlav.currentRow())

def on_clicked(self):
    self.list_of_imp=[]
    for row in range(0, self.listWidgetdate.count()):
        it = self.listWidgetdate.item(row)
        if it.checkState() == QtCore.Qt.Checked:
            # print(it.text())
            self.list_of_imp.append(True)
        else:self.list_of_imp.append(False)
    return self.list_of_imp

def dates(self,datein,dateout):
    self.list_dates=[]
    # start_date = datein
    # end_date = dateout

    st_date = datein
    ed_date = dateout

    delta = ed_date - st_date

    for i in range(delta.days+1):
        day =st_date + timedelta(days=i)
        e=str(day)
        self.list_dates.append(e)

    return self.list_dates

def make_settigs(self,ind):
    self.tmp=self.on_clicked()
    self.lists['lst'+str(self.itm)]=self.tmp
    self.current=ind
    checked=2
    unchecked=0
-----   The problem is here ------
    try:
        if len(self.lists['lst'+str(self.current)])!=0:
            for i in range(len(self.lists['lst'+str(self.current)])):
                it = self.listWidgetdate.item(i)
                if (self.lists['lst'+str(self.current)][i])==True:
                    if it.checkState() == QtCore.Qt.Unchecked:
                        print(it.checkState, "------checked--------")
                        it.setCheckState(checked)
                    else:
                        it.setCheckState(checked)
                elif (self.lists['lst'+str(self.current)][i])==False:
                    if it.checkState() == QtCore.Qt.Checked:
                        print(it.checkState, "-----unchecked---------")
                        it.setCheckState(unchecked)
                    else:
                        it.setCheckState(unchecked)

    except: print("We don t have the list yet")

    self.lists['lst'+str(self.itm)]=self.tmp
    self.itm=ind


    print(self.lists)

    

if name == "main": import sys app = QtWidgets.QApplication(sys.argv) Dialog = QtWidgets.QWidget() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())




mardi 20 octobre 2020

Creating Custom MUI Checkbox Component to work with FormControlLabel

I have created a custom checkbox component that wraps a Material UI checkbox.

export default function PublishCheckbox({record}) {
const {publishData} = record;
const {categoryNameForId} = useStoreState(state => (state.document))
const togglePublishDocument = useStoreActions(actions => actions.document.togglePublishDocument);

const handleClick = (event) => {
    event.stopPropagation();
    togglePublishDocument({publishData});
}

return (
    <Checkbox disabled={source === 'PP'} checked={published} color="primary"
              onClick={handleClick} size="medium"/>
)
};

PublishCheckbox.propTypes = {
    record: PropTypes.object.isRequired,
}

It works fine for most of my cases, except where I try use a FormControlLabel component with it.

<FormControlLabel className={classes.publishButton} label="Publish" control={<PublishCheckbox record={file}/>}/>

What happens is that clicking the checkbox calls the onClick action of my custom component twice. Clicking on just the label calls it just once as you would expect. I think this is because the FormConrolLabel is specifically designed to work with MUI checkboxes (and radios and switches), but my custom component is not exposing and using the props and refs the same way so some of that Material UI magic is getting lost.

How can I change my custom checkbox to work with FormControlLabel and stop calling my onClick event twice?