mercredi 31 mai 2023

How to automatically check another checkbox when one checkbox is selected in p-treeTableCheckbox and p-tree of PrimeNG for Angular?

I have a problem with the PrimeNG library for Angular.

I am using p-treeTable + p-treeTableCheckbox to load checkbox corresponding with each item from the mock data json looks like this: enter image description here

Now I want when I check to checkbox, another checkbox auto-checked, For example when I check checkbox app 3, checkbox app 1 will be checked automatically.

I did it work in p-tree but it doesn't work in p-treeTable. I think it has already been selected but it does not show the checkbox. This is my stackblitz: https://stackblitz.com/edit/primeng-treetableselection-demo-9jfj9b?file=src%2Fapp%2Fapp.component.ts

Please help me, thanks a lot.




lundi 29 mai 2023

QML: two checkboxes in the same toolbar are overlapped - cannot set position

I have a toolbar with two checkboxes, which are correctly generated, but I cannot set their position, and so they are placed one on top of the other.

header : ToolBar {
    CheckBox {
       id: autoLoadButtonTB
       checked: true
       text: qsTr("Auto &Load")    //TODO 'L' should be underlined
       action: autoLoadAction
    }
    CheckBox {
       id: autoSaveButtonTB
       checked: true
       text: qsTr("&Auto Save")    //TODO 'A' should be underlined
       action: autoSaveAction
    }
}

Is it possible to have them one next to the other?




vendredi 26 mai 2023

Select checkbox and pick the correct row/rows

I want to create a return invoice. I insert the data from sql into a table in html/php. I want to select two products (for example rows 3 and 5) and js to make the correct calculation only for these products. At this moment, if I select rows 3 and 5, js does the calculations for the first two products. In fact, it takes my turn 1 and adds the next one. How can this be resolved?

$(document).ready(function() {
  $(document).on('click', '#checkAll', function() {
    $(".checkbox").prop("checked", this.checked);
  });

  $(document).on('change', function stornSelectedProducts() {
    var checkboxes = document.querySelectorAll('.checkbox');
    var count = 0;

    checkboxes.forEach(function(checkbox) {
      if (checkbox.checked) {
        count++;
        $('#total_item').val(count);
      }
    });
    cal_final_total(count);
  });
  update();

  function cal_final_total(count) {
    var final_item_total = 0;
    var final_total_vat = 0;
    var total_items_vat_0 = 0;

    for (j = 1; j <= count; j++) {
      var quantity = 0;
      var price = 0;
      var actual_amount = 0;
      var tax1_rate = 0;
      var tax1_amount = 0;
      var item_total = 0;
      quantity = $('#order_item_quantity' + j).val();
      if (quantity > 0) {
        price = $('#order_item_price' + j).val();
        if (price > 0) {
          actual_amount = parseFloat(quantity) * parseFloat(price);
          $('#order_item_actual_amount' + j).val(actual_amount);
          tax1_rate = $('#order_item_tax1_rate' + j).val();
          if (tax1_rate > 0) {
            tax1_amount = parseFloat(actual_amount) * parseFloat(tax1_rate) / 100;
            $('#order_item_tax1_amount' + j).val(tax1_amount);
          }

          total_vat_0 = parseFloat(actual_amount);
          total_items_vat_0 = parseFloat(total_items_vat_0) + parseFloat(total_vat_0);
          $('#order_item_actual_amount' + j).val(total_vat_0);

          total_vat = parseFloat(tax1_amount);
          final_total_vat = parseFloat(final_total_vat) + parseFloat(total_vat);
          $('#order_item_vat_amount' + j).val(total_vat);

          item_total = parseFloat(actual_amount) + parseFloat(tax1_amount);
          final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
          $('#order_item_final_amount' + j).val(item_total);
        }
      }
    }
    $('#final_total_amt').text(final_item_total);
    $('#final_total_amt_val').val(final_item_total);
    $('#total_amt_vat_val').val(final_total_vat);
    $('#total_amt_vat_0_val').val(total_items_vat_0);
  }

  $(document).on('blur', '.order_item_quantity', function() {
    cal_final_total(count);
  });

  $(document).on('blur', '.order_item_price', function() {
    cal_final_total(count);
  });

  $(document).on('blur', '.order_item_tax1_rate', function() {
    cal_final_total(count);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css">

  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js"></script>

</head>

<body>

  <div class="container-fluid">
    <table id="invoicetable" class="table table-bordered">
      <tr>
        <th width="7%">Sr No.</th>
        <th width="20%">Item Name</th>
        <th width="5%">Quantity</th>
        <th width="5%">Price</th>
        <th width="10%">Tax1</th>
        <th width="10%">Actual Amt.</th>
        <th width="10%">Total TAX</th>
        <th width="10%">Total</th>
        <th width="1%"><input id="checkAll" type="checkbox" </th>
      </tr>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>

      </tr>
      <tr>
        <td><span id="sr_no">1</span></td>
        <td><input type="text" value="Description 1" id="item_name1" class="form-control input-sm" /></td>
        <td><input type="text" value="7" id="order_item_quantity1" data-srno="1" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="4" id="order_item_price1" data-srno="1" readonly class="form-control order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate1" data-srno="1" readonly class="form-control order_item_tax1_rate" /></td>
        <td><input type="text" value="28" id="order_item_actual_amount1" data-srno="1" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="5.88" id="order_item_tax1_amount1" data-srno="1" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="33.88" id="order_item_final_amount1" data-srno="1" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count1" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
      <tr>
        <td><span id="sr_no">2</span></td>
        <td><input type="text" value="Description 2" id="item_name2" class="form-control input-sm" /></td>
        <td><input type="text" value="12" id="order_item_quantity2" data-srno="2" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="6" id="order_item_price2" data-srno="2" readonly class="form-control input-sm number_only order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate2" data-srno="2" readonly class="form-control input-sm number_only order_item_tax1_rate" /></td>
        <td><input type="text" value="72" id="order_item_actual_amount2" data-srno="2" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="15.12" id="order_item_tax1_amount2" data-srno="2" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="87.12" id="order_item_final_amount2" data-srno="2" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count2" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
      <tr>
        <td><span id="sr_no">3</span></td>
        <td><input type="text" value="Description 3" id="item_name3" class="form-control input-sm" /></td>
        <td><input type="text" value="2.5" id="order_item_quantity3" data-srno="3" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="14" id="order_item_price3" data-srno="3" readonly class="form-control input-sm number_only order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate3" data-srno="3" readonly class="form-control input-sm number_only order_item_tax1_rate" /></td>
        <td><input type="text" value="35" id="order_item_actual_amount3" data-srno="3" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="7.35" id="order_item_tax1_amount3" data-srno="3" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="42.35" id="order_item_final_amount3" data-srno="3" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count3" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
      <tr>
        <td><span id="sr_no">4</span></td>
        <td><input type="text" value="Description 4" id="item_name4" class="form-control input-sm" /></td>
        <td><input type="text" value="2" id="order_item_quantity4" data-srno="4" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="8.87" id="order_item_price4" data-srno="4" readonly class="form-control input-sm number_only order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate4" data-srno="4" readonly class="form-control input-sm number_only order_item_tax1_rate" /></td>
        <td><input type="text" value="17.74" id="order_item_actual_amount4" data-srno="4" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="3.72" id="order_item_tax1_amount4" data-srno="4" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="21.46" id="order_item_final_amount4" data-srno="4" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count4" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
      <tr>
        <td><span id="sr_no">5</span></td>
        <td><input type="text" value="Description 5" id="item_name5" class="form-control input-sm" /></td>
        <td><input type="text" value="9" id="order_item_quantity5" data-srno="5" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="7.87" id="order_item_price5" data-srno="5" readonly class="form-control input-sm number_only order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate5" data-srno="5" readonly class="form-control input-sm number_only order_item_tax1_rate" /></td>
        <td><input type="text" value="70.83" id="order_item_actual_amount5" data-srno="5" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="14.87" id="order_item_tax1_amount5" data-srno="5" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="85.70" id="order_item_final_amount5" data-srno="5" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count5" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
      <tr>
        <td><span id="sr_no">6</span></td>
        <td><input type="text" value="Description 6" id="item_name6" class="form-control input-sm" /></td>
        <td><input type="text" value="7" id="order_item_quantity6" data-srno="6" class="form-control input-sm order_item_quantity" /></td>
        <td><input type="text" value="7.54" id="order_item_price6" data-srno="6" readonly class="form-control input-sm number_only order_item_price" /></td>
        <td><input type="text" value="21" id="order_item_tax1_rate6" data-srno="6" readonly class="form-control input-sm number_only order_item_tax1_rate" /></td>
        <td><input type="text" value="52.78" id="order_item_actual_amount6" data-srno="6" class="form-control input-sm order_item_actual_amount" readonly /></td>
        <td><input type="text" value="11.08" id="order_item_tax1_amount6" data-srno="6" readonly class="form-control input-sm order_item_tax1_amount" /></td>
        <td><input type="text" value="63.86" id="order_item_final_amount6" data-srno="6" readonly class="form-control input-sm order_item_final_amount" /></td>
        <td align="center"><input class="checkbox" id="count6" type="checkbox" onChange="stornSelectedProducts()"></td>
      </tr>
    </table>

    <br>
    <br>

    <table class="table table-hover">
      <tr>
        <td width=50%><input type="text" class="form-control" value="Total without tax" readonly></td>
        <td width=50%><input type="text" value="0.00" class="form-control" value="0.00" id="total_amt_vat_0_val" readonly></td>
      </tr>
      <tr>
        <td width=50%><input type="text" class="form-control" value="Tax" readonly></td>
        <td width=50%><input type="text" value="0.00" class="form-control" value="0.00" id="total_amt_vat_val" readonly></td>
      </tr>
      <tr>
        <td width=50%><input type="text" class="form-control" value="Total with tax" readonly></td>
        <td width=50%><input type="text" class="form-control" value="0.00" id="final_total_amt_val" readonly></td>
      </tr>
      <tr>
      </tr>
    </table>
  </div>
</body>

</html>



jeudi 25 mai 2023

Add multiple checkboxes in shiny datatable and retrieve it's value

I added multiple checkbox columns (check1, check2) to the datatable. I have corresponding table with bool1 and bool2 that I want to update based on the reactives for the checkboxes. I am able to retrieve the data for check1 only. I need to update the callback function to take in both check1 and check2 columns but I am not too familiar with JS. Need help figuring this out.

library(shiny)
library(DT)

ui <- fluidPage(
  br(),
  fluidRow(
    column(
      6,
      DTOutput("dtable")
    ),
    column(
      6,
      verbatimTextOutput("reactiveDF")
    )
  )
)

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
  }
  inputs
}

dat0 <- data.frame(
  fruit  = c("apple", "cherry", "pineapple", "pear"),
  letter = c("a", "b", "c", "d")
)

dat1 <- cbind(dat0, bool1 = FALSE, bool2 = FALSE)

dat2 <- cbind(
  dat0,
  check1 = shinyInput(checkboxInput, nrow(dat0), "checkb"),
  check2 = shinyInput(checkboxInput, nrow(dat0), "checkc")
)

js <- c(
  "$('[id^=checkb]').on('click', function(){",
  "  var id = this.getAttribute('id');",
  "  var i = parseInt(/checkb(\\d+)/.exec(id)[1]);",
  "  var value = $(this).prop('checked');",
  "  var info = [{row: i, col: 3, value: value}];",
  "  Shiny.setInputValue('dtable_cell_edit:DT.cellInfo', info);",
  "})"
)

server <- function(input, output, session) {

  Dat <- reactiveVal(dat1)

  output[["dtable"]] <- renderDT({
    datatable(
      dat2,
      rownames = TRUE,
      escape = FALSE,
      editable = list(target = "cell", disable = list(columns = c(3,4))),
      selection = "none",
      callback = JS(js)
    )
  }, server = FALSE)

  observeEvent(input[["dtable_cell_edit"]], {
    info <- input[["dtable_cell_edit"]] # this input contains the info of the edit
    print(info)
    Dat(editData(Dat(), info))
  })

  output[["reactiveDF"]] <- renderPrint({
    Dat()
  })

}

shinyApp(ui, server)



mercredi 24 mai 2023

Select checkbox and update return invoice

I want to create a return invoice. I take the data from sql, and I have the possibility to change the quantity of each product that I want to return. In the image you can see that I selected record 2 and 4, but the script takes the first 2 records in ascending order and does the calculation for me.

I leave the script in php and js below, so you can help me correct it. I want to understand what I didn't do well.

cal_final_total(count) is for calculate quantity price and tax

Thank you in advance for the answers.

enter image description here

$(document).on('change', function stornSelectedProducts() {
  var checkboxes = document.querySelectorAll('.checkbox');
  var count = 0;

  checkboxes.forEach(function(checkbox) {
    if (checkbox.checked) {
      count++;
      $('#total_item').val(count);
    }
  });
  cal_final_total(count);
});
update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover">
  <thead>
    <tr>
      <th width="1%">#</th>
      <th width="10%">Product code</th>
      <th width="40%">Description <span class="text-danger font-weight-bold">*</span></th>
      <th width="6%">Unit <span class="text-danger font-weight-bold">*</span></th>
      <th width="10%">QTY<span class="text-danger font-weight-bold">*</span></th>
      <th width="8%">Price <span class="text-danger font-weight-bold">*</span></th>
      <th width="8%">Price without VAT</th>
      <th width="8%">VAT</th>
      <th width="10%">Total with VAT</th>
      <th align="center"><input id="checkAll" class="form-control" type="checkbox" </th>
    </tr>
  </thead>
  @php($count = 0) @foreach($invoice as $row) @php($count++)
  <tbody>
    <tr>
      <td><span id=""></span></td>
      <td><input type="text" value="" name="item_product_code[]" id="item_product_code" class="form-control" readonly></td>
      <td><input type="text" value="" name="item_description[]" id="item_description" class="form-control" readonly></td>
      <td><input type="text" value="" name="item_unit[]" id="item_unit" class="form-control" readonly></td>
      <td><input type="text" value="" name="item_quantity[]" id="item_quantity" class="form-control"></td>
      <td><input type="text" value="" name="item_rate[]" id="item_rate" class="form-control" readonly></td>
      <td><input type="text" value="" name="item_actual_amount[]" id="item_actual_amount" class="form-control" data-srno="" readonly></td>
      <td><input type="text" value="" name="item_vat_amount[]" id="item_vat_amount" class="form-control" data-srno="" readonly></td>
      <td><input type="text" value="" name="item_final_amount[]" id="item_final_amount" class="form-control" data-srno="" readonly></td>
      <td align="center"><input class="checkbox" id="" type="checkbox" onChange="stornSelectedProducts()"></th>
    </tr>
  </tbody>
  @endforeach
</table>

<div class="row">
  <div class="col-xl-8 col-md-6 col-sm-6">
  </div>
  <div class="col-xl-4 col-md-6 col-sm-6">
    <table class="table table-hover">
      <tr>
        <td width=50%><input type="text" class="form-control" value="Total without VAT" readonly></td>
        <td width=50%><input type="text" name="total_amt_vat_0_val" class="form-control" value="0.00" id="total_amt_vat_0_val" readonly></td>
      </tr>
      <tr>
        <td width=50%><input type="text" class="form-control" value="VAT" readonly></td>
        <td width=50%><input type="text" name="total_amt_vat_val" class="form-control" value="0.00" id="total_amt_vat_val" readonly></td>
      </tr>
      <tr>
        <td width=50%><input type="text" class="form-control" value="Total with VAT" readonly></td>
        <td width=50%><input type="text" name="total_amt_val" class="form-control" value="0.00" id="total_amt_val" readonly></td>
      </tr>
      <tr>
      </tr>
    </table>
  </div>
</div>



How to correctly set mat-checkbox values in formArray, reading saved data from API and having default value (false) for new formArray elements?

I'm working on a mat-stepper structure, in order to create the entity "Rental Contracts". I can create a new rental contract starting from zero, or open a saved draft and continue filling data and saving it to the database usinn entity framework API's.

One rental contract can refer to n vehicles, that the customer will use during the contract validity period.

Each vehicle is represented in a formArray element. Each vehicle can be owned by the rental house, or subleased, and have a number of properties to be filled by the user. Almost all these properties are working well, except the checkbox.

I've created a mat-checkbox to show if the selected machine is subleased or not. I need three different behaviours:

  1. When I create an empty element for the formArray, I need to set "false" value to the checkbox.
  2. Once the user selects a machine code, the system checks if it is subleased, and sets the checkbox selection to "true" ("or "false" otherwise).
  3. If I loaded data from draft, the checkbox needs to be set depending on what I previously saved on the db.

If I use formControl name, I am not able to manage values coming from API. If I use ngModel, I can read from DB but formArray does not work properly when I add a new element to it.

What I need is to understand how to configure my formArray element in order to get working all of the needed behaviours.

My form looks like this:

enter image description here

Here is my "mixed" code (I have tried several changes and commented some code that was not working):

component.ts:

[...]
  vehiclesForm = new FormGroup({
    stocks: new FormArray([])
  });

[...]
  ngOnInit(): void {
    this.vehiclesForm = this.formBuilder.group({
      stocks: this.formBuilder.array([])
    });
  }

  loadData(contractData: any) {
    this.contractData = contractData;
    //console.log('contract-vehicles - contractData', contractData);
    this.getAllBuildingSitesByCustomerId(contractData.customerId);
    this.rentalTypeId = contractData.rentalTypeId;
    this.secondRentalTypeId = contractData.secondRentalTypeId;
    //console.log("this.contractData.rentalStocks", this.contractData.rentalStocks);

    if ((<FormArray>this.vehiclesForm.get("stocks")).length === 0) {
      if (this.contractData.rentalStocks != null && this.contractData.rentalStocks?.length > 0) {

        this.getRentalStocksDetail(this.contractData.rentalStocks).subscribe(
          (stockResults) => {
            this.contractData.rentalStocks.forEach((rentalStock, index) => {
              const stock = stockResults[index];
              const stockIdControl = new FormControl(stock, autocompleteObjectValidator());
              this.filteredStocks[index] = stockIdControl.valueChanges.pipe(
                debounceTime(300),
                switchMap((value) => this.getStocks(value, index))
              );
              this.addStockToFormArray(rentalStock, stockIdControl);
              this.onStockSelectionChange(stock, index);
            });
          },
          (err) => {
            console.log("contract-vehicles.component: getRentalStocksDetail:", err);
          },
        );
      } else {
        this.addNewStockToFormArray();
      }
    }
  }

  getRentalStocksDetail(stocks: any[]): Observable<any[]> {
    let calls = [];
    stocks.forEach(stock => { calls.push(this.stockService.getStock(stock.stockId, true)); });
    return forkJoin(calls);
  }

  getControls() {
    //console.log("<FormArray>this.vehiclesForm.get('stocks')).controls",(<FormArray>this.vehiclesForm.get("stocks")).controls);
    return (<FormArray>this.vehiclesForm['controls'].stocks['controls']);
  }

  getStocks(filter: any, index: number): Observable<any[]> {
    if (filter?.length < 2 || typeof filter !== 'string') {
      return of([]);
    }

    this.queryStock.find = filter;
    this.queryStock.startDate = moment(((<FormGroup>(<FormArray>this.vehiclesForm.get("stocks")).controls[index])).controls.startDate.value).format('YYYY-MM-DDT00:00:00');
    this.queryStock.endDate = moment(((<FormGroup>(<FormArray>this.vehiclesForm.get("stocks")).controls[index])).controls.endDate.value).format('YYYY-MM-DDT23:59:59');
    return this.rentalStockService.getAvailableRentalStocks(this.queryStock).pipe(
      map((response) => response),
      tap((response: any[]) => {
        return response.sort((a, b) => {
          if (a.ownerRef === b.ownerRef) {
            return a.registrationNumber < b.registrationNumber ? -1 : 1
          } else {
            return a.ownerRef < b.ownerRef ? -1 : 1
          }
        });
      })
    );
  }

  displayStock(stock: any): string {
    var desc: string;
    if (stock && stock.id) {
      desc = stock.registrationNumber;
      //console.log("stock.ownerRef", stock.ownerRef);
      if (stock.ownerRef) {
        desc = stock.ownerRef + ' - ' + desc;
      }
    }
    return desc;
  }

  addNewStockToFormArray() {
    if (!(<FormArray>this.vehiclesForm.get('stocks')).valid) {
      return;
    }
    const formLength = (<FormArray>this.vehiclesForm.get('stocks')).length;
    const stockIdControl = new FormControl(null, autocompleteObjectValidator());
    this.filteredStocks[formLength] = stockIdControl.valueChanges.pipe(
      debounceTime(300),
      switchMap((value) => this.getStocks(value, formLength))
    );
    this.addStockToFormArray(null, stockIdControl);
  }

  public addStockToFormArray(rentalStock: any, stockControl: FormControl) {
    console.log("rentalStock", rentalStock);
    console.log("subleased", rentalStock?.subleased);
    const checkDefaultValues = <FormGroup>(<FormArray>this.vehiclesForm.get("stocks")).controls[0];
    (<FormArray>this.vehiclesForm.get("stocks")).push(
      new FormGroup({
        stockId: new FormControl(rentalStock ? rentalStock.id : 0),
        startDate: new FormControl(rentalStock?.startDate ?? this.contractData.startDate),
        endDate: new FormControl(rentalStock?.endDate ?? this.contractData.expiryDate),
        stock: stockControl,
        //subleased: new FormControl({value: rentalStock ? rentalStock.subleased : false, disabled: true}),
      })
    );
  }

  onStockSelectionChange(myStock: any, j: number, fromUI: boolean = false) {
    console.log("onStockSelectionChange", fromUI);
    let formArray = (<FormArray>this.vehiclesForm.get("stocks")).controls;
    formArray[j].get('stockId').setValue(myStock.id);
    //formArray[j].get('subleased').setValue(myStock.subleased);
    if (fromUI) {
      this.contractData.rentalStocks[j].subleased = myStock.subleased;
    }
  }

HTML:

<form [formGroup]="vehiclesForm">
    <table style="width: 50%;">
        <thead>
            <tr>
                <th style="text-align: center;">StartDate</th>
                <th style="text-align: center;">EndDate</th>
                <th style="text-align: center;">Stock</th>
                <th style="text-align: center;">Subleased</th>
                <th style="text-align: center;">Delete</th>
            </tr>
        </thead>
        <tbody formArrayName="stocks">
            <tr *ngFor="let stock of getControls(); let i = index" [formGroupName]="i">
                <!-- Start Date -->
                <td style="text-align: center;">
                    <div class="hidden">
                        <input type="text" class="form-control" formControlName="stockId">
                    </div>
                    <mat-form-field appearance="outline" class="field-width-120 w-100-p mb-12">
                        <mat-label></mat-label>
                        <input matInput [matDatepicker]="startDatePicker"
                            formControlName="startDate"
                            [min]="contractData.startDate" [max]="contractData.expiryDate">
                        <mat-datepicker-toggle matSuffix [for]="startDatePicker">
                        </mat-datepicker-toggle>
                        <mat-datepicker #startDatePicker></mat-datepicker>
                    </mat-form-field>
                </td>
                <!-- End Date -->
                <td style="text-align: center;">
                    <mat-form-field appearance="outline" class="field-width-120 w-100-p mb-12">
                        <mat-label></mat-label>
                        <input matInput [matDatepicker]="endDatePicker"
                            formControlName="endDate"
                            [min]="contractData.startDate" [max]="contractData.expiryDate">
                        <mat-datepicker-toggle matSuffix [for]="endDatePicker">
                        </mat-datepicker-toggle>
                        <mat-datepicker #endDatePicker></mat-datepicker>
                    </mat-form-field>
                </td>
                <!-- Stock -->
                <td style="text-align: center;">
                    <mat-form-field appearance="outline" class="field-width-stock w-100-p mb-12">
                        <mat-label></mat-label>
                        <input matInput formControlName="stock" [value]="stock"
                            [matAutocomplete]="autoStock" type="text" autocomplete="off">
                        <mat-autocomplete #autoStock="matAutocomplete" [displayWith]="displayStock">
                            <mat-option *ngFor="let myStock of filteredStocks[i] | async"
                                [value]="myStock" (onSelectionChange)="onStockSelectionChange(myStock, i, true)">
                                
                            </mat-option>
                        </mat-autocomplete>
                    </mat-form-field>
                </td>
                <!-- Subleased -->
                <td style="vertical-align: initial; text-align: center;">
                    <mat-checkbox class="h5" [ngModel]="contractData.rentalStocks[i]?.subleased" [ngModelOptions]="{standalone: true}" disabled></mat-checkbox>
                </td>
                <!-- Delete -->
                <td style="vertical-align: initial; text-align: center;">
                    <button mat-icon-button color="warn"
                        (click)="onDeleteItem(i); $event.preventDefault()">
                        <mat-icon>delete</mat-icon>
                    </button>
                </td>
            </tr>
            <tr>
                <button mat-raised-button class="header-button mt-24 mt-md-0"
                    (click)="addNewStockToFormArray(); $event.preventDefault()">
                    <mat-icon>add</mat-icon>
                </button>
            </tr>
        </tbody>
    </table>
</form>

Any suggestion/help will be much appreciated!

Many thanks and best regards,

Laura




Angular - How to use value from multiple checkboxes

How can I receive only checked values ​​in one variable?

<input type="checkbox" id="check-4" name="checkbox" value="1">
<label for="check-4"><span>1</span></label>

<input type="checkbox" id="check-4" name="checkbox" value="2">
<label for="check-4"><span>2</span></label>

<input type="checkbox" id="check-4" name="checkbox" value="3">
<label for="check-4"><span>3</span></label>

If I checked values: 1,2

let temp = [1,2]



mardi 23 mai 2023

Set an onChange for checkbox in React?

I'm trying to update a record by selecting a checkbox when a book has been read. Whenever I refresh the page, the checkbox returns as unchecked. How can I store the selected checkbox and see it checked after the page is refreshed? Thanks in advance!

import React, { useState } from 'react';
import axios from 'axios';

const Book = ( {title, author, id, getBooks}) => {
  const [finished, setFinished] = useState(false)

  const handleChange = async (e) => {
    const { name, value } = e.target;

    await axios.put(`http://localhost:3000/api/v1/books/${id}`, {
        book: {
          [name]: value,
          finished: !finished
        },
      })
  };

  return (
    <tr>
      <td>
        <input
          type="text"
          name="title"
          defaultValue={title}
          onChange={handleChange}
          className="form-control"
        />
      </td>
      <td>
        <input
          type="text"
          name="author"
          defaultValue={author}
          onChange={handleChange}
          className="form-control"
        />
      </td>
      <td className="text-center">
        <div className="form-check form-check-inline pt-2">
          <input
            type="checkbox"
            name="finished"
            defaultChecked={finished}
            className="form-check-input"
            onChange={() => setFinished(!finished)}
          />
          <label className="form-check-label">
            Done
          </label>
        </div>
      </td>
    </tr>
  )
}

export default Book



why aria-checked attribute got disappeared

"aria-checked" attribute got disappeared after deployment, while it was existing when testing.

I was expecting aria-checked attribute to exist for the element. The same issue is in Firefox and Chrome. Kindly advise. My intention here is to know if the checkbox is checked or not and based on it, need to check it or uncheck based on some other conditions. Thank you.




Is there a way to create Radiobuttons in kivy via a loop with a dictionary and get the choosen value somewhere?

I'm trying to create an app with the code of an old tkinter program of mine. I use kivy for this, but because I never worked with it, I'm totally lost at some points. My question is, if it is possible to create radiobuttons (via Checkbox) by a loop with a dictionary just as I can do with tkinter?

sprachen = {"erste_sprache": 1, "zweite_sprache": 2, "dritte_sprache": 3, "vierte_sprache":4, "fünfte_sprache":5}
ausgewaehlt = tk.StringVar()
for einzelwert in sprachen:
    radiob = tk.Radiobutton(gruppeauswahl, text=einzelwert, value=einzelwert, variable=ausgewaehlt)
    #print("hier")
    radiob.grid(sticky = "w")
ausgewaehlt.set("erste_sprache")

I tried to just use checkbox. I got Radiobuttons via grouping. But the whole thing didn't work, because first I can't set a text, value and variable to this and second it doesn't want to create Checkboxes out of a dictionary.




lundi 22 mai 2023

Javascript check a checkbox on page load [duplicate]

I have a form which includes a trio of checkboxes:

<input class="hs-input" type="checkbox" name="products_required" value="ProductOne">
<input class="hs-input" type="checkbox" name="products_required" value="ProductTwo">
<input class="hs-input" type="checkbox" name="products_required" value="ProductThree">

Depending on which product landingpage the user has been just before getting to the form page determines which checkbox is pre-selected. So for example if I am ProductOne landingpage and go to the form page, the ProductOne checkbox will be pre-selected.

So Im trying to isolate the ProductOne checkbox which I can only do via the value attribute and simply set it to checked:

  const checkboxSelect = document.querySelectorAll("input[type='checkbox'][value='ProductOne']");
  checkboxSelect.checked = true;

But when I test this not only isnt the checkbox selected, but I see no errors in my console. So I think I've clearly missed something?




R Shiny checkboxInput automatically selected based on ondition

I have a datatable in Shiny where I want to insert a column with checkboxes. This works also so far without problems.
However, these checkboxes should be selected automatically when a certain condition is met. I have used the iris dataset as an example and would like to set a mark in the respective checkbox if the value in Sepal.Length is greater than 5.
With my current approach, all checkboxes are selected and unfortunately not only those that meet the condition.
Can anyone help me with my problem?

library(tidyverse)
library(shiny)
library(DT)

shinyInput<-function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label=NULL, ...))
  }
  inputs
}

ui <- fluidPage(

  dataTableOutput("table")
  
)

server <- function(input, output) {

  table1 <- iris %>% 
    mutate(Check = shinyInput(checkboxInput, nrow(iris), 'check1', value = ifelse(Sepal.Length >= 5, TRUE, FALSE)))
  
  output$table <- renderDataTable({
    DT::datatable({table1},
                  escape = F)
  })
    
}

shinyApp(ui = ui, server = server)

Current output:

enter image description here

Desired output:

enter image description here




samedi 20 mai 2023

Django get id of the selected checkbox on CheckboxSelectMultiple widget in Javascript

I have checkboxes in Django from a form :

testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple())

I would like to return only the ID (and then the value) of the last selected checkbox on .change event only when it's checked (when it's unchecked I don't want anything to happen).

I managed to do so with the following (thanks to this answer) :

Django How to get value of CheckboxSelectMultiple in Javascript in Template

$('#id_testrever_0').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_0').is(':checked')) {
        testrever = $('#id_testrever_0').val();
        $("input[name=email]").val(a + testrever)
    }
})
    $('#id_testrever_1').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_1').is(':checked')) {
        testrever = $('#id_testrever_1').val();
        $("input[name=email]").val(a + testrever)
    }
})

But I would like to achieve it in a more elegant way to minimise the code lenght and avoid the repetitions.

maybe by using

$("input:checkbox[name=testrever]").on("change", function() 

  $("input:checkbox[name=testrever]:checked").each(function()

if it's possible.




How to move the specific table row's data to another table once the checkbox on the same row is checked?

I have a table and for the first column, I have a checkbox for each row. How can I make it so that once the checkbox is checked, all of the data that belongs to the same row as the checkbox is moved to another table(which is on another frame)?

This is my first time here so I don't know if I'm doing this right but I'll be super grateful if anyone answers. Thank you.

I tried using an ActionListener for the checkbox but it didn't work or maybe I just did not do it right. This is my first time trying to create a system as a self learner so please bear with me.

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
    if (txtTask.getText().equals("") || txtSubject.getText().equals("") || txtDeadline.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Enter all necessary data.");
    } else {
        String task = txtTask.getText();
        String subject = txtSubject.getText();
        String deadline = txtDeadline.getText();

        DefaultTableModel model = (DefaultTableModel) tableTasks.getModel();
        model.addRow(new Object[] { false, task, subject, deadline, false });

        JOptionPane.showMessageDialog(this, "New task has been added to the list . . . !");
        txtTask.setText("");
        txtSubject.setText("");
        txtDeadline.setText("");

        int lastRowIndex = model.getRowCount() - 1;
        Boolean isChecked = (Boolean) model.getValueAt(lastRowIndex, 0);
        if (isChecked) {
            Object[] rowData = new Object[tasksModel.getColumnCount()];
            for (int col = 0; col < tasksModel.getColumnCount(); col++) {
                rowData[col] = tasksModel.getValueAt(lastRowIndex, col);
            }
            finishedTasksModel.addRow(rowData);
            tasksModel.removeRow(lastRowIndex);
        }
    }
}



How to add quantity button to checkbox in Java Swing

``/*

  • Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
  • Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */

import javax.swing.*; import java.text.DecimalFormat;

/** *

  • @author arnavgupta */ public class NewJFrame extends javax.swing.JFrame {

    /**

    • Creates new form NewJFrame */ public NewJFrame() { initComponents(); }

    /**

    • This method is called from within the constructor to initialize the form.

    • WARNING: Do NOT modify this code. The content of this method is always

    • regenerated by the Form Editor. */ @SuppressWarnings("unchecked") //
      private void initComponents() {

      jLabel1 = new javax.swing.JLabel(); Cricket = new javax.swing.JCheckBox(); Rugby = new javax.swing.JCheckBox(); Food = new javax.swing.JCheckBox(); Mac = new javax.swing.JCheckBox(); PC = new javax.swing.JCheckBox(); Bench = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); SubTotal = new javax.swing.JTextPane(); jScrollPane2 = new javax.swing.JScrollPane(); Tax = new javax.swing.JTextPane(); jScrollPane3 = new javax.swing.JScrollPane(); Total = new javax.swing.JTextPane(); SubtotalLabel = new javax.swing.JLabel(); TaxLabel = new javax.swing.JLabel(); TotalLabel = new javax.swing.JLabel(); Calc = new javax.swing.JButton(); Clear = new javax.swing.JButton(); Exit = new javax.swing.JButton();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      jLabel1.setFont(new java.awt.Font("Kailasa", 1, 24)); // NOI18N jLabel1.setText("Sanjay's Goods");

      Cricket.setText("Cricket Bat $400"); Cricket.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CricketActionPerformed(evt); } });

      Rugby.setText("Rugby Ball $40"); Rugby.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RugbyActionPerformed(evt); } });

      Food.setText("Masala Dosa $19"); Food.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FoodActionPerformed(evt); } });

      Mac.setText("Brand New Macbook pro $1"); Mac.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { MacActionPerformed(evt); } });

      PC.setText("30 Year old PC $500"); PC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PCActionPerformed(evt); } });

      Bench.setText("Bench Press with weights $100");

      jScrollPane1.setViewportView(SubTotal);

      jScrollPane2.setViewportView(Tax);

      jScrollPane3.setViewportView(Total);

      SubtotalLabel.setText("Subtotal");

      TaxLabel.setText("Tax");

      TotalLabel.setText("Total");

      Calc.setText("Calculate"); Calc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CalcActionPerformed(evt); } });

      Clear.setText("Clear"); Clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearActionPerformed(evt); } });

      Exit.setText("Exit"); Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExitActionPerformed(evt); } });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Exit) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(93, 93, 93) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TotalLabel) .addComponent(TaxLabel)) .addGap(74, 74, 74)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(SubtotalLabel) .addGap(66, 66, 66))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2) .addComponent(jScrollPane1) .addComponent(jScrollPane3)))) .addGap(112, 112, 112)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(106, 106, 106)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Rugby) .addComponent(Food) .addComponent(Cricket)) .addGap(123, 123, 123) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Mac) .addComponent(Bench) .addComponent(PC))) .addGroup(layout.createSequentialGroup() .addGap(62, 62, 62) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Clear) .addComponent(Calc)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Cricket) .addComponent(Mac)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Rugby) .addComponent(PC)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Food) .addComponent(Bench)) .addGap(54, 54, 54) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(SubtotalLabel) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TaxLabel) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(11, 11, 11) .addComponent(Calc) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Clear) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(TotalLabel) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13) .addComponent(Exit) .addGap(18, 18, 18)) );

      pack(); }//

    private void CricketActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void RugbyActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

    private void MacActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

    private void PCActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

    private void CalcActionPerformed(java.awt.event.ActionEvent evt) { DecimalFormat df = new DecimalFormat("0.00"); double total; double subtotal = 0; double tax; double taxrate = .08;

     if (Cricket.isSelected()){
         subtotal = subtotal + 400;
     }
     if (Rugby.isSelected()){
         subtotal = subtotal + 40;
     }
     if (Food.isSelected()){
         subtotal = subtotal + 19;
     }
    
     if (Mac.isSelected()){
         subtotal = subtotal + 1;
     }
    
     if (PC.isSelected()){
         subtotal = subtotal + 500;
     }
    
     if (Bench.isSelected()){
         subtotal = subtotal + 100;
     }
    
     SubTotal.setEditable(false);
     Tax.setEditable(false);
     Total.setEditable(false);
     SubTotal.setText(Double.toString(subtotal));
     subtotal = Double.parseDouble(SubTotal.getText());
     tax = subtotal * taxrate;
     total = tax + subtotal;
     Tax.setText(Double.toString(tax));
     Total.setText(Double.toString(total));
    
     Tax.setText(df.format(tax));
     SubTotal.setText(df.format(subtotal));
     Total.setText(df.format(total));
    

    }

    private void ClearActionPerformed(java.awt.event.ActionEvent evt) { Cricket.setSelected(false); Rugby.setSelected(false); Food.setSelected(false); Mac.setSelected(false); PC.setSelected(false); Bench.setSelected(false); SubTotal.setText(" "); Tax.setText(" "); Total.setText(" "); }

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }

    private void FoodActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }

    /**

    • @param args the command line arguments / public static void main(String args[]) { / Set the Nimbus look and feel / // / If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //

      /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); }

    // Variables declaration - do not modify private javax.swing.JCheckBox Bench; private javax.swing.JButton Calc; private javax.swing.JButton Clear; private JCheckBox Cricket; private javax.swing.JButton Exit; private JCheckBox Food; private javax.swing.JCheckBox Mac; private javax.swing.JCheckBox PC; private JCheckBox Rugby; private javax.swing.JTextPane SubTotal; private javax.swing.JLabel SubtotalLabel; private javax.swing.JTextPane Tax; private javax.swing.JLabel TaxLabel; private javax.swing.JTextPane Total; private javax.swing.JLabel TotalLabel; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; // End of variables declaration
    }

I have a simple store GUI and I have certain products for sale using checkboxes but now I want to make it so that the user can buy multiple of the same product, how can I do that?




vendredi 19 mai 2023

how do I keep checkboxs stay checked after refreshing the page?

I am studying how to keep checkboxs stay checked after refreshing the page. And I find this helps. However, the code, does not work right at my server. When I refresh, checkboxs stayed unchecked. I also use this compiler. NOT GOOD. See

The code I use:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#checkbox-container{
  margin: 10px 5px;
}

#checkbox-container div{
  margin-bottom: 5px;
}

#checkbox-container button{
  margin-top: 5px;
}

input[type=text] {
  padding: .5em .6em;
  display: inline-block;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 3px #ddd;
  border-radius: 4px;
}
</style>
</head>

<body>
<div id="checkbox-container">
  <div>
    <label for="option1">Option 1</label>
    <input type="checkbox" id="option1">
  </div>
  <div>
    <label for="option2">Option 2</label>
    <input type="checkbox" id="option2">
  </div>
  <div>
    <label for="option3">Option 3</label>
    <input type="checkbox" id="option3">
  </div>
</div>
</body>


</html>
<script>
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#checkbox-container :checkbox");
    
    $checkboxes.on("change", function(){
      $checkboxes.each(function(){
        checkboxValues[this.id] = this.checked;
      });
      
      localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });
    
    // On page load
    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
</script>

It seems to me that the code only works on CODEPEN. May somebody tells me what is wrong? Thanks a lot.




How can I make my HTML form email me when a checkbox is checked using PHP POST?

I am trying to add a checkbox to a form and get the confirmation through an email. I am using the POST method. All the rest of fields works fine, but checkbox doesn't...

Thanks!

HTML FORM

<form class="form-contact" id="formulario" name="contacto" method="post" action="paraenviar.php">

<label for="nombre">Nombre</label>
<input name="nombre" id="nombre" type="text" required class="fill" size="20" /><br /> 
      
<label for="empresa">Empresa</label>
<input name="empresa" id="empresa" type="text" required class="fill" size="20" /><br /> 

<label for="email">eMail</label>
<input name="email" id="email" type="text" required class="fill" size="20" /><br /> 

<label for="mensaje">Mensaje</label>
<textarea name="mensaje" id="mensaje" cols="26" rows="3" required class="textarea"></textarea><br />
        
<input type="checkbox" id="protecciondatos" name="protecciondatos" value="protecciondatos" required>

<label for="proteccion-datos">He leído y acepto la <a href="#">política de protección de datos</a> </label>
        
<br><br>
        
<input class="sendbutton" name="insert" type="submit" value="Enviar"/>

</form>

PHP

<?php

$nombre = $_POST['nombre'];
$empresa = $_POST['empresa'];
$email = $_POST['email'];


$mensaje = "NOMBRE: " . $nombre ." \r\n";
$mensaje .= "EMPRESA: " . $empresa . " \r\n";
$mensaje .= "E-MAIL: " . $email . " \r\n";
$mensaje .= "MENSAJE: " . $_POST['mensaje'] . " \r\n";
$mensaje .= "FECHA DEL ENVÍO: " . date('d/m/Y', time());

$para = 'xxxx@xxx';
$asunto = 'Blablabla';

mail($para, $asunto, utf8_decode($mensaje));

?>



jeudi 18 mai 2023

Worksheet_change not working anymore & trying to uncheck boxes when target changes

I am needing help with worksheet_change code that was working for a while but now is not recognizing changes after I've been trying to include more in the code (+2 lines).

Context: Table on each ws in a wb that serves a template that a user fills out. The table/template has drop-downs (dependent on prior drop-down), buttons (shapes), and various other worksheet changes related to column range updates.

The one I am focused on is a range (column B). This column does have data validation drop-downs attached to it. Previously, I was able to get excel to recognize any change made in this range--like being blank or changing to another drop down option-- and it would then clear out some following cells (in Col D:F) in the same row as a reset. These cleared cells also have DV drop-downs within them. Recently, I've been trying to uncheck some checkboxes located in additional columns at the end of this table if there were any in that same row. I added on to the code I wrote and no boxes unchecked and no col B changes were recognized at all.

Even as I worked backwards and ran the original version of the code I created, it now won't recognize any Col B (target) changes.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngB As Range
Set rngB = Range("B7:B28")
Dim chk As CheckBox

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    If Not Intersect(rngB, Target) Is Nothing Then
            Range(ActiveCell.Offset(0, 2), ActiveCell.Offset(0, 4)).Value = ""
            Range(ActiveCell.Offset(0, 13), ActiveCell.Offset(0, 16)).chk.Value = False
              
        For Each myCell In Intersect(Target, rngB)
            If myCell.Value = "" Then
                Range(myCell.Offset(0, 2), myCell.Offset(0, 4)).Value = ""
                Range(myCell.Offset(0, 13), myCell.Offset(0, 16)).chk.Value = False
            End If
        Next myCell
    End If

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

For reference, here is the original code that is no longer working either:

     If Not Intersect(rngB, Target) Is Nothing Then
        Range(ActiveCell.Offset(0, 2), ActiveCell.Offset(0, 4)).Value = ""
           
        For Each myCell In Intersect(Target, rngB)
            If myCell.Value = "" Then
                Range(myCell.Offset(0, 2), myCell.Offset(0, 4)).Value = ""
            End If
        Next myCell
    End If

If there is anything else I can provide, please let know. Would appreciate some assistance.




How to mark checkboxes in a list backward, numerically descending?

I am generating a list from a database using PHP. Each line is numbered in ascending order and contains a checkbox. If you select one, all checkboxes above it, numerically descending, should also be selected.

I have already tried various things, but it does not work. Here is the code in a shortened form:

<table id="mySEARCH" class="shoppinglist-content">
<!-- ******************************************************************************** shopping list beginn-->
    <!-- script test start -->
    <?php
        if(isset($_COOKIE['shoppinglist'])){
            $list = $_COOKIE['shoppinglist'];
            $stmt = $pdo->prepare("SELECT * FROM `$list`");
            $stmt->execute();
            $x = 0;
            foreach($stmt as $item)
            { $x++;?>
                <tr id="line<?php echo $x;?>" style="opacity: 1.0;">
                <td class="split-list"><input type="checkbox" id="split-list-<?php echo $x;?>" name="split-list" onchange="markAbove<?php echo $x;?>()" value="<?php echo $x;?>"></td>
                </tr>
                <script>
                    function markAbove<?php echo $x;?>(){
                        var choosedLine = document.querySelectorAll("input[type=checkbox]");
                        for(var i = <?php echo $x;?>; i > choosedLine.value; i--){
                            choosedLine.setAttribute("checked", "");
                        }
                        console.log(i);
                    }
                </script>
            <?php
            }
        }else {
/******************************************************************************** shopping list end****/
            ?><tr><td></td><td></td><td>Keine Items vorhanden</td><td></td><td></td><td></td><td></td></tr><?php
        }
    ?>
<!-- script test end -->
</table>

enter image description here

Does anyone have a tip on how this can work?




How to load the children on demand in react checkbox tree along with virtual scrolling

            import React, { us
eState } from 'react';
                import CheckboxTree from 'react-checkbox-tree';
                import 'react-checkbox-tree/lib/react-checkbox-tree.css';
                import { List } from 'react-virtualized';
                import 'react-virtualized/styles.css';
                import {
                MdCheckBox,
                MdCheckBoxOutlineBlank,
                MdChevronRight,
                MdKeyboardArrowDown,
                MdAddBox,
                MdIndeterminateCheckBox,
                } from "react-icons/md";

                const VirtualizedCheckboxTree = () => {
                const [treeData, setTreeData] = useState([
                    {
                    value: 'node1',
                    label: 'Node 1',
                    children: [], // Initially empty
                    },
                    {
                    value: 'node2',
                    label: 'Node 2',
                    children: [], // Initially empty
                    },
                    {
                    value: 'node3',
                    label: 'Node 3',
                    children: [], // Initially empty
                    },
                ]);

                const orgNodeIcons = {
                    check: <MdCheckBox className="rct-icon rct-icon-check" />,
                    uncheck: <MdCheckBoxOutlineBlank className="rct-icon rct-icon-uncheck" />,
                    halfCheck: (
                    <MdIndeterminateCheckBox className="rct-icon rct-icon-half-check" />
                    ),
                    expandClose: <MdChevronRight className="rct-icon rct-icon-expand-close" />,
                    expandOpen: <MdKeyboardArrowDown className="rct-icon rct-icon-expand-open" />,
                    expandAll: <MdAddBox className="rct-icon rct-icon-expand-all" />,
                    collapseAll: (
                    <MdIndeterminateCheckBox className="rct-icon rct-icon-collapse-all" />
                    ),
                    parentClose: <></>,
                    parentOpen: <></>,
                    leaf: <></>,
                };
                const handleLoadMore = (parentNode) => {
                    // Simulate loading data from an API
                    setTimeout(() => {
                    const updatedTreeData = [...treeData];
                    const parentIndex = updatedTreeData.findIndex(
                        (node) => node.value === parentNode[0]
                    );

                    if (parentIndex !== -1) {
                        // Dynamically add children nodes
                        const children = [
                        { value: 'newNode1', label: 'New Node 1' },
                        { value: 'newNode2', label: 'New Node 2' },
                        ];

                        updatedTreeData[parentIndex].children = children;

                        setTreeData(updatedTreeData);
                    }
                    }, 1000);
                };

                const rowRenderer = ({ key, index, style }) => (
                    <div key={key} style={style}>
                    <CheckboxTree
                        nodes={treeData}
                        checked={[]}
                        expanded={[]}
                        onExpand={handleLoadMore}
                        showExpandAll
                        icons={orgNodeIcons}

                    />
                    </div>
                );

                return (
                    <div style=>
                    <List
                        width={300}
                        height={400}
                        rowCount={1}
                        rowHeight={400}
                        rowRenderer={rowRenderer}
                    />
                    </div>
                );
                };

                export default VirtualizedCheckboxTree;

` In the above example i tried to add the children when user click on the expand icon but iam getting the below error

enter image description here

Help me with a working example to load the children on demand and also achieve the virtual scrolling

Help me with a working example to load the children on demand and also achieve the virtual scrolling

`




mardi 16 mai 2023

Showing the count of checked checkboxes using vanilla javascript

Im currently working on a website that generates a random password. One part of it shows the safety of the current password. Until now i was only able to make the safety-indicator dependent on the current length of the password. I want to also include the current count of checked checkboxes in the safety indicator.

I tried this function to update the the count of checked checkboxes with "onchange":

function updateSafetyIndicator() {

    const checks = document.querySelector(".checks");
    const checkedCount = 0;

    for (var i = 0; i < checks.length; i++) {
        if (checks[i].checked) {
            checkedCount++;
        }
    }

    console.log(checkedCount)

    if (checkedCount <= 1) {
        passwordSafetyIndicator.id = "veryweak";
    }

    else if (checkedCount <= 2) {
        passwordSafetyIndicator.id = "weak";
    }

    else if (checkedCount <= 3) {
        passwordSafetyIndicator.id = "medium";
    }

    else if (checkedCount <= 4) {
        passwordSafetyIndicator.id = "strong";
    }
}



lundi 15 mai 2023

If checkbox is checked, check another box

I'm trying to create a few checkboxes that when checked, will check another... which I got to work! But, the problem I'm having now is that if multiple are selected and one is unchecked at any point, the additional checkbox get unchecked no matter what. I'd like to find a way to have the additional checkbox stay checked, as long as one of the others is, and uncheck if none are selected.

For example: I have 4 checkboxes, if a user selects #1 I want to check #2. Or if a user selects #1 + #3, check #2, but if #3 is unchecked, #2 stays as long as 1,3, or 4 are. I hope this makes sense. I've been trying different things, but this is the code where I landed. Any help, advice on a better way to accomplish this would be greatly appreciated.

var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");

chk1.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk3.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk4.on('change', function(){
  chk2.prop('checked',this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">4



dimanche 14 mai 2023

tailwind toggle component not passing value in form

I'm trying to add a toggle switch to my form (blade template in laravel 9). I pulled the toggle from https://flowbite.com/docs/forms/toggle/, but it was missing the 'name' attribute so I added that myself, and it now appears in the form data, but it's always null.

Here's the code:

<label class="relative inline-flex items-center cursor-pointer">
    <input type="checkbox" name="goal" value="" class="sr-only peer">
    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
    <span class="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">Goal</span>
</label>

As far as I can tell, the toggle switch doesn't actually change the value of the checkbox at all, but the div set to change based on 'peer' suggests that it is.

I must be missing something really obvious. Any ideas?




remove data from list when checkbox in unchecked

i used this command widgets.removeAt(data[index]['title']); but when i tried to uncheck its checkbox not all title of title of checkbox is removed

class _MyHomePageState extends State<MyHomePage> {

  List<Widget> widgets=[];
  List<Map<String, dynamic>> data = [
    {'title': 'checkbox1', 'value': false},
    {'title': 'checkbox2', 'value': false},
    {'title': 'checkbox3', 'value': false}
  ];


  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body:
            Column(
              children: [
                Column(
                  children: widgets
                ),
                ListView.builder(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  itemCount : data.length,
                  itemBuilder: (context, index) {
                    return CheckboxListTile(
                        title: Text(data[index]['title']),
                        value: data[index]['value'],
                        onChanged: (value) {
                          setState(() {

                            // bool check=data[index]['value'] = value!;
                            if(data[index]['value'] = value!){
                              widgets.add(Text(data[index]['title'].toString()));
                              print(data[index]['title'].toString());
                            }else{
                              widgets.removeAt(index);
                            }
                          });
                        });
                  },
                ),

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


in that picture checkbox title not removed in console i got this error Value not in range: 2




samedi 13 mai 2023

Custom checkbox (radio) not centred while zooming

I am writing an extension for chrome browser. A block with two custom checkboxes and labels are added to the page I need. The problem is that when scaling the page, the internal selection of the radio starts to behave strangely,changes shape and moves out of the center Checkboxes page scaling

I can't figure out what is causing the problem. I've tried different positioning options for the before element, but it only works for one page scale. ChatGPT and the Indians from YouTube did not help. You are my last hope :( Here is my script.js code and styles style.css

script.js

const checkbox1 = document.createElement('input');
checkbox1.classList.add('checkbox-container');
checkbox1.setAttribute('type', 'checkbox');
checkbox1.setAttribute('checked', true);

const enabledLabel = document.createElement('label');
enabledLabel.classList.add('label-container');
enabledLabel.appendChild(checkbox1);
enabledLabel.appendChild(document.createTextNode('Enabled'));
user_abuser_block.appendChild(enabledLabel);

const checkbox2 = document.createElement('input');
checkbox2.classList.add('checkbox-container');
checkbox2.setAttribute('type', 'checkbox');

const disabledLabel = document.createElement('label');
disabledLabel.classList.add('label-container');
disabledLabel.appendChild(checkbox2);
disabledLabel.appendChild(document.createTextNode('Disabled'));
user_abuser_block.appendChild(disabledLabel);

style.css

.checkbox-container {
  left: -4px;
  top: -1px;
  position: relative;
  width: 1.05em;
  height: 1.05em;
  border-radius: 50%;
  vertical-align: middle;
  border: 0.1em solid #656565;
  appearance: none;
  -webkit-appearance: none;
  outline: none;
  cursor: pointer;
  margin-right: 2px;
}

.checkbox-container:checked {
  position: relative;
  border: 0.1em solid #71aaeb;
}

.checkbox-container:checked::before {
  content: "";
  position: absolute;
  transform-origin: center;
  width: 0.6em;
  height: 0.6em;
  background-color: #71aaeb;
  border-radius: 50%;
  transform: translate(25%, 25%);
}

.label-container {
  cursor: pointer;
  display: block;
  margin-bottom: 5px;
}

thanks in advance for your replies!




How can I make my Checkbuttons independent of each other on Tkinter?

Running this on macOS Ventura Version 13.3.1 on python 3.9.12

I have an application with a total of 6 Checkbuttons (A-F). I have some rules to guide what happens with these Checkbuttons:

  • A and C should start off as being selected.

  • IF A and B are ever both deselected then I want to know that and perform a specific task.

  • One and only one of C-F should always be selected. If C is selected then I do not want user to be able to deselect it. If D-F is then selected, I want C to be deselected and activated.

My problem is that is seems like A and C are linked with each other (when A is selected/deselected so is C) while B, D, E, and F are linked with each other. How can I avoid this?

I tried using variations of both IntVar() and BooleanVar() for the Checkbutton variables. I know that global variables can be problematic but I am trying to solve this without using Classes if possible.

My code is shown below:

from tkinter import *

root = Tk()

#####
######Defining Checkbutton variables and initial values
#####
global a_var
global b_var
global c_var
global d_var
global e_var
global f_var

a_var = IntVar()
a_var = 1

b_var = IntVar()
b_var = 0

c_var = IntVar()
c_var = 1

d_var = IntVar()
d_var = 0

e_var = IntVar()
e_var = 0

f_var = IntVar()
f_var = 0

#####
#####Checkbutton Functions
#####

#If cb_a and cb_b are both deselected at the same time then print("Error!")
def cb_a_update():
    global a_var
    global b_var
    
    if a_var == 1:
        if b_var == 1:
            a_var = 0 
            cb_a.a_var = a_var
            print("cb_a is deselected and cb_b is selected.")
        else:
            a_var = 0 
            cb_a.a_var = a_var
            print("Error! cb_a and cb_b are both deselected!")
    else:
        a_var = 1
        cb_a.a_var = a_var
        print('cb_a is selected.')

#If cb_a and cb_b are both deselected at the same time then print("Error")
def cb_b_update():
    global a_var
    global b_var
    
    if b_var == 1:
        if a_var == 1:
            b_var = 0 
            cb_b.b_var = b_var
            print("cb_b is deselected and cb_a is selected.")
        else:
            b_var = 0 
            cb_b.b_var = b_var
            print("Error! cb_b and cb_a are both deselected!")
    else:
        b_var = 1
        cb_b.b_var = b_var
        print('cb_b is selected.')

#For these 4 Checkbuttons, only 1 can be selected at any given time.
def cb_c_update():
    global c_var
    global d_var
    global e_var
    global f_var
    
    if c_var == 1:
        print("cb_c should not be allowed to deselect manually - should not see this message")
    else:
        c_var = 1
        cb_c.c_var = c_var
        cb_c.configure(state=DISABLED)
        d_var = 0
        cb_d.d_var = d_var
        cb_d.configure(state=ACTIVE)
        e_var = 0
        cb_e.e_var = e_var
        cb_e.configure(state=ACTIVE)
        f_var = 0
        cb_f.f_var = f_var
        cb_f.configure(state=ACTIVE)
        print("cb_c was selected/disabled and cb_d,e,f are deselected/active")

def cb_d_update():
    global c_var
    global d_var
    global e_var
    global f_var
    
    if d_var == 1:
        print("cb_d should not be allowed to deselect manually - should not see this message")
    else:
        d_var = 1
        cb_d.d_var = d_var
        cb_d.configure(state=DISABLED)
        c_var = 0
        cb_c.c_var = c_var
        cb_c.configure(state=ACTIVE)
        e_var = 0
        cb_e.e_var = e_var
        cb_e.configure(state=ACTIVE)
        f_var = 0
        cb_f.f_var = f_var
        cb_f.configure(state=ACTIVE)
        print("cb_d was selected/disabled and cb_c,e,f are deselected/active")

def cb_e_update():
    global c_var
    global d_var
    global e_var
    global f_var
    
    if e_var == 1:
        print("cb_e should not be allowed to deselect manually - should not see this message")
    else:
        e_var = 1
        cb_e.e_var = e_var
        cb_e.configure(state=DISABLED)
        c_var = 0
        cb_c.c_var = c_var
        cb_c.configure(state=ACTIVE)
        d_var = 0
        cb_d.d_var = d_var
        cb_d.configure(state=ACTIVE)
        f_var = 0
        cb_f.f_var = f_var
        cb_f.configure(state=ACTIVE)
        print("cb_e was selected/disabled and cb_c,d,f are deselected/active")

def cb_f_update():
    global c_var
    global d_var
    global e_var
    global f_var
    
    if f_var == 1:
        print("cb_f should not be allowed to deselect manually - should not see this message")
    else:
        f_var = 1
        cb_f.f_var = f_var
        cb_f.configure(state=DISABLED)
        c_var = 0
        cb_c.c_var = c_var
        cb_c.configure(state=ACTIVE)
        d_var = 0
        cb_d.d_var = d_var
        cb_d.configure(state=ACTIVE)
        e_var = 0
        cb_e.e_var = e_var
        cb_e.configure(state=ACTIVE)
        print("cb_f was selected/disabled and cb_c,d,e are deselected/active")

#####
#####Define Checkbuttons
#####
cb_a = Checkbutton(root, text="A",variable=a_var,onvalue=1,offvalue=0,command=cb_a_update)
cb_b = Checkbutton(root, text="B",variable=b_var,onvalue=1,offvalue=0,command=cb_b_update)

cb_c = Checkbutton(root, text="C",variable=c_var,onvalue=1,offvalue=0,command=cb_c_update,state=DISABLED)
cb_d = Checkbutton(root, text="D",variable=d_var,onvalue=1,offvalue=0,command=cb_d_update)
cb_e = Checkbutton(root, text="E",variable=e_var,onvalue=1,offvalue=0,command=cb_e_update)
cb_f = Checkbutton(root, text="F",variable=f_var,onvalue=1,offvalue=0,command=cb_f_update)

#####
#####Place Checkbuttons on grid layout
#####
cb_a.grid(row=0,column=0)
cb_a.select()
cb_b.grid(row=0,column=1)
cb_b.deselect()

cb_c.grid(row=1,column=0)
cb_c.select()
cb_d.grid(row=1,column=1)
cb_d.deselect()
cb_e.grid(row=1,column=2)
cb_e.deselect()
cb_f.grid(row=1,column=3)
cb_f.deselect()

root.mainloop()



vendredi 12 mai 2023

JavaScript code not working properly in Odoo v14

Good day, I hope you are doing well.

I am developing a new module in odoo, it's simple Parc Module.

I want to disable the checkboxes when the value of Stock is 0.

I wrote this code :

odoo.define('de_alfa_parc.CustomListRenderer', function (require) {
"use strict";
    var ListRenderer = require('web.ListRenderer');
    ListRenderer.include({
        _renderRow: function (record) {
            var self = this;
            var tr = this._super(record);
            var categ = ['Maintenance','Installation','Transport',"Volume d'impression"]
            console.log(record.data.small_category_name_field);
            tr.find("input[type='checkbox']").prop('disabled', record.data.stock <= 0 && !categ.includes(record.data.small_category_name_field) == true);
            return tr;
        },
    });
});

it's working well when I open the view and the checkboxes are disabled when the stock value is 0

BUT !!

When I touch any line, or modify any value, all the checkboxes become automatically enabled and I need to refresh the page so the script works again, can you please assit ?

Please to see the screnshots for more details

The code is working here on first load of the page I try to update the line The code stops working After refreshing the page, the code works again

Thank you in advance.




When i select the `select all` checkbox the each checkbox is not selected visually, but i can see that are selected in the state

I am writing react and i have a Table component in ant design and i want to select all the records that exists in all pages and not in every page that is the default. My code is like this

<Table
   style=
   rowSelection={SelectionConfig}
   ......


 const {selectedRows} = this.state

 const SelectionConfig = {
  selectedRows,
    onSelect: (record, selected, selectedRows, nativeEvent) => {
        this.setState({selectedRows: selectedRows})
        this.props.updateFieldsToCreate(selectedRows)
  },
  columnTitle: () => {
    return(
      <div>
      <Checkbox
        checked={selectedRows.length}
        indeterminate={
          selectedRows.length > 0 &&
          selectedRows.length < this.state.polygonData.length
        }
        onChange={(e) => {
          const { checked } = e.target;
          const selectedRows = checked
            ? this.state.polygonData.map((r) => r)
            : [];
          this.setState({ selectedRows: selectedRows }, () => {
            this.props.updateFieldsToCreate(selectedRows);
          });
        }}
      />
      </div>
    )
  },
  type: "checkbox",
  fixed: true,
}

When i console.log my stateselectedRows i can see that has data and i can sent this data to my server. But the each row seems that it is not selected only visually like this. I have find this it's help me to find how to choose all the data. How i can make this visual so the user can know that has select all the rows in every page.




Sanitize multiple checkbox in Wordpress form

I'm creating Wordpress Plugin and i'm stuck with my checkbox's group. I want to sanitize it but when i add the sanitize_callback, my form do not save anything.

Here's my checkbox part

    function customPostTypeHTML() { 
            
        $args=array(
            'public'                => true,
            'exclude_from_search'   => false,
            '_builtin'              => false
        ); 
        
        $output = 'names';
        $operator = 'and'; 
        $post_types = get_post_types($args,$output,$operator);
        
        foreach ($post_types  as $post_type ) {
            
            <div>
                <input type="checkbox" name="asmsl_custom_post_type_page[<?php echo $post_type; ?>]" id="<?php echo $post_type; ?>" value="1" <?php checked(isset(get_option('asmsl_custom_post_type_page')[$post_type]), '1'); ?>>
                <label for="<?php echo $post_type; ?>"><?php echo ucfirst($post_type); ?></label> 
            </div>
        <?php }
        
    ?>
<?php }

Well, this checkbox is the pre-made wordpress form works well. I test it in a custom form, it works too.

In this example as I said, i use the wordpress form, so i add et register some settings to display it :

    add_settings_section('asmsl-custom-post-type_first_section',  esc_html__('Custom Post Type', 'asmsl_domain'), array($this, 'customPostTypeSection'), 'asmsl-custom-post-type');
    register_setting('customPostTypePage', 'asmsl_custom_post_type_page', array('sanitize_callback' => array($this, 'sanitizeCustomPostType'), 'default' => "0"));
    add_settings_field('asmsl_custom_post_type_page', esc_html__('Choose where to display your Social media', 'asmsl_domain'), array($this, 'customPostTypeHTML'), 'asmsl-custom-post-type', 'asmsl-custom-post-type_first_section');

Problem appears when i use the "array('sanitize_callback')". If I delete this part, my checkboxes are saving well..but I need to sanitize this checkboxes.

I tried many things, doing my own sanitize function but everytime I failed either : not saving data, or : saving data without sanitize anything.

Any suggestions ?




jeudi 11 mai 2023

JqGrid prevent checkboxes from double clic event

I'm using a JqGrid with multiselect : true and i'm using double clic event to launch an edit function.

ondblClickRow: function (rowid) {
                var rowData = $(this).getRowData(rowid);
                document.location.href = "../record/" + rowData['id']
            },

But when it comes to select multiple rows, if you select or deselect the checkbox too quickly it launches the edit function (which I do not want).

How can prevent the dblclick event on the checkboxes and allow it anywhere else on the rest of the row ?




jquery checkbox select and alert popup [duplicate]

I want to show the row specifically when the checkbox corresponding to it is selected

//checkbox
'columnDefs': [{
  'targets': 0,
  'checkboxes': {
    'selectRow': true
  },
  'render': function(data, type, row, meta) {
    data = '<input type="checkbox" class="dt-checkboxes">'
    if (row[3] === 'London') {
      data = JSON.stringify(data);
      return type === 'display' && data.length > 120 ? data.substr(0, 120) + '…' : data;
      // return JSON.stringify(data);
    }
  },
  'createdCell': function(td, cellData, rowData, row, col) {
    if (rowData[3] === 'London') {
      this.api().cell(td).checkboxes.disable();
    }
  }
}],
//checkbox end
columns: [
    {
      title: 'Select',
      data: 'select',
      "width": "12%"
    },

    {
      title: 'Date Time',
      data: 'dateTime',
      "width": "12%"
    },
    {
      title: 'Transaction Id',
      data: 'transactionId',
      "width": "12%"
    },
    {
      title: 'Service Name',
      data: 'serviceName',
      "width": "12%"
    },
    {
      title: 'Status',
      data: 'serviceName',
      "width": "12%"
    },
    {
      title: 'Request',
      data: 'request',
      "width": "22%"
    },
    {
      title: 'Response',
      data: 'response',
      "width": "42%",
      render: function(data, type) {
        data = JSON.stringify(data);
        return type === 'display' && data.length > 120 ? data.substr(0, 120) + '…' : data;
        // return JSON.stringify(data);
      }
    }
  ],

  "language": {
    "emptyTable": "Exception details not found"
  }, select: {
    style: 'os',
    selector: 'td:first-child'
  }

});



mercredi 10 mai 2023

Checkbox with text in same line using ITextSharp

I'm using ITextSharp.LGPLv2.Core 3.3.5 to generate a PDF. I need to create a checkbox with a label. The checkbox can be checked or not depends on the data when I generate the PDF.

Basically something like this:

enter image description here

How can I achieve this? Currently I'm having two problems. First I don't know how to place content in the same line (I'm using a PdfPTable for this but the relative width makes hard to predict the result). Second, I don't know how to create the actuall checkbox. How can I achieve this?




mardi 9 mai 2023

node.js handlebars express how to re-route on checkbox checked or unchecked

I am new to node.js and handelbars. I have searched everywhere and can't find a solution / example on how to re-route? (CRUD) when I check the checkbox.

i.e.

list.hbs snippet below

<label class="toggle">
   <input class="toggle-checkbox" type="checkbox" id="hide">
   <div class="toggle-switch"></div>
   <span class="toggle-label">Show all</span>           
</label>

When checkbox is checked

//list only active bookings for this vehicle
bookings.get('/activeonly/:ID', isLoggedIn, async(req, res) => {    
    const { ID } = req.params;
    const bookings = await pool.query('SELECT * FROM booking WHERE status <> "COMPLETED" and regnr = ?', [ID]);
    const bookingregnr = [ID];
    res.render('bookings/bookingslist', {bookings: bookings, bookingregnr});
    selectedRegnr = bookingregnr;
});

When check box is not checked

//list all bookings for this vehicle
bookings.get('/:ID', isLoggedIn, async(req, res) => {   
    const { ID } = req.params;
    const bookings = await pool.query('SELECT * FROM booking WHERE regnr = ?', [ID]);
    const bookingregnr = [ID];
    res.render('bookings/bookingslist', {bookings: bookings, bookingregnr});
    selectedRegnr = bookingregnr;
});

PLEASE HELP and THANK YOU

I have added the script below and can't move on from here other than out put on the console

    <script  type = "text/javascript">
        const toggles = document.querySelector("#hide");
        toggles.addEventListener('change',function(e){      
            if (toggles.checked){
                 console.log("Show completed");     
                
            }else{
                console.log("Hide completed");
                
            }
        });
    </script>



Flutter pdf package checkbox

I created a pdf document in my flutter project. but the checkbox won't show up. The row has space in front of the text, but it is blank, no checkbox or anything. This happened after I updated the pdf package dependency and starting from there the checkbox won't show up. At first, before I update the package, the checkbox shows up but the checkbox doesn't have a mark even if I set the value to true, the exported pdf only has box but not highlighted, I tried going back to the package version before I update it where it at least shows the checkbox, but any other version is the same, the checkbox did not show up ever again. What could be the cause?

Here is the class where I have the creation of pdf:

// ignore_for_file: prefer_interpolation_to_compose_strings

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:open_file/open_file.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:provider/provider.dart';
import 'package:qvin/utils/labelFormat.dart';

import '../../providers/dvirProvider.dart';

class PdfApi {
  static Future<File> generatePDF(
      BuildContext context,
      String? vehicleNo,
      String? remarks,
      bool isCondition,
      bool isAbove,
      bool isAboveDefect,
      bool isNoResult) async {
    final pdf = pw.Document();
    final font = await rootBundle.load("assets/hind.ttf");
    final ttf = pw.Font.ttf(font);

    DateTime dateToday = DateTime.now();
    final provider = Provider.of<DVIRProvider>(context, listen: false);
    final datasTruck = provider.checklistTruck;
    final datasTrailer = provider.checklistTrailer;

    final headers = [
      'TITLE',
      'STATUS',
    ];

    final dataTruck = datasTruck
        .map((e) => [
              e.title,
              e.isCheck == true ? 'x' : '/',
            ])
        .toList();

    final dataTrailer = datasTrailer
        .map((e) => [
              e.title,
              e.isCheck == true ? 'x' : '/',
            ])
        .toList();

    pdf.addPage(
      pw.MultiPage(
        theme: pw.ThemeData(defaultTextStyle: pw.TextStyle(font: ttf)),
        build: (context) => <pw.Widget>[
          pw.Center(
            child: pw.Text(
              "Driver's Vehicle Inspection Report",
              style: pw.TextStyle(fontSize: 24, fontWeight: pw.FontWeight.bold),
            ),
          ),
          pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
          pw.Center(
            child: pw.Text(
              "Check ANY Defective Item and Give Details under 'Remarks.'",
              style: const pw.TextStyle(
                fontSize: 14,
              ),
            ),
          ),
          pw.SizedBox(height: 2 * PdfPageFormat.cm),
          pw.Column(crossAxisAlignment: pw.CrossAxisAlignment.start, children: [
            pw.Text(
              "DATE: ${LabelFormat.formatDate(dateToday)}",
              style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold),
            ),
            pw.SizedBox(height: 0.5 * PdfPageFormat.cm),
            pw.Text(
              "TRUCK/TRACTOR NO. $vehicleNo",
              style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold),
            ),
            pw.SizedBox(height: 0.5 * PdfPageFormat.cm),
          ]),
          pw.Table.fromTextArray(
            data: dataTruck,
            headers: headers,
            cellHeight: 30,
            headerStyle: pw.TextStyle(fontWeight: pw.FontWeight.bold),
            cellAlignments: {
              0: pw.Alignment.centerLeft,
              1: pw.Alignment.center,
            },
          ),
          pw.Column(crossAxisAlignment: pw.CrossAxisAlignment.start, children: [
            pw.Text(
              "TRAILER(S) NO (S). $vehicleNo",
              style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold),
            ),
            pw.SizedBox(height: 0.5 * PdfPageFormat.cm),
          ]),
          pw.Table.fromTextArray(
            data: dataTrailer,
            headers: headers,
            cellHeight: 30,
            headerStyle: pw.TextStyle(fontWeight: pw.FontWeight.bold),
            cellAlignments: {
              0: pw.Alignment.centerLeft,
              1: pw.Alignment.center,
            },
          ),
          pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
          pw.Text(
            "REMARKS: ${remarks ?? '--'}",
            style: pw.TextStyle(
              fontSize: 12,
              fontWeight: pw.FontWeight.bold,
            ),
          ),
          pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
          if (isNoResult == true)
            pw.Column(children: [
              pw.Row(children: [
                pw.Checkbox(
                  name: 'condition',
                  value: isCondition,
                ),
                pw.SizedBox(width: 0.8 * PdfPageFormat.cm),
                pw.Text(
                  'Condition of the above vehicle is satisfactory',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
              ]),
              pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
              pw.Row(children: [
                pw.Text(
                  "Driver's Signature",
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
                pw.Spacer(),
                pw.Text(
                  'Date: ${LabelFormat.formatDate(dateToday)}',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
              ]),
              pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
            ])
          else
            pw.Column(children: [
              pw.Row(children: [
                pw.Checkbox(
                  name: 'aboveDefectsCorrected',
                  value: true,
                ),
                pw.SizedBox(width: 0.8 * PdfPageFormat.cm),
                pw.Text(
                  'Above Defects Corrected',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
                pw.Checkbox(
                  height: 20,
                  width: 20,
                  name: 'sample',
                  value: true,
                  tristate: true,
                  decoration: pw.BoxDecoration(
                    color: PdfColors.blue,
                  ),
                ),
              ]),
              pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
              pw.Row(children: [
                pw.Checkbox(
                  name: 'aboveDefectsNeed',
                  value: true,
                ),
                pw.SizedBox(width: 0.8 * PdfPageFormat.cm),
                pw.Text(
                  'Above Defects Need NOT Be Corrected For Safe Operation Of Vehicle',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
              ]),
              pw.SizedBox(height: 0.8 * PdfPageFormat.cm),
              pw.Row(children: [
                pw.Text(
                  "Mechanic's Signature",
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
                pw.Spacer(),
                pw.Text(
                  'Date: ${LabelFormat.formatDate(dateToday)}',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
              ]),
              pw.SizedBox(height: 0.4 * PdfPageFormat.cm),
              pw.Row(children: [
                pw.Text(
                  "Driver's Signature",
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
                pw.Spacer(),
                pw.Text(
                  'Date: ${LabelFormat.formatDate(dateToday)}',
                  style: const pw.TextStyle(
                    fontSize: 14,
                  ),
                ),
              ]),
            ]),
        ],
      ),
    );
    return saveDocument(name: 'sample.pdf', pdf: pdf);
  }

  static Future<File> getDocument({
    required String name,
    required pw.Document pdf,
  }) async {
    final bytes = await pdf.save();
    final dir = await getApplicationSupportDirectory();
    final file = File('${dir.path}/$name');
    await file.writeAsBytes(bytes);
    print({'file:$file'});
    return file;
  }

  static Future<File> saveDocument({
    required String name,
    required pw.Document pdf,
  }) async {
    final bytes = await pdf.save();
    final directory = await getApplicationDocumentsDirectory();
    final dvirDirectory = Directory('/storage/emulated/0/dvir documents');
    await dvirDirectory.create(recursive: true);
    final file = File('${dvirDirectory.path}/$name');
    await file.writeAsBytes(bytes);
    print('file saved to: ${file.path}');
    return file;
  }

  static Future openFIle(File file) async {
    final url = file.path;
    await OpenFile.open(url);
  }
}