dimanche 31 janvier 2021

Show divs if chec box checked else hide unless the 'show all' checkbox checked

I am attempting to make a page which depending on which checkboxes are checked, the corresponding divs/values will be displayed. If the red checkbox is checked, then the red div will be displayed. If the blue radio is checked, the blue div will display. If blue and green are checked, then the blue and green divs will show but not the red. If the all check box is clicked, everything will show again so we can then repeat the process which means that all are showing but if i click the blue check box, then only blue will show and everything else won't until i click an additional value - so if blue and red are clicked then blue and red will show but not the green as that hasn't been clicked. If the blue is unchecked, then only the red will be showing

I've been working on this for a few days and I feel that I've hit my wall. If a check box is checked, I want that value to show, so if 'all', 'red', and 'green' are checked, then 'red', 'green', and 'blue' would show because the 'all' check box has been checked. If all is unchecked, then the blue div should vanish because it is not checked. I've been using google, lydna.com, and stack to get myself to where I currently am, but i'm not able to get the all aspect to work as I was hoping.

I started with links and am now using checkboxes. If you click one of the boxes, it shows the corresponding values. I want all the divs with the 'all' class to show on initial page load. I have figured out how to show that which is checked.

I have the .all class set to display initially, as that was how i could get everything to show on initial load. I've hit my wall and i'm hoping for help with this. And I have looked through the stacks and read many examples, but nothing I've found seems to compare to what I am trying to do.

FYI: Student / newb here with the most rudimentary understanding of javascript.

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="utf-8"> 
    <title>Show Hide Elements Using Checkboxes</title> 
  
    <!--CSS stylesheet-->
    <style> 
        .box { 
            color: #fff; 
            padding: 20px; 
            display: none; 
            margin-top: 20px; 
        } 
        
        .all{display: block;}
  
        .red { 
            background: red; 
        } 
  
        .green { 
            background: green; 
        } 
  
        .blue { 
            background: blue; 
        } 
  
        label { 
            margin-right: 15px; 
        } 
    </style> 
  
    <!--import jQuery cdn-->
    <script src= 
        "https://code.jquery.com/jquery-1.12.4.min.js"> 
    </script> 
  
    <script> 
        // Enable-Disable text input when checkbox is checked or unchecked
        // on initial page load, all is checked so everything shows
        
        // if all clicked - show all, if all not checked, remove all that have no other checked values
  
        // jQuery functions to show and hide divisions 
        $(document).ready(function () { 
            $('input[type="checkbox"]').click(function () { 
                var inputValue = $(this).attr("value"); 
                $("." + inputValue).toggle(); 
            }); 
        }); 
    </script> 
</head> 

<body> 
  <input type="hidden" name="all" value="false">

    <div> 
        <!--checkboxes-->
        <label><input type="checkbox"   id="checkbox"
            name="colorCheckbox" value="all"   checked="true"> 
            all 
        </label> 
        
        <label><input type="checkbox" 
            name="colorCheckbox" value="red"> 
            red 
        </label> 
  
        <label><input type="checkbox" 
            name="colorCheckbox" value="green">  
            green 
        </label> 
  
        <label><input type="checkbox" 
            name="colorCheckbox" value="blue">  
            blue 
        </label> 
    </div> 
  
    <!--Divisions to be shown and hidden-->
    <div class="all red   box">all Red Selected</div> 
    <div class="all green box">all Green Selected</div> 
    <div class="all blue  box">all Blue Selected</div> 

</body> 
</html>



JAVAFX How to update checkbox deselect after change?

Hi I am trying to write a JavaFX GUI application that allows the user to pick a set of pizza toppings using a set of check boxes. Assuming each topping cost 50 cents, and a plain pizza costs $10, display the cost of the pizza. Note that, once a topping is checked or unchecked, the cost of pizza should update automatically. I almost have it working but when I click multiple boxes the price changes, I am trying to + 0.50 cents per topping and if I de select check box -0,50 cents, but when I choose multiple check box it is adding more. How can I change this thanks.

import javafx.scene.control.CheckBox;
import javafx.scene.text.Text;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;


public class PizzaMenu extends VBox
{
    private double cost;
    private Text text;
    private CheckBox checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, checkbox6;
    public PizzaMenu()
    {
        cost=10.00;
        text=new Text("Pizza Cost:" + cost);
        checkbox1 = new CheckBox("Extra Cheese");
        checkbox1.setOnAction(this::processCheckBox);
        checkbox2 = new CheckBox("Green Pepper");
        checkbox2.setOnAction(this::processCheckBox);
        checkbox3 = new CheckBox("Pepperoni");
        checkbox3.setOnAction(this::processCheckBox);
        checkbox4 = new CheckBox("Onion");
        checkbox4.setOnAction(this::processCheckBox);
        checkbox5 = new CheckBox("Sausage");
        checkbox5.setOnAction(this::processCheckBox);
        checkbox6 = new CheckBox("Anchovies");
        checkbox6.setOnAction(this::processCheckBox);
        //layout container 4 hbox, 2 vbox?
        HBox hSet1 = new HBox(checkbox1, checkbox2);
        hSet1.setAlignment(Pos.CENTER);
        HBox hSet2 = new HBox(checkbox3, checkbox4);
        hSet2.setAlignment(Pos.CENTER);
        HBox hSet3 = new HBox(checkbox5, checkbox6);
        hSet3.setAlignment(Pos.CENTER);
        HBox userCost = new HBox(text);
        userCost.setAlignment(Pos.CENTER);
        VBox vSet1 = new VBox(hSet1,hSet2,hSet3,userCost);
        vSet1.setAlignment(Pos.CENTER);
        setSpacing(20);
        getChildren().addAll(vSet1);
    }
    public void processCheckBox(ActionEvent event)
    {
        if(checkbox1.isSelected() || checkbox2.isSelected() || checkbox3.isSelected() || checkbox4.isSelected() || checkbox5.isSelected() || checkbox6.isSelected())
        {
            cost = cost + 0.50;
            text.setText("Pizza Cost:" + cost);
        }
        else if(!checkbox1.isSelected() || !checkbox2.isSelected() || !checkbox3.isSelected() || !checkbox4.isSelected() || !checkbox5.isSelected() || !checkbox6.isSelected())
        {
            cost = cost - 0.50;
            text.setText("Pizza Cost:" + cost);
        }
    }
}



Multiple filter query iusing php and MySQL

I have 12 "values" that can be assigned to customers - these are all stored in the database against the customer id - how do you go about writing a query to select all customers that have specific values assigned to them from a specific array of customers. These values are to be selected via a checkbox. I imagine it's some sort of nested if(isset) query ?




input multiple check box data to database

I created a form with multiple checkboxes to add to database, what do I need to change in the VALUE $_POST[penerima] to enter multiple checkboxes data into the database?

if(isset($_POST['simpan'])){
$simpan = mysqli_query($koneksi, "INSERT INTO umum (tanggal_terima, pengirim, no_surat, perihal, disposisi, penerima )
                                VALUES ('$_POST[tgl_terima]',
                                        '$_POST[pengirim]',
                                        '$_POST[no_surat]',
                                        '$_POST[perihal]',
                                        '$_POST[disposisi]',
                                        '$_POST[penerima]')
                                        ");



How to uncheck all Chromium checkboxes

I found this code snippet that seemed to be working, but I tried to implement it and it gave several errors, my question is just how to disable all checkboxes after loading the site.

var filter_form = document.getElementById("filter_form");
var inputs = filter_form.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type == "checkbox") {
      /* If default is checked, but state is not checked, check it*/
      if (inputs[i].defaultChecked == true) {
        if (inputs[i].checked != true) {
          inputs[i].checked = true;
        }
      /* If defeault not checked, but state is checked, uncheck it */
      } else {
        if (inputs[i].checked == true) {
          inputs[i].checked = false;
        }
      }
    }  
}

enter image description here




Angular checkbox list with mat-checkbox

I have a form with checkboxes in the form of a list. When I check a checkbox, the value updates in my formgroup but at the HMI level, the checkbox does not remain checked

ngOnInit(){
    const validators = [];
    if(this._isRequired){
      validators.push(Validators.required);
    }
    this.controlFormGroup.addControl(this.controlName, new FormArray([]));
    
    this.addCheckboxes();
    this.onComponentReady.emit(this.controlFormGroup);
  }
  get optionsFormArray() {
    console.log(this.controlFormGroup.controls[this.controlName]);
    return this.controlFormGroup.controls[this.controlName] as FormArray;
  }
  private addCheckboxes() {
    this.options.forEach(() => this.optionsFormArray.push(new FormControl(false)));
  }

<div [formGroup]="controlFormGroup">
    <div [formArrayName]="controlName" *ngFor="let option of optionsFormArray.controls; let i = index" [ngClass]="orientation">
        <mat-checkbox [formControlName]="i">
            
        </mat-checkbox>
    </div>
    <mat-error *ngIf="controlFormGroup.controls[controlName].touched && controlFormGroup.controls[controlName].hasError('required')">
        <span [innerHTML]="errorMessage"></span>
    </mat-error>
</div>

I don't understand the problems




jQuery function can 'check' but can't 'uncheck' checkboxes

I'm setting up a click event for a div that will check/uncheck a set of checkboxes with a given identifier. Everything I've tried will usually check the box but I haven't found any variation of the code that will uncheck it. Here's everything I tried so far:

var dtebox = $( "#tg" + did );
var stebox = $( "#tg" + sid );
dtebox.prop( "checked", !dtebox.prop("checked" ));
stebox.prop( "checked", !stebox.prop("checked" ));

if($( "#tg" + did ).checked){
    $( "#tg" + did ).prop( "checked", false );
    $( "#tg" + sid ).prop( "checked", false );
    setFilters();
}else{
    $( "#tg" + did ).prop( "checked", true );
    $( "#tg" + sid ).prop( "checked", true );
    setFilters();
}

if($( "#tg" + did ).is( ":checked" )){
    $( "#tg" + did ).prop( "checked", false );
    $( "#tg" + sid ).prop( "checked", false );
    setFilters();
}else{
    $( "#tg" + did ).prop( "checked", true );
    $( "#tg" + sid ).prop( "checked", true );
    setFilters();
}

if($( "#tg" + did ).prop("checked")){
    $( "#tg" + did ).prop( "checked", false );
    $( "#tg" + sid ).prop( "checked", false );
    setFilters();
}else{
    $( "#tg" + did ).prop( "checked", true );
    $( "#tg" + sid ).prop( "checked", true );
    setFilters();
}

I've also tried all of these variations with just one checkbox. I don't know if setting the checkbox to "false" negates the if statement but, based on all the similar posts I've seen, at least one of these methods should uncheck as well as check the boxes. Can anyone tell me why the uncheck doesn't work?




Styling Checkbox for Zoom an IMG [closed]

I need your help. How can I style a checkbox like the button in the photo below? Thank u all for the support! ;)

IMAGE OF THE BUTTON

  function myFunction() {
    // Get the checkbox
    var checkBox = document.getElementById("myCheck");
    // Get the output text
    var img = document.getElementById("img_zoom");
  
    // If the checkbox is checked, display the output img
    if (checkBox.checked == true){
      img.style.transform = "scale(2)";
    } else {
      img.style.transform = "scale(1)";
    }
  }
img {
  margin: 50px;
  width: 100px;
  transition: all .4s ease;
}

#myCheck {
  position: absolute;
  top: 0px;
}
<input type="checkbox" id="myCheck" class="btn" onclick="myFunction()">
<img src="https://images7.alphacoders.com/104/1047388.jpg" id="img_zoom">



samedi 30 janvier 2021

shinyTree Checkboxes using Dates

I'm trying to create a branching checkbox input using dates similar to the picture below.

enter image description here

The final selections will be unique observations from the prior selected Name. Each Name could have many observations so I'd like to be able to use dates to choose specific ones. An example of my current code is below. I'm able to update the checkbox input based on the name to show all the Name's observations.

ui.r

library(shiny)
library(dplyr)

shinyUI(
    fluidPage(
        navbarPage(inverse = TRUE,
                   tabPanel("Page Title",
                            sidebarPanel(width = 4,
                                         selectizeInput("Name",
                                                        label = "Name",
                                                        choices = sort(unique(mydata$Name))
                                         ),
                                         checkboxGroupInput("Observation",
                                                            label = "Observation",
                                                            choices = sort(unique(mydata$Observation))
                                         )
                            )
                            ,
                            mainPanel(
                                tableOutput("RepDimTable")
                            ))
                   
        )))

server.r

library(shiny)
library(dplyr)

shinyServer(function(input, output, session){
    
    dat <- reactive({
        
        d <- mydata %>%
            filter(Name == input$Name)
        
        updateCheckboxGroupInput(session, "Observation", choices = unique(d$Observation))
        
        d
        
    })
    
    
    output$RepDimTable = renderTable({

        repDimReactive = dat()   %>%
            filter(Observation %in% input$Observation) %>%
            select(Observation, Date, Name, Colour, Score)
        
        repDimReactive
        
    })
})

I'm unsure how to create the branching checkbox from the Date and Observation columns. I've attempted shinyTree solutions but didn't know how to nest the dates and observations into a useable list form.

Data

mydata <- structure(list(Observation = 1:8, Date = c("2020-12-01", "2020-12-01", 
"2020-12-01", "2021-01-01", "2021-01-01", "2021-01-01", "2021-01-15", 
"2021-01-15"), Name = c("Bob", "Fred", "George", "Bob", "Bob", 
"George", "Fred", "George"), Score = c(1L, 4L, 1L, 2L, 2L, 3L, 
2L, 1L), Colour = c("Red", "Blue", "Blue", "Green", "Blue", "Blue", 
"Green", "Red"), Year = c(2020L, 2020L, 2020L, 2021L, 2021L, 
2021L, 2021L, 2021L), Month = c(12L, 12L, 12L, 1L, 1L, 1L, 1L, 
1L), Day = c(1L, 1L, 1L, 1L, 1L, 1L, 15L, 15L)), row.names = c(NA, 
8L), class = "data.frame", na.action = structure(9:22, .Names = c("9", 
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", 
"21", "22"), class = "omit"))



Javascript in Wordpress Contact Form 7 plugin - Show A Field Only When Specific Checkboxes Are Selected

Hello… I’m new one this forum… Please, I need a help…

I have this code for contact form 7 , and works perfect but with radio button (i need to be a checkbox):

<label>Select A Size:</label> [radio select-a-size id:SelectASizeRadio default:1 "S" "M" "XL" "Other"]
 
<label id="EnterYourSize"> Please Specify Your Size
[text size] </label>
 
[submit "Send"]
 
<script language="javascript" type="text/javascript">
// Hide the Text field by default
document.getElementById('EnterYourSize').style.display = 'none';
document.getElementById('SelectASizeRadio').addEventListener('click', displayTextField);
function displayTextField() {
  // Get the value of the currently selected radio button. 'select-a-size' is the name of the radio buttons you specify in the form builder
  var radioText = document.querySelector('input[name="select-a-size"]:checked').value;
  if (radioText == 'Other') {
    document.getElementById('EnterYourSize').style.display = 'block';
  } else {
    document.getElementById('EnterYourSize').style.display = 'none';
  }
}
</script>

How I can change this from radio to checkbox with same function, when user check “Other” to get a text input field?




vendredi 29 janvier 2021

How To Pre-Select CheckBox in SwiftUI

This is my CheckBoxField

How do I display a checkboxfield with a checkmark shows it was pre-checked already?

Here is how I use it. I would like to see the checkboxfield has a checkmark in there when loading like this one.

enter image description here

CheckboxField(
    id: "Completed",
    label: "Completed",
    callback: self.checkboxSelected
)

func checkboxSelected(id: String, isMarked: Bool) {
    print("This is done ->>> \(id) is marked: \(isMarked)")
}

import SwiftUI

struct CheckboxField: View {
    let id: String
    let label: String
    let size: CGFloat
    let color: Color
    let textSize: Int
    let callback: (String, Bool)->()
    
    init(
    id: String,
    label:String,
    size: CGFloat = 10,
    color: Color = Color.black.opacity(0.68),
    textSize: Int = 14,
    callback: @escaping (String, Bool)->()
    ) {
        self.id = id
        self.label = label
        self.size = size
        self.color = color
        self.textSize = textSize
        self.callback = callback
    }
    
    @State var isMarked:Bool = false
    
    var body: some View {
        Button(action:{
            self.isMarked.toggle()
            self.callback(self.id, self.isMarked)
        }) {
            HStack(alignment: .center, spacing: 10) {
                Image(systemName: self.isMarked ? "checkmark.square" : "square")
                .renderingMode(.original)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 20, height: 20)
                Text(label)
                .font(Font.system(size: size))
                .foregroundColor(Color.black.opacity(0.87))
                Spacer()
            }.foregroundColor(self.color)
        }
        .foregroundColor(Color.white)
    }
}



php enable checkboxes if two arrays values equal

Issue im having is no matter what method I use to get to this point $result[$k] never equals to $results['value'] but if i literally use the actual an integer like the example, works for each one. i know i'm missing something simple

$k=0;
foreach($field->choices as &$results){
  if($results['value'] == $result[1]){
    $results['isSelected'] = true;
  }
  $k++;
}



How to Send Multiple Checkbox through migration in LARAVEL_7

I want to store the selected checks in a single variable and send it to the database, I am only using migrations, others that other data is sent in the migration.

Pd: I get this error by the array: ErrorException Array to string conversion

My template.

<form action="" method="POST">
                @csrf

                <div class="row">
                    <div class="col-md-6 mt-5">
                        <select name="Sede" class="form-select" aria-label="Default select example">
                            <option selected name="Sede">Campus Sede</option>
                            <option value="Cancún">Cancún</option>
                            <option value="Chihuahua">Chihuahua</option>
                            
                        </select>
                    </div>

                    <div class="col-md-6 mt-5">
                        <select name="Alcance" class="form-select" aria-label="Default select example">
                            <option selected name>Alcance</option>
                            <option value="Local">Local</option>
                            <option value="Nacional">Nacional</option>
                        </select>
                    </div>

                    <div class="col-md-6 mt-5">
                        <label for="">Nombre del Proyecto</label>
                        <input type="text" name="Nombre" class="form-control col-12">
                    </div>

                    <div class="col-md-6 mt-5">
                        <label for="">Cierre de Inscripciones</label>
                        <input data-date-format="yyyy/mm/dd" id="datepicker" name="Cierre" class="form-control col-12">
               
               
                    </div>

                    <div class="col-md-6 mt-5">
                        <input type="checkbox" name="Areas[]"id="ingenieria" value="Ingeniería" />
                        <label for="ingenieria">Ingeniería</label>
                        <input type="checkbox" name="Areas[]"id="humanidades" value="Humanidades" />
                        <label for="humanidades">Humanidades</label>
                        <input type="checkbox" name="Areas[]"id="negocios" value="Negocios" />
                        <label for="negocios">Negocios</label>
                        <input type="checkbox" name="Areas[]" id="salud" value="Salud" />
                        <label for="salud">Salud</label>
                    </div>

                    <div class="col-md-12 mt-5">
                        <label for="">Cual es el departamento donde impactara directamente el proyecto?</label>
                        <input type="text" name="P1" class="form-control col-12">
                    </div>

                    
                    <div class="row form-group mt-5">
                        <button type="submit" class="btn btn-success col-md-2 offset-5">Guardar</button>
                    </div>
            </form>

My controller:

public function save(Request $request){

        $validator = $this->validate($request, [
            
            'Sede'=> 'required|string|max:255',
            'Alcance'=> 'required|string|max:255',
            'Nombre'=> 'required|string|max:255',
            'Cierre'=> 'required|date',
            'Areas'=> 'required',
            'P1'=> 'required|string|max:255',
            'P2'=> 'required|string|max:255',
            'P3'=> 'required|string|max:255',
            'P4'=> 'required|string|max:255'
        ]);

       $data = request()->except('_token');

      Project::insert($data);
        
       return back()->with('datosGuardados', 'Datos almacenados, Correctamente');
   
      

    }

My Model:

class Project extends Model
{
    protected $fillable = ['Sede','Alcance','Nombre','Cierre','Areas','P1','P2','P3','P4'];

    protected $casts = [
        'Areas' => 'array'
    ];
}

My migration:

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('Sede');
        $table->string('Alcance');
        $table->string('Nombre');
        $table->date('Cierre');
        $table->string('Areas');
        $table->string('P1');
        $table->string('P2');
        $table->string('P3');
        $table->string('P4');
        $table->timestamps();
    });
}

enter image description here

As you see the error is due to the checkbox that I don't know how to send it as a single array and store it in the database, I would appreciate any help. I was investigating and I did not find anything




Selenium checkbox not being checked

I'm trying to test the privacy statement checkbox on this website

enter image description here

the HTML code of the checkbox is

<input type="checkbox" name="registryTandCs" id="registryTandCs" value="" class="form-check-input form-check-input--custom" required="required" data-parsley-multiple="registryTandCs">

The code that I am using to check this is

driver.findElement(By.id("registryTandCs")).click();

However, it doesn't seem to work. I have also tried

WebElement checkBox = driver.findElement(By.id("registryTandCs"));
checkBox.click();

If it's any help, the website in question is here




como impedir de desmarcar um checkbox [closed]

Como faço pra impedir um usuário de desmarcar um checkbox com o javascript? Estou perguntando isso pois não é possível usar readOnly num checkbox.




Google Sheet Script : This operation is not supported on a range with a filtered-out row

Here is my issue :

My code below does not work because of the line: current.uncheck();

And the log say : "This operation is not supported on a range with a filtered-out row."

But this sheet is not supposed to contain a filter, I also try to remove the potential filters without success.

if(current.isChecked()) // If the check box is checked
{
  // I put some data in a array :
  var arraySupport = rangeColumnToArray(ss.getSheetByName("import_support").getRange("A1:A15"))

  var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of Data Bank");

  // I change criteria filter on other sheet :
  var criteriaSupport = SpreadsheetApp.newFilterCriteria()
      .setHiddenValues(arraySupport)
      .build();  
  dataSheet.getFilter().setColumnFilterCriteria(24, criteriaSupport);
  
  ss.getRange("G5:G").clearContent();  // clear eventual content
  copyExo();  // This fonction copy one column from the filtered sheet (dataSheet) on activeSheet
  activeSheet.getFilter().remove();  // I try that without success
  current.uncheck(); // And I try to uncheck the checkbox
}

Thank's for all the help you will provide me.




Angular checkbox with boolean

I'm working on a Angular project where I need to give an use admin right. The isAdmin is a boolean (false/true). But it can't figure it how to parse the right value to the component and save the value.

<div class="checkbox">
   <label>
     <input type="checkbox" name="isAdmin" [(ngModel)]="user.isAdmin" [checked]="item.checked">
     Is Admin?
   </label>
</div>

The component.ts looks likes this:

this.userForm.get('isAdmin').valueChanges.subscribe(val => {
  this.newUser.isAdmin = !!val;
});

Can someone see what is mine mistake?




Why can't get input value checkbox in array?

In the code described below, the value of the input should be taken from everyone in the array and a new div with the input value in innerHtml should be created. I don't know why get an error that length.value not defined?

<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsone">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divstwo">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsthree">

<button onclick="myFunction()">Click me</button>

<div id="container"></div>

function myFunction() {
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked').value;

         for (var i = 0; i < checkboxnewdivs.length; i++) {
                     
         var iddivs = array.push(checkboxnewdivss[i].value);  
         
         var div_new = document.createElement("DIV"); 
         div_new.innerHTML = "ID div:"+iddivs ;                   
         document.getElementById("container").appendChild(div_new);
        
         }        
}



how to make checkbox IntVar can do math?

hi i'm having problem on my python quick project to use checkbox as int, i can use intVar for them but IntVar cant be use to do math for my ifelse output

gejala = Label(window, text="Pilihlah gejala anda yang tertera dibawa ini : ")
gejala.grid(padx=10, pady=3)

pt_1 = IntVar()
pt_2 = IntVar()
pt_3 = IntVar()
pt_4 = IntVar()
pt_5 = IntVar()
pt_6 = int()

p1 = Checkbutton(window, text = "Sesak nafas", variable = pt_1, onvalue=30)
p1.grid(column=1)
p2 = Checkbutton(window, text = "Sulit bergerak atau berbicara", variable = pt_2, onvalue=20)
p2.grid(column=1)
p3 = Checkbutton(window, text = "Demam", variable = pt_3, onvalue=5)
p3.grid(column=1)
p4 = Checkbutton(window, text = "Batuk dan sakit tenggorokan", variable = pt_4, onvalue=6)
p4.grid(column=1)
p5 = Checkbutton(window, text = "Terasa hambar saat mengkonsumsi makanan dan minuman", variable = pt_5, onvalue=50)
p5.grid(column=1)
p6 = Checkbutton(window, text = "Terasa sakit atau tertekan pada bagian dada", variable = pt_6, onvalue=35)
p6.grid(column=1)



infeksi=pt_1+pt_2+pt_3+pt_4+pt_5+pt_6

def rumus():
    if infeksi >= 49:
        infek = Label(window, text="Anda terkena covid-19 , harap hubungi puskesmas atau rumah sakit terdekat dan lakukan isolasi mandiri.")
        infek.grid(column=1)
    else:
        infek = Label(window, text="Anda bebas dari covid-19, harap selalu mematuhi protokol yang ada.")
        infek.grid(column=1)


diag = Button(window, text="Diagnosa", command=rumus)
diag.grid(column=1, pady=5)



Getter and Setter in checkbox angular

I have two pages, namely view all and filter page on the filter page I have a checkbox list, when I click the show all button it will display the data according to the filter that was checked, and this is going well

I want to make a checkbox if after I click button show all, the checkbox value that is checked remains in the list, I think there must be a setter and getter in the checkbox , but I am confused how to make it... what I have created now is when I click show all, after displaying the data according to the checked list and I enter the list page, the list is empty, nothing is checked

filterpage.html

<li *ngFor="let source of sourcesList"><ion-checkbox class="checkbox" [(ngModel)]="source.checked" ></ion-checkbox></li>

to get the value as checked I use this code in .ts

 for(let item of this.sourcesList){
        if(item.checked == true){
          params = item.sourceName;
        }
      }

but how to do it so that when it displays the filter list again, it will be checked according to the previous tick a.k.a (not refreshed)??




Index out of range blazor checkbox

I try to create the user management in blazor. The check box is check/uncheck when i click on it. but when It showed index out of bound . I dont know what went wrong. just try with blazor wasb. please help check this. it is just basic component but somehow i dont get used to its usage yet.
I try to create the user management in blazor. The check box is check/uncheck when i click on it. but when It showed index out of bound . I dont know what went wrong. just try with blazor wasb. please help check this. it is just basic component but somehow i dont get used to its usage yet.

  @page "/manageuserrole/{userId}"
    @inject HttpClient client

@inject IJSRuntime js
@inject NavigationManager uriHelper

<h3>User Roles</h3>


@if (manageUserRolesDto == null)
{
    <text>Loading...</text>
}
@*else if (manageUserRolesDto.Length == 0)
    {
        <text>No Records Found.</text>
    }*@
else
{
    <EditForm Model="@manageUserRolesDto" OnValidSubmit="@UpdateUserRoles">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Role</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
                {
                    <tr>
                        <td>@manageUserRolesDto.UserRoles[i].RoleName</td>
                        <td>
                            <div class="form-check m-1">
                                <input type="checkbox" 
                                       @bind="@manageUserRolesDto.UserRoles[i].Selected" 
                                       />
                            </div>
                        </td>

                    </tr>
                }

            </tbody>
        </table>
        <button type="submit" class="btn btn-success">
            Submit
        </button>
    </EditForm>


}
@code {
    [Parameter]
    public string userId { get; set; }

    ManageUserRolesDto manageUserRolesDto { get; set; }
    protected override async Task OnInitializedAsync()
    {
        manageUserRolesDto = await client.GetFromJsonAsync<ManageUserRolesDto>("api/userroles/" + userId);
    }

    private void checkUserRole(int i)
    {
        manageUserRolesDto.UserRoles[i].Selected = !manageUserRolesDto.UserRoles[i].Selected;

    }



    async Task UpdateUserRoles()
    {
        await client.PutAsJsonAsync("api/userroles/" + userId, manageUserRolesDto);
        uriHelper.NavigateTo("user");

    }


    async Task ManagePermission(string roleId)
    {

    }
}



jeudi 28 janvier 2021

Multiple select with custom data

I have a form with a multiple select like this: 

.form-row__select
        = f.collection_check_boxes(:game_ids, @games, :id, :name)

The collection @games worked because the data was returned this way:

=> #<Game:0x00007fa12c3a9560
 id: 5,
 name: :example,
 active: true,
 ...

But now I need to add custom data to my collection and I was not able to make the multiple select work:

game = Game.enabled.includes(:category)
    @games = game.map do |s|
       [[s.category.name, I18n.t(s.type_code, scope: 'enum.type.name')].join(' - '), s.id]
    end
@games.sort!

The result of the above method is an array of array like this:

[["Example one - Category X", 5],
["Example four - Category Y", 1]]
...

How can I make a multiple select using the array above and showing its strings so they can be selected? Thank you so much for your help!




Vuelidate - How To Validate Checkboxes at the same time?

I have a form that includes 5 checkboxes total. Here is my logic;

If MainCheck is true -> AllCheck is also true, other 3 of them is false. -> If the other three of them is true at the same time that means all of them are selected, that's why AllCheck becomes true and the others turn to false again... (CheckA, CheckB and CheckC)

But here is the deal...

Let's say the user checks the MainCheck, it gives them 4 more checboxes to see. (If MainCheck is not checked, then they are not allowed to see the other 4 checkboxes.)

The user may want to check RadioA and RadioC and not RadioB so they may uncheck the RadioAll. My issue starts here.

I want to use Vuelidate to validate these 3 forms. In a way, I settled on how logic would work. But I don't know how to validate checkboxes and I need your help at this point.

validations(){
  if(this.MainCheck && !this.AllCheck){
     return {
    CheckA, CheckB and CheckC validations needed to be here 
    because the user didn't select the AllCheck so he/she wants to select one ore two of the checkboxes, 
    not the three of them together.
  }
}
  else if(this.MainCheck && this.AllCheck){
    return {
    This means that I don't need to validate the CheckA, B and C 
    because the user already select the AllCheck...
  }
}
   }

So my validation should control the three checkboxes. There may be checked only one checkbox, that's okay, or there may be checked two checkboxes (A and B, A and C or B and C). But if AllCheck is not checked and none of the three others are checked, then I need an error message that says "You haven't checked AllCheck and also you haven't checked any other options. You need to select at least one of them.)

How do I do that?




mercredi 27 janvier 2021

Google Sheets range(s) to allow varying numbers of checkboxes

I have a sheet where I need to limit the number of checkboxes allowed within a range. Like this

H219 to H225 allows only one checkbox to be checked.

H228: H335 allows three checkboxes.

H340:H347 Allows two checkboxes.

This script works when I use it once, but when i add it multiple times and change the range it seems to stop working.

function onEdit(e) {
  const sh=e.range.getSheet();
  if(sh.getName()=='GOALS') {
    const mcpr=1;
    const mcpc=2;
    const arrayrange='h219:h225';
    const arg=sh.getRange(arrayrange);
    const avs=arg.getValues();
    const ulr=arg.getRow();
    const ulc=arg.getColumn();
    const lrr=ulr+arg.getHeight()-1;
    const lrc=ulc+arg.getWidth()-1;   
    if(e.range.columnStart<=lrc && e.range.rowStart<=lrr && e.value=="TRUE") {
      let rc=avs[e.range.rowStart-ulr].filter(function(e){return e;}).reduce(function(a,v){ if(v){return a+1;} },0);
      if(rc>mcpr){e.range.setValue("FALSE");e.source.toast('Sorry maximum checks per row is ' + mcpr);};
      let cc=avs.map(function(r,i){return r[e.range.columnStart-ulc];}).filter(function(e){return e}).reduce(function(a,v){if(v){return a+1;}},0);
      if(cc>mcpc){e.range.setValue('FALSE');e.source.toast('Sorry maximum checks per column is ' + mcpc);};          
    }
  }
}

//

function onEdit(e) {
  const sh=e.range.getSheet();
  if(sh.getName()=='GOALS') {
    const mcpr=1;
    const mcpc=3;
    const arrayrange='h236:h244';
    const arg=sh.getRange(arrayrange);
    const avs=arg.getValues();
    const ulr=arg.getRow();
    const ulc=arg.getColumn();
    const lrr=ulr+arg.getHeight()-1;
    const lrc=ulc+arg.getWidth()-1;   
    if(e.range.columnStart<=lrc && e.range.rowStart<=lrr && e.value=="TRUE") {
      let rc=avs[e.range.rowStart-ulr].filter(function(e){return e;}).reduce(function(a,v){ if(v){return a+1;} },0);
      if(rc>mcpr){e.range.setValue("FALSE");e.source.toast('Sorry maximum checks per row is ' + mcpr);};
      let cc=avs.map(function(r,i){return r[e.range.columnStart-ulc];}).filter(function(e){return e}).reduce(function(a,v){if(v){return a+1;}},0);
      if(cc>mcpc){e.range.setValue('FALSE');e.source.toast('Sorry maximum checks per column is ' + mcpc);};          
    }
  }
}

Thank you so much, I have searched far and wide and this was the best script i could find, i just need it to work in about 6 places within the same sheet, with each range allowing a different number of checkboxes.




Blank time series plot with bokeh

as you can see in the picture (datfarme) I want to plot a time series plot (for total vaccinations per date ) with a check box filter for the countries (i have 60 country in my dataset ) but all i get is a blank plot.enter image description here

This is my code :

import panel as pn
import altair as alt
from altair import datum
import pandas as pd
from vega_datasets import data
import datetime as dt

alt.renderers.enable(‘default’)
pn.extension(‘vega’)
df2 = df.copy()

create list of company names (tickers) to use as options
tickers = [‘Argentina’, ‘Austria’, ‘Bahrain’, ‘Belgium’ ,‘Brazil’, ‘Bulgaria’ ,‘Canada’,
‘Chile’ ,‘China’ ,‘Costa0Rica’ ,‘Croatia’ ,‘Cyprus’, ‘Czechia’, ‘Denmark’,
‘Ecuador’, ‘England’ ,‘Estonia’ ,‘Finland’, ‘France’ ,‘Germany’, ‘Gibraltar’,
‘Greece’ ,‘Hungary’, ‘Iceland’, ‘India’, ‘Indonesia’ ,‘Ireland’ ,‘Isle0of0Man’,
‘Israel’ ,‘Italy’ ,‘Kuwait’ ,‘Latvia’ ,‘Lithuania’ ,‘Luxembourg’ ,‘Malta’,
‘Mexico’, ‘Netherlands’, ‘Northern0Ireland’ ,‘Norway’ ,‘Oman’ ,‘Panama’,
‘Poland’ ,‘Portugal’, ‘Romania’, ‘Russia’ ,‘Saudi0Arabia’ ,‘Scotland’ ,‘Serbia’,
‘Seychelles’, ‘Singapore’ ,‘Slovakia’, ‘Slovenia’ ,‘Spain’ ,‘Sweden’,
‘Switzerland’ ,‘Turkey’ ,‘United0Arab0Emirates’ ,‘United0Kingdom’,
‘United0States’, ‘Wales’]

this creates the dropdown widget
ticker = pn.widgets.Select(name=‘country’, options=tickers)

this creates the date range slider
date_range_slider = pn.widgets.DateRangeSlider(
name=‘Date Range Slider’,
start=dt.datetime(2020, 12, 13), end=dt.datetime(2021, 1, 25),
value=(dt.datetime(2020, 12, 13), dt.datetime(2021, 1, 25))
)

title = ‘total vaccinations per day’
subtitle = ‘This dashboard allows you to select a country and date range to see total vaccinations per day.’

@pn.depends(ticker.param.value, date_range_slider.param.value)

def get_plot(ticker, date_range):
# Load and format the data
df = df2 # define df
df[‘date’] = pd.to_datetime(df[‘date’])
# create date filter using values from the range slider
# store the first and last date range slider value in a var
start_date = date_range_slider.value[0]
end_date = date_range_slider.value[1]
# create filter mask for the dataframe
mask = (df[‘date’] > start_date) & (df[‘date’] <= end_date)
df = df.loc[mask] # filter the dataframe
# create the Altair chart object
chart = alt.Chart(df).mark_line().encode( alt.X(‘date’),alt.Y(‘total_vaccinations’),
tooltip=alt.Tooltip([‘date’,‘total_vaccinations’])).transform_filter(
(datum.symbol == ticker) # this ties in the filter
)
return chart

dashboard = pn.Row(pn.Column(title, subtitle, ticker, date_range_slider),
get_plot # our draw chart function!
)
dashboard.servable()

enter image description here

any help would be appreciated and thank you in advance




VBA: ADODB with checkbox for output value

I run the ADODB query, the values of my variables are 0 and 1. In the place of my values I would like to have the checkbox enter image description here, but I don't know how to add it to my query.

My code is:

Public Sub INFO_PROTO(NO_POLICE As String)

Dim RECSET As New ADODB.Recordset
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc, db_produit prod, db_protocole proto" & _
            " where sousc.no_police = '" & NO_POLICE & "' and sousc.cd_dossier = 'SOUSC' and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit and sousc.is_protocole = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
If Not RECSET.EOF Then
    Worksheets("1 - Feuille de Suivi Commercial").Range("test").Value = RECSET.Fields("b_perf_cma").Value
    Worksheets("1 - Feuille de Suivi Commercial").Range("test2").Value = RECSET.Fields("b_perf_supp_ann").Value
    Worksheets("1 - Feuille de Suivi Commercial").Range("test3").Value = RECSET.Fields("b_perf_ctrat_gar").Value
Else
   Worksheets("1 - Feuille de Suivi Commercial").Range("test").Value = "NC"
    Worksheets("1 - Feuille de Suivi Commercial").Range("test2").Value = "NC"
    Worksheets("1 - Feuille de Suivi Commercial").Range("test3").Value = "NC"
End If
RECSET.Close

End Sub




Hide checkbox using CSS in Wordpress

I would like to hide the default checkbox from my light/darkmode toggle featured on my Wordpress blog. (Using single.php)

I inspected the code using the console and adjusted the CSS using the code below in the preview which worked. However, when I saved and ran it properly, I didn't get the same outcome.

input[type=checkbox], input[type=radio] {
box-sizing: border-box;
padding: 0;
display: none !important;
}
            <section id="blog-post">
                <div class="container-fluid">
                    <div class="row justify-content-center">
                        <div class="col-10">
                        <div class="checkbox mt-3 text-right">
                            <input type="checkbox" id="darkSwitch">
                            <label for="darkSwitch"><i class="far fa-lightbulb fa-lg"><i>Light switch</i></i></label>
                        </div>   
                            <div class="row my-5 justify-content-center">
                                <div class="col-sm-12 col-md-10 col-lg-8 mt-3">                                    
                                    <h2 class="subheader mt-3">Lorem Ipsum Dolor Amet.</h2>
                                    <div class="dropcap">
                                        <pre></pre>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <em>This is italic text</em>, <strong>this is bold text</strong>, <em><strong>this is bold italic</strong></em> text. Donec justo massa, imperdiet ac efficitur sit amet, pretium a nunc. Aliquam sem nisi, sagittis a lacus ut, pulvinar molestie magna. Nam aliquam tincidunt erat nec pulvinar. Nullam urna nunc, cursus nec pharetra eu, euismod id dolor. Duis imperdiet, ante iaculis suscipit pharetra, mauris neque ultricies lacus, tincidunt posuere lectus ipsum ac est. Donec odio nunc, feugiat nec mi eget, faucibus euismod urna. Donec pretium sit amet leo eget auctor. Nulla consequat metus at ullamcorper faucibus. Donec ultricies tristique velit sit amet commodo. Morbi bibendum, nulla ut aliquam bibendum, ex lacus lacinia dui, quis sagittis justo neque vel mauris. Phasellus varius dapibus sapien, et euismod turpis. Praesent elit metus, posuere nec ipsum eget, ultricies lobortis massa.</p>
<p>Quisque ornare libero id nibh imperdiet ultrices. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc fringilla urna in mauris consequat, eget lobortis elit sodales. Curabitur ipsum ligula, tincidunt eu venenatis quis, ullamcorper et nunc. Sed in hendrerit felis, eu fermentum mauris. In varius non urna at ullamcorper. Duis at arcu nibh. Vivamus et elementum purus. Nulla a tellus dapibus, tristique libero ut, porta odio. Nulla luctus aliquet tempus. Pellentesque ultrices finibus turpis, non vestibulum metus.</p>

Unchecked Checked




How are the countries displayed from the json file

I am really new and I got this piece of code that displays the countries before filtering it. I understood the filtering part. But I am not able to understand how the countries are getting displayed before the filtering on the webpage. I need to include a checkbox for each country and I know how to do this if it was the list of items but I am not able to understand this. How can I add the checkbox if I don't know what I am adding it for? Can anyone please help me?

import React, { Component, useCallback, useState  } from "react";


import {
  Button,
  Input,
  Footer,
  Card,
  CardBody,
  CardImage,
  CardTitle,
  CardText
} from "mdbreact";

import blankImg from "./blank.gif";

import "./style.css";
import "./flags.min.css";

import countriesList from "./countries.json";

class App extends Component {
  state = {
    search: ""
  };

  handleClick = () => { this.setState({ search: ""}); }

  renderCountry = country => {
    const { search } = this.state;
    var code = country.code.toLowerCase();
  function toggle(source) {
      
    }
    
   
    return (
      <div className="col-md-3" style=>
        <Card>
          <CardBody>
            <p className="">
              <img
                src={blankImg}
                className={"flag flag-" + code}
                alt={country.name}
              />
            </p>
            <CardTitle title={country.name}>
              {country.name.substring(0, 15)}
              {country.name.length > 15 && "..."}
            </CardTitle>
          </CardBody>
        </Card>
      </div>
    );
  };

  onchange = e => {
    this.setState({ search: e.target.value });
  };
  
  

  render() {
    const { search } = this.state;
    const filteredCountries = countriesList.filter(country => {
      return country.name.toLowerCase().indexOf(search.toLowerCase()) !== -1;
    });
   

    return (
      <div className="flyout">
        <main style=>
          <div className="container">
            <div className="row">
             
              <div className="col">
                
                <Input
                  label="Search Country"
                  icon="search"
                  onChange={this.onchange}
                />
                
                
                <button onClick={this.handleClick}> Click to clear</button>
               
              </div>
              <div className="col" />
            </div>

            <div className="row">
            
              {filteredCountries.map(country => {
                return this.renderCountry(country);
              })} 
            </div>
          </div>
        </main>
        <Footer color="indigo">
          <p className="footer-copyright mb-0">
            &copy; {new Date().getFullYear()} Copyright
          </p>
        </Footer>
      </div>
    );
  }
}

export default App;

This is the countries.json format

[
  {
    "name": "Afghanistan",
    "code": "AF"
  },
  {
    "name": "Åland Islands",
    "code": "AX"
  },
  {
    "name": "Albania",
    "code": "AL"
  },
  {
    "name": "Algeria",
    "code": "DZ"
  },
  {
    "name": "American Samoa",
    "code": "AS"
  },
  {
    "name": "AndorrA",
    "code": "AD"
  },
  {
    "name": "Angola",
    "code": "AO"
  },
  
 



SwiftUI Checkbox Is Not Displaying The Check Mark When Clicked

I generate a dynamic checkbox list

struct ClaimStatusSearchView: View {

@ObservedObject var myObject = myObject ()

var body: some View {
    VStack(alignment:.leading, spacing:20) {
        Text("My Check Box List")
            .font(.system(size: 16))
            .bold()
            .foregroundColor(.black)
        ForEach(myObject.checkBoxList, id:\.id) { item in
            CheckboxField(
                id: item.checkboxDesc ,
                label: item.checkboxDesc ,
                callback: self.checkboxSelected
            )
        }
    }.padding(20)
    
}

But when I click on the checkbox, the checkmark is not displayed.

enter image description here




Bind angular mat-checbox ngModule

I have an Array of mat-checbkox, where user can only select one option:

export enum ProjectStatus {
  Ready = "Is ready",
  Testing = "is testing",
  Done = "is done"
}

<div *ngFor="let status of projectStatus; let i=index">
    <mat-checkbox [checked]="selected.index === i"
        (change)="selected.index = i; selected.status=status; selected.checked= true;">
    </mat-checkbox>
</div>

Then I got some others mat-checkbox:

<div>
    <mat-checkbox>SEND REPORTS</mat-checkbox>
</div>
<div>
    <mat-checkbox>WARN DEVELOPERS</mat-checkbox>
</div>
<div>
    <mat-checkbox>WARN PROJECT MAANGER</mat-checkbox>
</div>
<div>
    <mat-checkbox>WARN TESTERS</mat-checkbox>
</div>

My question is, how I can check another mat-checkbox dynamically based on the first checkbox list checked. I have to use ngModule?

For example, If I select:

is Testing

I want to check automatically the checkboxs:

SEND REPORTS
WARN DEVELOPERS

enter image description here

That's the link of the testing application: https://stackblitz.com/edit/angular-vrnk7t-bxeplb?file=src%2Fapp%2Fcheckbox-overview-example.html




jQuery slideToggle bug with checkbox

I am using slideToggle to show/hide some form elements, checkboxes in my case. When the slideToggle is triggered, the checkboxes are immediately rendered, then the slideUp/Down animation occurs. Has anyone encountered this problem and is there a solution?




mardi 26 janvier 2021

How to select single check box configurated with parent child relationship

string a='headsete' List ele=driver.findElements(By.xpath("//*[@id="rct-3YbUK0N"]/ol/li1/span/label/span1")); System.out.println(Integer.toString(ele.size())); for (i=0 i<=a i++) { el.click(); } using this lines unable to fix errors Aim: To select a child checkbox "Add eSeal Product"

enter image description here




Can't select chechbox with v-model in VueJS

I have a checkbox as a feature filter for a real estate agency site.

From the database comes the list of categories with their respective characteristics:

public function get_categories(Request $request)
{

    $categories = Category::with('features')->get();

    return response()->json([
        'validation' => true,
        'categories' => $categories
    ]);

}

In the Vue template, I have an accordion with UIKit.

I have one accordion header per category that I walk through using a v-for

Then inside the body of the accordion I have the checkboxes that correspond to the characteristics that belong to that category

<li 
    v-for="category in categories" 
    :key="category.id">
    
    <a 
        href="#" 
        class="uk-accordion-title">
        
    </a>

    <div class="uk-accordion-content">
        
        <div uk-grid>
            
            <div 
                class="uk-width-1-1 uk-margin-small"
                v-for="feature in category.features"
                :key="feature.id">
                
                <label>
                    
                    <input 
                        :id="'feature_' + feature.id"
                        class="uk-checkbox"
                        type="checkbox"
                        name="features" 
                        :value="feature.id"
                        v-model="features"
                        @change="filterUpdate"> <!-- ID hacer que este sea venga de la BD -->
                    
                        &nbsp; 

                </label>

            </div>

        </div>
        
    </div>

</li>

To load the categories of course I have a method that is responsible for making the request when creating the component

layoutLoadCategories() {

    axios.get('api/layout/get/categories').then( res => {

        this.categories = res.data.categories;

    });

},

The problem is that when I try to click on a checkbox, nothing happens. Not selected enter image description here




Python, KivyMD - Getting data from Checkboxes, Text input, there must be a better way

enter image description hereNew to programming (about 6 months) Trying to create a heavy equipment inspection form for my company. Everything is working but I am suspicious that there may be an easier way. I have a form with multiple check box groups, all my data is going into a dictionary with keys to the values. As you can see from my code, I have a lot of repetition already and once I finish the If statements for the check boxes my code will be very large and repetitive for extracting the data. Looking for some tips on this. In the KV file scroll down to the "tires" check boxes to see the id references for the if statments.

Thanks

PYTHON CODE

from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import StringProperty
from kivy.app import runTouchApp




class ContentNavigationDrawer(BoxLayout):
    screen_manager = ObjectProperty()
    nav_drawer = ObjectProperty()


class MainApp(MDApp):
    text = StringProperty('-.text')

    def build(self):
        self.theme_cls.primary_palette = 'Amber'
        self.theme_cls.theme_style = 'Dark'
        self.theme_cls.primary_hue = 'A700'
        return Builder.load_string(KV)

    def my_callback(self):
        mileage = self.root.ids.mileage.text
        hours = self.root.ids.hours.text
        comments = self.root.ids.comments.text
        if self.root.ids.a1.active is True:
            a1 = 1
        else:
            a1 = 0
        if self.root.ids.b1.active is True:
            b1 = 1
        else:
            b1 = 0
        data_out = dict()
        data_out['ac'] = comments
        data_out['aa'] = mileage
        data_out['ab'] = hours
        data_out['ad'] = a1
        data_out['ae'] = b1
        print(data_out)


MainApp().run()

Kivy Code

<Check_tires@MDCheckbox>:
    group: 'tires'
    size_hint: None, None
    size: "48dp", "48dp"   
<Check_breaks@MDCheckbox>:
    group: 'breaks'
    size_hint: None, None
    size: "48dp", "48dp"   
<Check_steering@MDCheckbox>:
    group: 'steering'
    size_hint: None, None
    size: "48dp", "48dp"   
<Check_undercarriage@MDCheckbox>:
    group: 'undercarriage'
    size_hint: None, None
    size: "48dp", "48dp"    
<Check_suspension@MDCheckbox>:
    group: 'suspension'
    size_hint: None, None
    size: "48dp", "48dp"
<Check_engine@MDCheckbox>:
    group: 'engine'
    size_hint: None, None
    size: "48dp", "48dp"
<Check_drive@MDCheckbox>:
    group: 'drive'
    size_hint: None, None
    size: "48dp", "48dp"
<Check_fuel@MDCheckbox>:
    group: 'fuel'
    size_hint: None, None
    size: "48dp", "48dp"
<Check_cooling@MDCheckbox>:
    group: 'cooling'
    size_hint: None, None
    size: "48dp", "48dp"
<Check_electrical@MDCheckbox>:
    group: 'electrical'
    size_hint: None, None
    size: "48dp", "48dp"
        
<ContentNavigationDrawer>:

    ScrollView:

        MDList:

            OneLineIconListItem:
                text: 'Inspection'
                on_press:
                    root.nav_drawer.set_state("close")
                    root.screen_manager.current = 'inspection'
                IconLeftWidget:
                    icon: 'file'

            OneLineIconListItem:
                text: 'Load Count'
                on_press:
                    root.nav_drawer.set_state('close')
                    root.screen_manager.current = 'loads'
                IconLeftWidget:
                    icon: 'counter'

            OneLineIconListItem:
                text: 'Map'
                on_press:
                    root.nav_drawer.set_state('close')
                    root.screen_manager.current = 'map'
                IconLeftWidget:
                    icon: 'map'

            OneLineIconListItem:
                text: "Settings"
                on_press:
                    root.nav_drawer.set_state("close")
                    root.screen_manager.current = "settings"
                IconLeftWidget:
                    icon: 'settings'
                    
            
Screen:

    MDToolbar:
        id: toolbar
        pos_hint: {"top": 1}
        elevation: 10
        title: "Menu"
        left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]

    NavigationLayout:
        x: toolbar.height

        ScreenManager:
            id: screen_manager

            Screen:
                name: "inspection"
                
                MDTextFieldRect:
                    id: hours
                    multiline: False
                    size_hint: 0.15, None
                    height: "30dp"
                    pos_hint: {'center_x': .92, 'center_y': .85}
                    on_text: app.my_callback()
                MDLabel:
                    text: "Hours"
                    pos_hint: {'center_x': 1.25, 'center_y': .85}
                    
                MDTextFieldRect:
                    id: mileage
                    multiline: False
                    size_hint: 0.15, None
                    height: "30dp"
                    pos_hint: {'center_x': .92, 'center_y': .8}
                    on_text: app.my_callback()
                MDLabel:
                    text: "Mileage"
                    pos_hint: {'center_x': 1.25, 'center_y': .8}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': 0.92, 'center_y': .75}
                MDLabel:
                    text: "Spill Kit"
                    pos_hint: {'center_x': 1.25, 'center_y': .75}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': 0.92, 'center_y': .7}
                MDLabel:
                    text: "360 Walk"
                    pos_hint: {'center_x': 1.25, 'center_y': .7}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': 0.92, 'center_y': .65}
                MDLabel:
                    text: "Radio Check"
                    pos_hint: {'center_x': 1.25, 'center_y': .65}
                    
                MDTextFieldRect:
                    id: comments
                    size_hint: 0.35, 0.41
                    height: "30dp"
                    pos_hint: {'center_x': .819, 'center_y': .37}
                    on_text: app.my_callback()
                MDLabel:
                    text: "Comments"
                    pos_hint: {'center_x': 1.145, 'center_y': .6}
                
                MDLabel:
                    text: "Inspection Item"
                    pos_hint: {'center_x': .6, 'center_y': .85}
                MDLabel:
                    text: "Good"
                    pos_hint: {'center_x': .775, 'center_y': .85}
                MDLabel:
                    text: "Repair"
                    pos_hint: {'center_x': .87, 'center_y': .85}
                MDLabel:
                    text: "Inoperable"
                    pos_hint: {'center_x': 0.955, 'center_y': .85}
                MDLabel:
                    text: "N/A"
                    pos_hint: {'center_x': 1.083, 'center_y': .85}
                                   
                Check_tires:
                    id: a1
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .8}
                Check_tires:
                    id: b1
                    pos_hint: {'center_x': .5, 'center_y': .8}
                Check_tires:
                    id: c1
                    pos_hint: {'center_x': .4, 'center_y': .8}
                Check_tires:
                    id:d1
                    pos_hint: {'center_x': .3, 'center_y': .8}
                MDLabel:
                    text: "Tires"
                    pos_hint: {'center_x': .6, 'center_y': .8}
                    
                Check_breaks:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .75}
                Check_breaks:
                    pos_hint: {'center_x': .5, 'center_y': .75}
                Check_breaks:
                    pos_hint: {'center_x': .4, 'center_y': .75}
                Check_breaks:
                    pos_hint: {'center_x': .3, 'center_y': .75}
                MDLabel:
                    text: "Brakes"
                    pos_hint: {'center_x': .6, 'center_y': .75}
                    
                Check_steering:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .7}
                Check_steering:
                    pos_hint: {'center_x': .5, 'center_y': .7}
                Check_steering:
                    pos_hint: {'center_x': .4, 'center_y': .7}
                Check_steering:
                    pos_hint: {'center_x': .3, 'center_y': .7}
                MDLabel:
                    text: "Steering"
                    pos_hint: {'center_x': .6, 'center_y': .7}
                    
                Check_undercarriage:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .65}
                Check_undercarriage:
                    pos_hint: {'center_x': .5, 'center_y': .65}
                Check_undercarriage:
                    pos_hint: {'center_x': .4, 'center_y': .65}
                Check_undercarriage:
                    pos_hint: {'center_x': .3, 'center_y': .65}
                MDLabel:
                    text: "Undercarriage"
                    pos_hint: {'center_x': .6, 'center_y': .65}
                    
                Check_suspension:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .6}
                Check_suspension:
                    pos_hint: {'center_x': .5, 'center_y': .6}
                Check_suspension:
                    pos_hint: {'center_x': .4, 'center_y': .6}
                Check_suspension:
                    pos_hint: {'center_x': .3, 'center_y': .6}
                MDLabel:
                    text: "Suspension"
                    pos_hint: {'center_x': .6, 'center_y': .6}
                
                Check_engine:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .55}
                Check_engine:
                    pos_hint: {'center_x': .5, 'center_y': .55}
                Check_engine:
                    pos_hint: {'center_x': .4, 'center_y': .55}
                Check_engine:
                    pos_hint: {'center_x': .3, 'center_y': .55}
                MDLabel:
                    text: "Engine"
                    pos_hint: {'center_x': .6, 'center_y': .55}
                    
                Check_drive:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .5}
                Check_drive:
                    pos_hint: {'center_x': .5, 'center_y': .5}
                Check_drive:
                    pos_hint: {'center_x': .4, 'center_y': .5}
                Check_drive:
                    pos_hint: {'center_x': .3, 'center_y': .5}
                MDLabel:
                    text: "Drive Train"
                    pos_hint: {'center_x': .6, 'center_y': .5}
                    
                Check_fuel:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .45}
                Check_fuel:
                    pos_hint: {'center_x': .5, 'center_y': .45}
                Check_fuel:
                    pos_hint: {'center_x': .4, 'center_y': .45}
                Check_fuel:
                    pos_hint: {'center_x': .3, 'center_y': .45}
                MDLabel:
                    text: "Fuel System"
                    pos_hint: {'center_x': .6, 'center_y': .45}
                    
                Check_cooling:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .4}
                Check_cooling:
                    pos_hint: {'center_x': .5, 'center_y': .4}
                Check_cooling:
                    pos_hint: {'center_x': .4, 'center_y': .4}
                Check_cooling:
                    pos_hint: {'center_x': .3, 'center_y': .4}
                MDLabel:
                    text: "Cooling System"
                    pos_hint: {'center_x': .6, 'center_y': .4}
                    
                Check_electrical:
                    active: True
                    pos_hint: {'center_x': .6, 'center_y': .35}
                Check_electrical:
                    pos_hint: {'center_x': .5, 'center_y': .35}
                Check_electrical:
                    pos_hint: {'center_x': .4, 'center_y': .35}
                Check_electrical:
                    pos_hint: {'center_x': .3, 'center_y': .35}
                MDLabel:
                    text: "Electrical System"
                    pos_hint: {'center_x': .6, 'center_y': .35}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .3}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .3}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .3}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .3}
                MDLabel:
                    text: "Exhaust System"
                    pos_hint: {'center_x': .6, 'center_y': .3}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .25}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .25}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .25}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .25}
                MDLabel:
                    text: "Hydraulic System"
                    pos_hint: {'center_x': .6, 'center_y': .25}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .2}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .2}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .2}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .2}
                MDLabel:
                    text: "Transmission"
                    pos_hint: {'center_x': .6, 'center_y': .2}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .15}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .15}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .15}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .15}
                MDLabel:
                    text: "Clutch"
                    pos_hint: {'center_x': .6, 'center_y': .15}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .1}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .1}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .1}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .1}
                MDLabel:
                    text: "Operator Controls"
                    pos_hint: {'center_x': .6, 'center_y': .1}
                    
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .6, 'center_y': .05}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .5, 'center_y': .05}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .4, 'center_y': .05}
                MDCheckbox:
                    size_hint: None, None
                    size: "48dp", "48dp"
                    pos_hint: {'center_x': .3, 'center_y': .05}
                MDLabel:
                    text: "Lights"
                    pos_hint: {'center_x': .6, 'center_y': .05}
                              
            Screen:
                name: "loads"
                
                MDFloatingActionButton:
                    icon: "minus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .1, 'center_y': .35}
                MDLabel:
                    text: "Till"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': .59, 'center_y': .8}
                MDLabel:
                    text: "0"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': .595, 'center_y': .5}               
                MDFloatingActionButton:
                    icon: "plus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .1, 'center_y': .65}
                    
                MDFloatingActionButton:
                    icon: "minus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .3, 'center_y': .35}
                MDLabel:
                    text: "CCR"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': .78, 'center_y': .8}
                MDLabel:
                    text: "0"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': .795, 'center_y': .5}               
                MDFloatingActionButton:
                    icon: "plus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .3, 'center_y': .65}
                    
                MDFloatingActionButton:
                    icon: "minus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .5, 'center_y': .35}
                MDLabel:
                    text: "Sub Base"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': 0.96, 'center_y': .8}
                MDLabel:
                    text: "0"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': .995, 'center_y': .5}               
                MDFloatingActionButton:
                    icon: "plus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .5, 'center_y': .65}
                    
                MDFloatingActionButton:
                    icon: "minus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .7, 'center_y': .35}
                MDLabel:
                    text: "Coarse Base"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': 1.15, 'center_y': .8}
                MDLabel:
                    text: "0"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': 1.195, 'center_y': .5}               
                MDFloatingActionButton:
                    icon: "plus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .7, 'center_y': .65}
                    
                MDFloatingActionButton:
                    icon: "minus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .9, 'center_y': .35}
                MDLabel:
                    text: "Waste"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': 1.37, 'center_y': .8}
                MDLabel:
                    text: "0"
                    md_bg_color: app.theme_cls.primary_color  
                    pos_hint: {'center_x': 1.395, 'center_y': .5}               
                MDFloatingActionButton:
                    icon: "plus"
                    md_bg_color: app.theme_cls.primary_color
                    pos_hint: {'center_x': .9, 'center_y': .65}

            Screen:
                name: "map"
                MDLabel:
                    text: "Map"
                    halign: "center"

            Screen:
                name: "settings"
                MDLabel:
                    text: "Settings"
                    halign: "center"

    MDNavigationDrawer:
        id: nav_drawer

        ContentNavigationDrawer:
            screen_manager: screen_manager
            nav_drawer: nav_drawer
'''



How o force the user to select a single checkbox with HTML? [duplicate]

I am creating a quiz in HTML. The questionnaire can be answered by selecting a checkbox. So far try this:

<h3>This is question 1?</h3>
<input type="radio" name="answer1" id="c01" value="0"/> answer A
<input type="radio" name="answer2" id="c02" value="0" /> answer B
<h3>This is question 2?</h3>
<input type="radio" name="answer3" id="c03" value="0"/> answer 1
<input type="radio" name="answer4" id="c04" value="0" /> answer 2
<input type="radio" name="answer5" id="c05" value="0"/> answer 3

However, the previous statement doesnt work because I only want to be possible to select one and only one answer (selecting more than one checkbox per answer is not allowed). How can I force the user to only select a single checkbox for each different question by only using html tags?




Freemarker how to select only true checkboxes?

Have following data passed from backend:

ALL_CONFIGS: {callDigitalIo=true, controllerId=1, numberPlatesHashSalt=..., numberPlatesShouldBeHashed=false, parkingStatusShouldBeChecked=true}

Where boolean params should be displayed like input element with type=checkbox.

Here is how I handle it on UI page (.ftl):

<div>
    <label class="col-form-label">
        Parking Status Should Be Checked:
        <input type="checkbox" class="form-check-input ml-2"
               id="parkingStatusShouldBeChecked" name="parkingStatusShouldBeChecked"
               <#if parkingStatusShouldBeChecked??>checked="checked"</#if>
        />
    </label>
</div>

However, checkboxes are all selected:

enter image description here

Number Plates Should be Hashed should not be selected.

How to select only true variables?




Freemarker how to display selected checkbox on UI page

Have following data passed from backend:

ALL_CONFIGS: {callDigitalIo=true, controllerId=1, numberPlatesHashSalt=..., numberPlatesShouldBeHashed=false, parkingStatusShouldBeChecked=true}

Where boolean params should be displayed like input element with type=checkbox.

Here is how I handle it on UI page (.ftl):

<div>
    <label class="col-form-label">
        Parking Status Should Be Checked:
        <input type="checkbox" class="form-check-input ml-2"
               id="parkingStatusShouldBeChecked" name="parkingStatusShouldBeChecked"
               <#if parkingStatusShouldBeChecked??>checked="checked"</#if>
        />
    </label>
</div>

However, checkboxes aren't selected:

enter image description here

Despite the fact that at Preview mode it is exactly selected!

Couldn't understand what is missed there?

How to solve this issue?




React change value of checkbox after 24 hours

I am creating a "smart shopping list", which sees how often I buy products and when I should buy next. At my current state, I want to keep the checkbox checked for 24 hours, so I am not able to uncheck it and it should be unchecked automatically after 24 hours (this is a criterion that I have to follow). How can I write something like setTimeout in my onChange function? I really could need some help here, thank you very much for responding.

Here is my code:

import React from 'react';
import firebase from '../lib/firebase';
import Nav from './Nav';
import { useCollectionData } from 'react-firebase-hooks/firestore';

const db = firebase.firestore().collection('shopping_list');

const ItemsList = () => {
  const userToken = localStorage.getItem('token');

  const [shoppingList, loading, error] = useCollectionData(
    db.where('token', '==', userToken),
    { idField: 'documentId' },
  );

  
  const markItemAsPurchased = (index) => {
    const { items, documentId } = shoppingList[0];
    const shoppingListObject = items[index];
    if (shoppingListObject.lastPurchasedOn !== null) {
      return;
    }
    shoppingListObject.lastPurchasedOn = Date.now();
    items[index] = shoppingListObject;
    db.doc(documentId)
      .update({
        items: items,
      })
      .then(() => console.log('Successfully updated item'))
      .catch((e) => console.log('error', e));
  };
  return (
    <div>
      <h1>Your Shopping List</h1>
      <div>
        {loading && <p>Loading...</p>}
        {error && <p>An error has occured...</p>}
        {shoppingList && !shoppingList.length && (
          <p>You haven't created a shopping list yet...</p>
        )}
        <ul>
          {shoppingList &&
            shoppingList[0] &&
            shoppingList[0].items.map((shoppingItemObject, index) => {
              return (
                <li key={shoppingItemObject.shoppingListItemName + index}>
                  <label>
                    {shoppingItemObject.shoppingListItemName}
                    <input
                      type="checkbox"
                      onChange={() => markItemAsPurchased(index)}
                      checked={
                        shoppingItemObject.lastPurchasedOn === null
                          ? false
                          : true
                      }
                    />
                  </label>
                </li>
              );
            })}
        </ul>
      </div>
      <Nav />
    </div>
  );
};

export default ItemsList;



How to link a slider and checkbox to a counter?

I am new in JavaScript. I am trying to link a slider and checkbox to a counter. The slider should increase the counter's value depending on the range. And then the checkboxes have fixes values that they should add to the counter if it is checked or not.

var slider = document.querySelector('#myRange');                               //Input
var output = document.querySelector("#value-range");                           //Output
let rangeValue = document.querySelector('#final-price');                       //Counter
const boxesContainer = document.querySelector('.price-boxes__container');      //Checkboxes

I created an event for the checkboxes, so when you click on it, adds the value.

boxesContainer.onchange = function(e) {
    if (e.target.classList.contains('checkbox')){
        const price = parseInt(e.target.getAttribute('value'))
        if (e.target.checked === true) {
            total += price;
        } else {
            total -= price;
        }
        rangeValue.innerHTML = total
    }
}

And I created another event for the slider as well.

slider.oninput = function () {
    let value = slider.value;
    userPrice(value)    
    output.style.left = (value/2.88);
    output.classList.add("show");
    rangeValue.innerHTML = prices[value-25];
       
    function userPrice (value) {
        if (value == 25) {
            output.innerHTML = '6 €p'
        } else {
            output.textContent = `${prices[value-25] - prices[value-26]} €p`;
        }
    }
}

The slider has min 25, max 1000, step = 1, value = 25. Each step is one user. I created an array that has the price depending on the slider's value. Between 26-50 users 6€ per user, 51-250 4€/p, 251-500 3€/p and 501-1000 2€/p. Therefore, I thought the easy way was to create an array and use the slider's value to sent the price to the counter.

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
let rangePrices = range(25, 1000, 1);

const prices = [];

rangePrices.forEach((rangeValue, i)=> {
    if(rangeValue === 25) {
        prices.push(299)
    } else if (rangeValue < 51) {
         prices.push(prices[i-1] + 6)
    } else if (rangeValue < 251){
        prices.push(prices[i-1] + 4)
    } else if (rangeValue < 501) {
        prices.push(prices[i-1] + 3)
    } else {
        prices.push(prices[i-1] + 2)
    }
});

But at the end, when I click on the checkboxes the counter adds the checkboxes' values, but it resets. I know that I have two rangeValue.innerHTML and is due to this that it does not work, but I do not know how to fix it...

It would be great if someone could help me!



keep the checkbox checked after refresh

I want to keep the list of checkboxes that I have checked when I refresh the page or move to another one.

This is my component.ts :

 isValidForm = false;
 public selectedActivityType: any[] = [];
 public assignmentFor: any = [{name :"Cause", id : "t1"}, {name: "Resulted damage", id:"t2"},{ name: "Emergency", id:"t3"}]
 constructor(){}
 ngOnInit(){}
selectActivityFor(event:any, option:any)
 {
  if ( event.target.checked )
   {
     this.selectedActivityType.push(option.id);
   }
 else{
    this.selectedActivityType.splice(this.selectedActivityType.indexOf(option.id),1);
  }    
 if(this.selectedActivityType.length >0 && 
(this.selectedActivityType.indexOf(this.assignmentFor[1].id) !== -1 || 
this.selectedActivityType.indexOf(this.assignmentFor[0].id) !== -1 ) )
 {
  this.isValidForm = true
}
else 
this.isValidForm = false;
 }

This is my component.html :

  <div *ngIf="assignmentFor.length !==0">
          <div class="container-fluid items-container" style="margin-top: 10px">
            <h5 class="mt-3" style="color : rgb(136,136,139); font-weight: bold">
              assignmentFor</h5>
            <div class="row">
              <div *ngFor="let option of assignmentFor; let i=index" class="animated cedfadeInUpX">
                <input type="checkbox" id="activityFor" (change)="selectActivityFor($event, option)" 
                 kendoCheckBox />
                <label class="k-checkbox-label"
                  style="padding-top:10px;margin-left:5px; padding-left:0;font-size: 14px; padding-right: 60px;"></label>
              </div>
            </div>
          </div>
        </div>



lundi 25 janvier 2021

Checkbox to control rangevalidator or maximum input double of textbox

I have a checkbox and the goal is to limit the maximum input value of a textbox when the checkbox is ticked.

I have two solutions in mind , one is to alter the value of the rangevalidator when the checkbox is ticked or the other is to restrict the value parsed into the textbox when the checkbox is ticked.

But my latter solution has an error as seen in the image below. While i don't know how to implement the former solution.

Code of the TextBox

<div class="d flex justify-content-start">
                    <div class="col-6 ">
                        Hours Spent
                            <asp:TextBox placeholder="Hours Spent *" Width="" ID="txtHoursSpent" runat="server" MaxLength="3"></asp:TextBox>
                        <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be greater than zero."
                            ValidationExpression="\d+" ControlToValidate="txtHoursSpent" MinimumValue="0.5" MaximumValue="12" Type="Double"></asp:RangeValidator>

                    </div>
                </div>

Code Of the CheckBox

<asp:CheckBox Text="Half-Day" runat="server" OnCheckedChanged="HalfDay_CheckedChanged" />

As you can see the error in the codebehind causes me to be unable to restrict the textbox to a certain range. Code Behind of the Checkbox

Does anyone know the solution perhaps?




input checkbox checked array function object error

it just doesn't error when i use only name=myCheckbox

function example(){
    
    var arr = $.map($('input[name=myCheckbox]:checkbox:checked'), function (e, i) {
        return +e.value;
    });
         return arr;
}

I need to use "id" in javascript. but I'm getting an error.

function example(id){
    
    var arr = $.map($('input[name=myCheckbox'+id+']:checkbox:checked'), function (e, i) {
        return +e.value;
    });
         return arr;
}

Uncaught Error: Syntax error, unrecognized expression: input[name=myCheckbox[object Object]]:checkbox:checked

How can I fix? Sorry my lang. Thank you..




The most optimal way to invert checkboxes in Google Script?

Because Google Script does not support radio buttons, I tried to created a workaround. Though I have learned the basics of Python, I'm new to Javascript/Google Sctipt. I finally got my code to work but I feel the result is far too clumsy for such a simple task. How to optimize it?

Here is the working sample: https://docs.google.com/spreadsheets/d/1bcMj3Yxewo4ZUgnhg0z46NyqJYBfxm-6ocvmEHLwtWE/edit?usp=sharing

And here's my code:

const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
function onEdit(e) {
  var invertedRange = { // C4:D5 is the range to follow
    top : 4,
    bottom : 5,
    left : 3,
    right : 4
  }
  var thisRow = e.range.getRow();
  var thisCol = e.range.getColumn();
 
  // Invert the checkboxes in the range
  if (thisRow <= invertedRange.bottom && thisRow >= invertedRange.top) {
    if (thisCol <= invertedRange.right && thisCol >= invertedRange.left) {
      var changeArray = ss.getRange(invertedRange.top, invertedRange.left, 2, 2).getValues();
      var invertedArray = [];
      var rPos = 0; // first row of the 2x2 matrix
      var valueToAdd = true;
      for (var readRow = invertedRange.top; readRow <= invertedRange.bottom; readRow = readRow + 1) {
        var cPos = 0; // first column of the 2x2 matrix
        var invertedPart = [];
        for (var readCol = invertedRange.left; readCol <= invertedRange.right; readCol = readCol + 1) {
          if (thisRow == readRow && thisCol == readCol) {
            var valueToAdd = changeArray[rPos][cPos]; // do not invert the checkbox that was already manually changed by user edit
          } else {
            var valueToAdd = !changeArray[rPos][cPos]; // invert all other checkboxes in the range
          }
          var invertedPart = invertedPart.concat(valueToAdd); // create an array from a pair of checkbox values
          cPos = cPos + 1;
        }
        invertedArray[rPos]=invertedPart; // add the pairs into an array
        rPos = rPos + 1;
      }
      ss.getRange(invertedRange.top, invertedRange.left, 2, 2).setValues(invertedArray); // set the chackbox values
    } return;
  }
}



Use of Faker in Laravel for dropdown and checkbox

i want to insert fake data into database and i have done for cities,price,names etc but i have stucked when i tried to Genrate fake data for dropdown type and checkboxes. how can i insert fake data to the database for these two types of input.




How to check all the items in objectlistview c#?

I am using Objectlistview in my WFA to create a chekedlistbox. I want to have a button called "Select all" that the user can click on it and all the rows are selected just by one click. I have been using the following code which works and all the checkboxes will be selected

 private void btnSelectallModule_Click(object sender, EventArgs e)
    {
        
        foreach (ListViewItem item in dataListView1.Items)
        {
            item.Checked = true;
        }

    }

The problem is that when I check all the items using this button then I hover over each item it will be unchecked automatically without even clicking on that item, which is so weird because I did not intend to do that in the code. Does anyone know what is going on and how can I fix this? Thanks




Checkbox in QToolbar

How can I add a checkbox to a QToolbar? You can add a QAction and setCheckable(true) on it, but that gives a toggle button rather than an actual checkbox.




Change another widget with a checkbox Flutter

I'm new to Flutter and I found a pretty cool design of a todoapp on Dribble so I wanted to create the app. Here's the design :

Design

I wonder how with the my callBack Function of my CheckBox I could change the color of the text part of the tile to this blue. My tile is currently a row containing a checkbox and a Container with the text in. So I would like to when i click on the checkbox, the background color of my container turns to blue. I dont' have a any idea how to do that. If you have some ideas please tell me.




Access CheckBox in DataGrid (WPF) autocomplete by Sql query

I have an empty DataGrid in a WPF interface. This DataGrid is automatically populated with the results of an SQL query and converts the Boolean values into the CheckBox within the DataGrid. How can I access these CheckBox from C# to capture when their status changes?

enter image description here

private static void RefreshPaths(DataGrid dataGridPaths, string connectionString) {
        string commandText = "SELECT * FROM dbo.Paths";
        using (SqlConnection connection = new SqlConnection(connectionString)) {
            SqlCommand command = new SqlCommand(commandText, connection);

            try {
                connection.Open();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, connection);
                DataTable dt = new DataTable();
                dataAdapter.Fill(dt);
                dataGridPaths.ItemsSource = dt.DefaultView; // DataGrid REFILL HERE
                connection.Close();
                dataAdapter.Dispose();
                connection.Dispose();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
                connection.Close();
                connection.Dispose();
            }
        }