vendredi 31 mars 2023

How do I set the value of a checkbox in a datagrid from vbnet code behind?

I have a modal window containing a datgrid with three checkboxes. One is the "selected" checkbox. Two are user editable. I need to set the two user checkboxes to true or false based on data entered. Databinding works fine, but later in the code I cannot find a way to check or uncheck the boxes. I can set their text to "true" or "false" but the datagrid then shows "true" or "false" instead of a checkmark. I've been beating my head on this for days now...any ideas? Surely someone has had the same need....

I've been trying all sorts of code to reference the checkbox cells and can see if they are checked on unchecked but the same sort of references do not work when trying to set the value. I really don't have any code to post because it has all been scrap.




jeudi 30 mars 2023

Want to save to checked and unchecked checkboxes in react?

i have popup modal in which there is "Select All" checkbox of module and its features checkboxes and when i click on Select All checkbox then its features checkboxes should also checked and vice versa . And when i click on save button then all the unchecked and checked checkboxes should be sent to server in which checked checkboxes as true and unchecked checkboxes as false.But the problem is here that "rights" are saving correctly then after closing popup if i want to edit rights for which i click on "Access" button again then popup should be open with selected right but in my case all checkboxes are checked coming and when i want to uncheck any checkbox this it is not working neither it is saved when click on "save" button .Anyone can help me ?

import axios from "axios";
import React, { useEffect, useState } from "react";

const ManageAccessGroups_assignRightsModal = ({ AgetGroupName }) => {
  const [GAMgetGroupsRights, setGAMgetGroupsRights] = useState([]);
  const [checkboxValues, setCheckboxValues] = useState([]);
  const [selectAll, setSelectAll] = useState([
    { moduleId: 1, checked: false },
    { moduleId: 2, checked: false },
    { moduleId: 4, checked: false },
    { moduleId: 5, checked: false },
    { moduleId: 6, checked: false },
    { moduleId: 7, checked: false },
    { moduleId: 8, checked: false },
    { moduleId: 9, checked: false },
    { moduleId: 10,checked: false },
    { moduleId: 11,checked: false },
    { moduleId: 12,checked: false },
  ]);
  
  const ManageAccessGroups_assignRightsModal_getAccessRights = async (id) => 
  {
    try 
    {
      const response = await axios.get(
        `${process.env.REACT_APP_API_URL}accessgrouprights/group/${id}`,
        {
          headers: 
          {
            "content-type": "application/json",
            Authorization: localStorage.getItem("token"),
          },
        }
      );
      const data = await response.data;
      setGAMgetGroupsRights(data);
      console.log(
        "group access rights   ==> ManageAccessGroups_assignRightsModal_getAccessRights",
        data
      );
      return data;
    } catch (error) 
    {
      console.log(
        "group access rights error ==> ManageAccessGroups_assignRightsModal_getAccessRights",
        error
      );
    }
  };
 // save rights   --start
 
  const handleCheckboxChange = (event, index) => 
  {
    const { name, checked } = event.target;
    const newGAMgetGroupsRights = [...GAMgetGroupsRights];
    const item = newGAMgetGroupsRights.flatMap((gRights) => gRights.accessGroupRightsList).find((item, i) => i === index);
    if (item) {
      item[name] = checked;
      setGAMgetGroupsRights(newGAMgetGroupsRights);
    }
  };

  const getSelectedPermissions = () => 
  {
    const selectedPermissions = [];
    GAMgetGroupsRights?.forEach((module) => {
      module.accessGroupRightsList?.forEach((item) => 
      {
        if (item.features.allowedView) 
        {
          selectedPermissions.push({
            createdBy: 12,
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: true,
            addRights: false,
            editRights: false,
            deleteRights: false,
            accessGroupId: item.accessGroupId,
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedAdd) 
        {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: true,
            editRights: false,
            deleteRights: false,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedEdit) {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: false,
            editRights: true,
            deleteRights: false,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedDelete) 
        {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: false,
            editRights: false,
            deleteRights: true,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
      });
    });
    return selectedPermissions;
  };
  
  const handleSelectAll = (event, moduleId) => 
  {
    const { checked } = event.target;
    const newGAMgetGroupsRights = [...GAMgetGroupsRights];
    const moduleIndex = newGAMgetGroupsRights.findIndex((module) => module.moduleId === moduleId);
    if (moduleIndex !== -1) 
    {
      newGAMgetGroupsRights[moduleIndex].accessGroupRightsList.forEach((item) => 
      {
        if (item.features.allowedView) 
        {
          item.viewRights = checked;
        }
        if (item.features.allowedAdd) 
        {
          item.addRights = checked;
        }
        if (item.features.allowedEdit) 
        {
          item.editRights = checked;
        }
        if (item.features.allowedDelete) 
        {
          item.deleteRights = checked;
        }
      });
    }
      setGAMgetGroupsRights(newGAMgetGroupsRights);
  
      const newSelectAll = [...selectAll];
      const moduleSelectAll = newSelectAll.find((item) => item.moduleId === moduleId);
    if (moduleSelectAll) 
    {
      moduleSelectAll.checked = checked;
      setSelectAll(newSelectAll);
    }
  };

  const ManageAccessGroups_assignRightsModal_insertGroupRights = async () => 
  { 
   
    const selectedPermissions = getSelectedPermissions();
    console.log("check adata", selectedPermissions)
    try 
    {
      const response = await axios.post(
        `${process.env.REACT_APP_API_URL}accessgrouprights/insert-data`,
        selectedPermissions,
        {
          headers: 
          {
            "Content-Type": "application/json",
            Authorization: localStorage.getItem("token"),
          },
        }
      );
      console.log("Rights saved success ==> ManageAccessGroups_assignRightsModal_insertGroupRights:", response.data);
    } 
    catch (error) 
    {
      console.error("Error saving rights error ==> ManageAccessGroups_assignRightsModal_insertGroupRights:", error);
    }
  };

  useEffect(() => 
  {
    const initialCheckboxValues = [];
    GAMgetGroupsRights?.forEach((gRights) => {
      gRights.accessGroupRightsList?.forEach((item) => {
        initialCheckboxValues.push({
          moduleId: gRights.moduleId,
          accessGroupId: item.accessGroupId,
          featureId: item.features.featureId,
          read:   item.viewRights,
          create: item.addRights,
          update: item.editRights,
          delete: item.deleteRights,
        });
      });
    });
  
    setCheckboxValues(initialCheckboxValues);
  }, []);
  
  // save rights  ---end

  useEffect(() => 
  {
    ManageAccessGroups_assignRightsModal_getAccessRights(AgetGroupName?.id);
  }, [AgetGroupName?.id]);

  return (
    <div>
      <div
        class="modal modal-static fade"
        id="kf-AccessRightsModal"
        tabindex="-1"
        aria-hidden="true"
        data-bs-backdrop="static"
      >
        <div class="modal-dialog modal-dialog-centered mw-750px">
          <div class="modal-content">
            <div class="modal-header">
              <h2 class="fw-bold">Group Access Rights</h2>
              <div
                class="btn btn-icon btn-sm btn-active-icon-primary"
                data-bs-dismiss="modal"
              >
                <span class="svg-icon svg-icon-1">
                  <svg
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <rect
                      opacity="0.5"
                      x="6"
                      y="17.3137"
                      width="16"
                      height="2"
                      rx="1"
                      transform="rotate(-45 6 17.3137)"
                      fill="currentColor"
                    />
                    <rect
                      x="7.41422"
                      y="6"
                      width="16"
                      height="2"
                      rx="1"
                      transform="rotate(45 7.41422 6)"
                      fill="currentColor"
                    />
                  </svg>
                </span>
              </div>
            </div>
            <div class="modal-body scroll-y mx-5 my-7" style=>
              <form id="kt_modal_update_role_form" class="form" action="#">
                <div
                  class="d-flex flex-column scroll-y me-n7 pe-7"
                  id="kt_modal_update_role_scroll"
                  data-kt-scroll="true"
                  data-kt-scroll-activate="{default: false, lg: true}"
                  data-kt-scroll-max-height="auto"
                  data-kt-scroll-dependencies="#kt_modal_update_role_header"
                  data-kt-scroll-wrappers="#kt_modal_update_role_scroll"
                  data-kt-scroll-offset="300px"
                >
                  <div class="fv-row mb-10">
                    <label class="fs-5 fw-bold form-label mb-2">
                      <span class="required">Group name</span>
                    </label>
                    <input
                      class="form-control form-control-solid"
                      placeholder="Enter a role name"
                      name="role_name"
                      value={AgetGroupName?.name}
                    />
                  </div>
                  <div class="fv-row">
                    <label class="fs-5 fw-bold form-label mb-2">
                      Group Permissions
                    </label>
                    <div class="table-responsive">
                      <table class="table align-middle table-row-dashed fs-6 gy-5">
                        {GAMgetGroupsRights?.map((gRights) => (
                          <tbody class="text-gray-600 fw-semibold">
                            <>
                            {console.log("grights ",gRights )}
                              <tr className="row">
                                <td
                                  class="col-4 text-gray-800  px-4 text-start"
                                  key={gRights?.moduleId}
                                  style=
                                >
                                  {console.log("grights ",gRights.moduleNameEn )}
                                  {gRights?.moduleNameEn}
                                  <i
                                    class="fas fa-exclamation-circle ms-1 fs-7"
                                    data-bs-toggle="tooltip"
                                    title="Allows a full access to the system"
                                  ></i>
                                </td>
                                <td className="col-4">
                                  <label class=" form-check form-check-sm form-check-custom form-check-solid ">
                                    <input
                                      class="form-check-input"
                                      type="checkbox"
                                      value=""
                                      id={`select-all-${gRights.accessGroupId}`}
                                      checked={selectAll.find((item) => item.moduleId === gRights.moduleId)?.checked || false}  
                                      onChange={(event) => handleSelectAll(event, gRights.moduleId)}
                                    />
                                    <span
                                      class="form-check-label"
                                      for="kt_roles_select_all"
                                    >
                                      Select all
                                    </span>
                                  </label>
                                </td>
                              </tr>
                              <tr>
                                <td>
                                  {gRights?.accessGroupRightsList?.map(
                                    (item, index) => (
                                      <td className="d-flex justify-content-between ">
                                        <label class="text-gray-800 w-200px">
                                          {item?.features?.featureNameEn}
                                        </label>
                                        <td>
                                          <div class="d-flex mx-12 ">
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item?.features?.allowedView}
                                                id={`read-${index}`} name="read" checked={item.viewRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Read
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedAdd}
                                                id={`create-${index}`} name="create" checked={item.addRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Create
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedEdit}
                                                id={`update-${index}`} name="update" checked={item.editRights} onChange={(event) => handleCheckboxChange(event, index)} 
                                              />
                                              <span class="form-check-label">
                                                Update
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedDelete}
                                                id={`delete-${index}`} name="delete" checked={item.deleteRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Delete
                                              </span>
                                            </label>
                                          </div>
                                        </td>
                                      </td>
                                    )
                                  )}
                                </td>
                              </tr>
                            </>
                          </tbody>
                        ))}
                      </table>
                    </div>
                  </div>
                </div>
                <div class="text-center pt-15">
                  <button
                    type="reset"
                    class="btn btn-light me-3"
                    data-bs-dismiss="modal"
                  >
                    Discard
                  </button>
                  <button
                    type="submit"
                    class="btn btn-primary"
                    data-kt-roles-modal-action="submit"
                    onClick={() => ManageAccessGroups_assignRightsModal_insertGroupRights(AgetGroupName?.id)}
                  >
                    <span class="indicator-label">Save</span>
                    <span class="indicator-progress">
                      Please wait...
                      <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                    </span>
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ManageAccessGroups_assignRightsModal;




Having an issue with checkbox v-model only returning the first keyword in array

I have several tracks in an array and have a search and checkboxes to filter the tracks. However, the checkboxes only return the first identified string in each filter. So if I click the checkbox for pop - in the example below - it will only show tracks containing only the pop genre. Tracks containing rock, pop genre won't appear. This is in composition API in Vue.

Here is the script:

const searchTerm = ref('')

const genreFilter = ref([])
const moodsFilter = ref([])
const tempoFilter = ref([])
const themeFilter = ref([])

const filteredTracks = computed(() => {
let filtered = useSong.tracks;

if (searchTerm.value) {
const term = searchTerm.value.toLowerCase();
filtered = filtered.filter(track =>
  track.description.toLowerCase().includes(term) || 
  track.genre.toLowerCase().includes(term) ||
  track.keywords.toLowerCase().includes(term) ||
  track.moods.toLowerCase().includes(term)
);
}

if (genreFilter.value.length > 0) {
filtered = filtered.filter(track => genreFilter.value.includes(track.genre))
}

if (moodsFilter.value.length > 0) {
filtered = filtered.filter(track => moodsFilter.value.includes(track.moods))
}

if (tempoFilter.value.length > 0) {
filtered = filtered.filter(track => tempoFilter.value.includes(track.tempo))
}

if (themeFilter.value.length > 0) {
filtered = filtered.filter(track => themeFilter.value.includes(track.theme))
}

return filtered;
});

Here is the html:

<div class="genres w-1/4"><h1 class="font-bold text-[#aeaeae]">Genres</h1><br>
        <input class="css-checkbox" type="checkbox" id="Rock" key="genre" value="Rock" v- 
 model="genreFilter">
        <label class="css-label pl-2 text-s font-light text-[#aeaeae]" for="Rock">Rock</label> 

        <input class="css-checkbox" type="checkbox" id="Pop" key="genre" value="Pop" v- 
 model="genreFilter">
        <label class="css-label pl-2 text-s font-light text-[#aeaeae]" for="Pop">Pop</label> 

How can I modify this so that I can check multiple boxes of genres and have them all show, removing only the unchecked boxes. Any help will be greatly appreciated. Also, you'll notice in the filters I have one for moods, tempo and theme. Whenever I click any of those checkboxes, nothing appears at all in the array despite the array having matching moods, tempo, and theme. Thanks.




datatable checkbox: JS code + input[["dtable_cell_edit"]] does not work with reactive DT

I am starting with the well known solution used to add checkbox to a datatable (code reported below)

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, bool = FALSE)

dat2 <- cbind(
  dat0,
  check = shinyInput(checkboxInput, nrow(dat0), "checkb")
)

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 = 3)),
      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)

Now i am trying to modify the code in order to work with a reactive dat1, e.g applying a filter on dat0$letter with a proper select input.

At first run with dat0 filtered with letter 'b' (initial choice), the click on check column is registered; then switching the filter to letter 'a', the dt is displayed with the checkboxInput unchecked, but when i click on it the input is not registered (the observeEvent(input[["dtable_cell_edit"]] is not executed)

Here is my code attemp:

library(shiny)
library(DT)

ui <- fluidPage(
  br(),
  selectInput("letter","", choices=c("a", "b", "c", "d"), selected="b"),
  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")
)



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 <-eventReactive(input$letter,{
   
    tmp <- dat0
    tmp <- cbind(tmp, bool = FALSE)
    
    tmp<- tmp[tmp$letter == input$letter,]
    return(list(tbl=tmp))
  })
    
  
  dat2 <-eventReactive(dat1(),{
   
    tmp= dat1()$tbl
    tmp <- cbind(
        tmp,
        check = shinyInput(checkboxInput, nrow(tmp), "checkb"))
    
    Dat(dat1()$tbl)
    
    return(list(tbl=tmp))
    
  })
  
  
  output[["dtable"]] <- renderDT({
    
    tmp <- dat2()$tbl
    datatable(
      tmp, 
      rownames = TRUE,
      escape = FALSE,
      editable = list(target = "cell", disable = list(columns = 3)),
      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()
  })
  
}

Any idea where i'm wrong? Thanks




How I can apply display:none property to #checkbox

display:none doesn't wroks for #checkbox
https://codepen.io/Nicitaa/pen/QWVPzvw

I want #checkbox display:none when input[type="checkbox"]:not(:checked)::after pic

I tried
input[type="checkbox"]:not(:checked)::after, #checkbox { display: none; }
input[type="checkbox"]:not(:checked)::after + #checkbox { display: none; }
input[type="checkbox"]:not(:checked)::after ~ #checkbox { display: none; }

If you need more information - leave comment

@form:rgba(0,255,0,1);
@form-hover:rgba(255,255,0,0.8);
@form-opacity:rgba(255,0,0,0.6);

body {
  background-color:#202020;
}
.bx {
        position: absolute;
        top: 0;
        left: 2.5px;
        pointer-events:none;
    }

input[type="checkbox"] {
    appearance:none;
    outline: none;
    -webkit-appearance:0;
    min-height:15px;
    min-width: 15px;
    max-height:15px;
    max-width: 15px;
    margin:0px 5px 0px 3px;
    border-radius:2px;
    box-shadow:1px 1px 3px rgba(0,0,0,1);
 // To set checked at center
 display: flex;
 justify-content: center;
 align-items: center;
}
input[type="checkbox"]::after {
    content:"\f00c";
    font-family: "Font awesome 5 Free";
    font-weight: 900;
    font-size:6px;
    color:#000000;
}

input[type="checkbox"]:not(:checked)::after, #checkbox {
    display: none;
}
input[type="checkbox"]:not(:checked) {
    background-color:  @form-opacity;
}
input[type="checkbox"]:not(:checked):hover {
    background-color:  @form-hover;
}
input[type="checkbox"]:not(:checked):active {
    background-color:  @form;
}
input[type="checkbox"]:checked {
    background-color: @form;
}
input[type="checkbox"]:checked:hover {
    background-color: @form-hover;
}
input[type="checkbox"]:checked:active {
    background-color: @form-opacity;
}
input[type="checkbox"]:checked::after, #checkbox {
    display: flex;
}
<!-- box icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">

<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>

<div class="login_body_help">
  <div class="checkbox">
    <input type="checkbox" id="check" checked>
    <i class='bx bx-check' id="checkbox"></i>
    <p>Remember me</p>
  </div>
  <a href="#">Forgot password?</a>
</div>



mercredi 29 mars 2023

Using a checkbox to trigger different conditions - javascript

I'm struggling with how to write code that is tied to a button on adobe. When I press it, it checks if checkbox is true or false and then saves it in FolderA or folderB.

Checkbox is unique, the export value is set to true in the properties.

var myFileName = this.getField("Text Field 5").value + ".pdf";

if (this.getField("checkbox") == "true") { // I cannot get this condition to trigger

myFileName = "C:/Documents/FolderA/" + myFileName
myTrustedSpecialTaskFunc(this, myFileName);

}

else  { //this condition always triggers

myFileName = "C:/Documents/FolderB/" + myFileName
myTrustedSpecialTaskFunc(this, myFileName);
}

When I click the button, only the else condition triggers, I havent been able to determine while the if condition doesnt trigger.




how to check inner checkbox selected in jest react

i have created a custom checkbox wrapper and want to check that that the inner checkbox is selected and that the other checkboxes are disabled

I couldnt find the answer on here so I found one myself and here is how I did it...

ANSWER

const checkbox = await within(
        await screen.findByTestId('test-id-item-123'),
      ).findByTestId('inner-checkbox-id');

      expect(checkbox).not.toBeChecked();
      expect(checkbox).not.toBeDisabled();

      fireEvent.click(checkbox);
      expect(checkbox).toBeChecked();
      expect(checkbox).not.toBeDisabled();

      const disabled_checkbox = await within(
        await screen.findByTestId('test-id-item-123456'),
      ).findByTestId('inner-checkbox-id');

      expect(disabled_checkbox).not.toBeChecked();
      expect(disabled_checkbox).toBeDisabled();



mardi 28 mars 2023

Print a string in database from simple form checkboxes

I have 3 propositions i want my user to be able to choose from : Rent, sell or sublet, with simple form collection checkboxes and print the selection into the database.

I did try the following code but it doesn't print anything.

<%= simple_form_for @annonce do |f| %>
<%= f.collection_check_boxes :Type_de_projet, [["Rent", 'Rent'], ["Sell", 'Sell']], :first, :last %>
<%= f.submit "Créer une annonce ", :class => 'btn btn-outline-primary'%>



How do I get the current checkbox value on click into ajax when thousands of checkboxes are possible?

I need to get the value of a checkbox during an onclick event into ajax so that I can run some php code based on the checkbox value. When I have a simple webpage with a single checkbox

<input type='checkbox' class='fav' id='chk' value='Something_123' onclick='AddRemoveFav()'>

I can easily get the value into PHP via ajax using

<script type='text/javascript>
    function AddRemoveFav(){
        if ($('chk').is(':checked')){
            $.ajax({
                type: 'POST',
                url: 'addRemoveFav.php',
                data: {checked_box : $('chk').val()),
                success: function(data){
                    $('#message').html(data);
                }
             });
          }

Unfortunately there may be thousands of checkboxes that are created in a php echo statement (each with a unique id such as id='chk1', id='chk2', etc) so now I don't know how to get the event to fire on only the checkbox that was selected and not on other checkboxes that were previously selected. I've spent the last few hours on SO trying different things but so far nothing has worked out. My thought is that I need to do something like onclick='AddRemoveFav(this)' and then use that in the ajax below but that is where I am stuck. Any help is greatly appreciated.




how to reset a checkbox behavior using javascript?

I have this function checkRule, when the value2 == "Exclusive", I call checkRule to allow select only specific Checkbox, when value2 != "Exclusive" i want to reset the checkbox behavior, to be alowed to select any of the boxes. How can I do that?

   if (value2 == "Exclusive") {
        if (RPDirect.checked == true) {
            for (var i = 0; i < Checkboxes.length; i++) {
                Checkboxes[i].addEventListener("change", checkRule);
               } 
        } if (value2 != "Exclusive") {
            
        }
    }
    function checkRule(e)  {
        if (Checkboxes[7].checked == false ) {
            alert("Public must be selected.")  
        } 
        }



lundi 27 mars 2023

run apps script based on first column value

completely new to Apps script; I did not find anything on the web, so please forgive me if it was already asked.

I have a spreadsheet in which, in the first column, there are checkboxes that can be true or false. I would like to run a script only on the rows that have the true checkbox. Here's the script (which is not running, it is just returning the first row).

function prova() {
const modello = DriveApp.getFileById('XXXX');
const cartellaword = DriveApp.getFolderById('XXXX');
const cartellapdf = DriveApp.getFolderById('XXXX');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('automazione');
const rows = sheet.getDataRange().getValues();

rows.forEach(function(row, column) {
if (column[0] = true) {
const copy = modello.makeCopy(`${row[1]} - prova`, cartellaword);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
const oggi = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy");
const pdf = doc.getAs(MimeType.PDF);

body.replaceText('{oggi}', oggi);
body.replaceText('{nome}', row[1]);
body.replaceText('{datanascita}', row[2]);

doc.saveAndClose();
cartellapdf.createFile(pdf).setName(`${row[1]} - prova`)
}

})

}`

I tried to use: if (column[0] === true { /// run script } if (index[0] = true { /// run script }

Right now, the script works but it creates a PDF replacing only the first row (cell A1 is empty). I expected it to work for every rows which first cell (B1, C1, D1...) has the true checkbox.




How to check if checked checkboxes are in a consecutive order using javascript

I am creating a form and I would like to check if the checkboxes that are checked, if they are in a consecutive order. Meaning I would like to check if 3 or more checkboxes are checked, and also if they are in a consecutive order for example if 1-2-3 checkboxes are checked then the data-calculate price to be 84.10. If 1-2-5 checkboxes are checked then the data-calculate attribute for all checkboxes to be 99.00. If 3-4-5-6-7 checkboxes are checked then the data-calculate to be 79.10. I will provide the HTML and JS code for you to understand. The code is working but I want to add the consecutive weeks also. I added a comment about where my the extra code should go. Here is my code. If something is not clear please let me know to make it clear. Thanks.

HTML Code

  <form id="form">
    <div class="c-checkbox-box">
      <span>1</span>
      <input type="checkbox" class="c_week_1" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>2</span>
      <input type="checkbox" class="c_week_2" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>3</span>
      <input type="checkbox" class="c_week_3" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>4</span>
      <input type="checkbox" class="c_week_4" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>5</span>
      <input type="checkbox" class="c_week_5" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>6</span>
      <input type="checkbox" class="c_week_6" data-calculate="99">
    </div>
    <div class="c-checkbox-box">
      <span>7</span>
      <input type="checkbox" class="c_week_7" data-calculate="99">
    </div>

    <div class="c-checkbox-box">
      <div class="c-checkbox-box">
        <span>TSHIRT</span>
        <input type="radio" name="c-equipement2" class="c-tshirt-checkbox" data-calculate="0">
        <input type="radio" name="c-equipement2" class="c-tshirt-checkbox" data-calculate="9">
        <input type="radio" name="c-equipement2" class="c-tshirt-checkbox" data-calculate="9">
        <input type="radio" name="c-equipement2" class="c-tshirt-checkbox" data-calculate="9">
      </div>
      <span>Hat</span>
      <input type="radio" name="c-equipement1" class="c-hat-checkbox" data-calculate="0">
      <input type="radio" name="c-equipement1" class="c-hat-checkbox" data-calculate="10">
      <input type="radio" name="c-equipement1" class="c-hat-checkbox" data-calculate="10">
      <input type="radio" name="c-equipement1" class="c-hat-checkbox" data-calculate="10">
    </div>
    <div class="c-checkbox-box">
      <span>USB</span>
      <input type="radio" name="c-equipement3" class="c-usb-checkbox" data-calculate="0">
      <input type="radio" name="c-equipement3" class="c-usb-checkbox" data-calculate="17">
      <input type="radio" name="c-equipement3" class="c-usb-checkbox" data-calculate="17">
      <input type="radio" name="c-equipement3" class="c-usb-checkbox" data-calculate="17">
    </div>

  </form>

  <div class="c_final_price_1_kid"></div>

JS Code

const week1 = document.querySelector(".c_week_1");
    const week2 = document.querySelector(".c_week_2");
    const week3 = document.querySelector(".c_week_3");
    const week4 = document.querySelector(".c_week_4");
    const week5 = document.querySelector(".c_week_5");
    const week6 = document.querySelector(".c_week_6");
    const week7 = document.querySelector(".c_week_7");

    let allCheckboxes = [week1, week2, week3, week4, week5, week6, week7];

    let hatCheckboxes = document.querySelectorAll(".c-hat-checkbox")
    let tshirtCheckboxes = document.querySelectorAll(".c-tshirt-checkbox")
    let usbCheckboxes = document.querySelectorAll(".c-usb-checkbox")


    let tshirtPrice = 0;
    let hatPrice = 0;
    let usbPrice = 0;
    let tripsPrice = 0;

    let count = 0;

    allCheckboxes.forEach((box, index) => {



      box.addEventListener("click", (e) => {

        let sum = 0;

        if (box.checked) {
          count++
        } else {
          count--
          box.dataset.calculate = 99.00;
        }

        sum = count * 28.5;


        allCheckboxes.forEach(box => {

          if (box.checked) {

            if (count > 5 && count <= 7) {

              // Here is the 3-7 weeks consecutive checkboxes checked
              // Here is the 3-7 weeks consecutive checkboxes checked
              // Here is the 3-7 weeks consecutive checkboxes checked
              box.dataset.calculate = 79.20;

            } else if (count >= 3 && count <= 5) {

              // Here is the 3-4 weeks consecutive checkboxes checked
              // Here is the 3-4 weeks consecutive checkboxes checked
              // Here is the 3-4 weeks consecutive checkboxes checked
              if (box[index - 1] === box[index] - 1 && box[index + 1] ===
                box[index] + 1) {

                _log("working");

              } else {
                
                _log("not working")
              
              }
            
              box.dataset.calculate = 84.15;

            } else {
              // Normal price without discount
              box.dataset.calculate = 99.00;

            }

            sum = sum + parseFloat(box.dataset.calculate);

          }

        });

        let tshirtResult = tshirtCheckboxes.forEach((box) => {
          box.addEventListener("click", (e) => {
            tshirtPrice = parseFloat(e.target.dataset.calculate)
            document.querySelector('.c_final_price_1_kid').innerText = parseFloat(sum.toFixed(4)) + tshirtPrice + hatPrice + usbPrice;
          })
        })

        let hatResult = hatCheckboxes.forEach((box) => {
          box.addEventListener("click", (e) => {
            hatPrice = parseFloat(e.target.dataset.calculate)
            document.querySelector('.c_final_price_1_kid').innerText = parseFloat(sum.toFixed(4)) + tshirtPrice + hatPrice + usbPrice;
          })
        })

        let usnResult = usbCheckboxes.forEach((box) => {
          box.addEventListener("click", (e) => {
            usbPrice = parseFloat(e.target.dataset.calculate)
            document.querySelector('.c_final_price_1_kid').innerText = parseFloat(sum.toFixed(4)) + tshirtPrice + hatPrice + usbPrice;
          })
        })

        let result = document.querySelector('.c_final_price_1_kid').innerText = parseFloat(sum.toFixed(4));

      })
    });



how to set an element's value attribute to a list

Is there a way to set a checkbox's value attribute to a list<string>?

I have this checkbox

<input type="checkbox" id="select_all" class="checkBoxClass" selectAllCheckboxes(this) />

Then I have also dynamically created other checkboxes, all with the class name attribute set as checkBoxClass as well.

I am trying to create a new list that updates whenever the checkboxes are checked/unchecked, but when the select all checkbox is checked it should add all the checkbox values into the new list. (the checkbox values come from another list that is passed into the script, listItems)

The following code adds/removes the normal checkbox values when they are checked/unchecked:

let elem = [...document.querySelectorAll(".checkBoxClass")]
elem.forEach(item => item.addEventListener('change', getChecked))
function getChecked() {
  let getChex = elem.filter(item => item.checked).map(item => item.value)
  console.log(getChex)
}

but I am not sure how to get it working for the select all so it adds all elements of listItems to the list. Or is there another way to do this? Thanks




dimanche 26 mars 2023

Check box not responding to click in react

I have a simple react component that has a check box i want to toggle the value for on a click, it seems like it completely ignores my click I cant even get a console log. No idea why this doesnt work

export const InputCheckbox: InputCheckboxComponent = ({ id, checked = false, disabled, onChange }) => {
  const { current: inputId } = useRef(`RampInputCheckbox-${id}`)
  

  const handleClick = () => console.log('click');
  return (
    <div className="RampInputCheckbox--container" data-testid={inputId}>
      <label
        className={classNames("RampInputCheckbox--label", {
          "RampInputCheckbox--label-checked": checked,
          "RampInputCheckbox--label-disabled": disabled,
        })}
      />
      <input
        id={inputId}
        type="checkbox"
        className="RampInputCheckbox--input"
        onChange={handleClick}
      />
    </div>
  )
}

I've tried changing to onClick and I noticed the component isn't re-rendering on the click




Flutter: The function setState isn't defined and I am using a Stateful widget

I'll put the code briefly to show how everything is meant to flow from the Stateful widget.

I basically want the checkbox on my card to change state when the user clicks on it.

Error message: The function 'setState' isn't defined.

I did my research and I know it only works under a stateful widget. My widget tree is under a StatefulWidget so it should work but isn't.

class MyAppState extends StatefulWidget{

       Scaffold{
          //calls CardWidget to build individual cards for my list
       }       
}

     Widget CardWidget{

          Return Inkwell {
              Container{
                   
                        child: Checkbox(
                             value: item.checkBox,
                             onChanged: (bool? value) {
                             item.checkBox = !value!;

                             setState(() {
                             item.checkBox;
                             });
                           },
                       ),



samedi 25 mars 2023

Python tkinter get the value of multiple checkbox

For my tkinter/customtkinter gui, i have several checkbox and i want to automatically see if they are checked or not.

All my checkbox have a name like "box0", "box1", "box2", etc.

(https://i.stack.imgur.com/8Bbez.png)

After that, i have a button, and when you click, i call my function named "check"

(https://i.stack.imgur.com/COSP7.png)

My function is like this, it check if the box0 is checked of not:

(https://i.stack.imgur.com/3dO3z.png)

But i don't want to copy paste and type 4 times the same code, i want to automatize it, with something like that:

def check():
     for i in range(4):
          if box+i == 1: 
               print(f"Box{i} is checked")

How can i do that ?




vendredi 24 mars 2023

how to capture when a checked checkbox becomes unchecked

I want to get the value of the checkbox that goes from being checked to unchecked.

<input type="checkbox" class="cbx" name="privilegiosG[]" id="privilegioG_<?= $privilegio->getId() ?>" value="<?= $privilegio->getId() ?>" <?= $checked; ?> />

tried this but it doesn't work for me

<script type="text/javascript>"

    $("input[name='seccionesG'] input:checkbox").change(function() {
    var ischecked= $(this).is(":checked");
    if(!ischecked)
        alert("uncheckd " + $(this).val());
    });

</script>



how to automate checkbox that has label with ::before and ::after and input tag

Trying to automate

https://ift.tt/L3TscRK

for practice and under section CheckBox & Radio Button practice Xpath there is section for "Which automation tools/frameworks do you use?" . These have a list of checkboxes which I want to automate but they have label with ::before and ::after . Tried xpath using input tag //input[@id='serenity'] but doesn't work.

Tried xpath using input tag //input[@id='serenity'] but doesn't work.

How do I locate these checkboxes?




jeudi 23 mars 2023

How do I make my checkboxes link up with my drop down list?

I'm wanting to make an order form with multiple check boxes within a group box. However I need to link them up so that an error message occurs if the checkbox is ticked but no quantity has been chosen.

How should I go about this?

e.g. ticking the box for pepperoni pizza but not choosing a quantity limited from 1-10.

Have tried to do multiple things but nothing is working.




mardi 21 mars 2023

I want to make "onclick" effect on mobile with checkbox:checked (without using JS)

I want my dropup content to appear when I check my checkbox, but it isn't working. Dropup-content by default has visibility: collapse, so I want it to have visibility: visible when I check the checkbox. how it should look

I tried to put .dropup-content under input:checked + span but nothing change

index.html:

<label for="sports">  
  <input type="checkbox" id="sports" class="checkbox">  
  <span class="span-label">Sports</span>  
</label>  
<div class="dropup-content">  
  <a href="">More...</a>  
  <a href="">Esports</a>  
  <a href="">Handball</a>  
  <a href="">Basketball</a>  
  <a href="">Football</a>  
</div>

index.scss:

input:checked + span {
    color: orange;  //changes color of text Sports
   .dropup-content {
       visibility: visible;
       max-height: 250px; 
       transition: max-height 0.2s; 
  } 
}



How to check if there are certain consecutive checkboxes checked in javascript and add discount and the opposite

I have a form with 7 checkboxes that have a data-calculate attribute. I want to manipulate the data-attribute value when there are a consecutive 3 to 5 checked. To get the 1st discount and 3 up to 5 or more checkboxes to get the 2nd discount from my form.

I have tried many times to achieve what I want but nothing is working. Also with the else statement is kind of confusing how to remove items and working with the discounts and all.

I am sending you my whole form to check maybe someone can help me finish it.

let _log = (item) => {
  return console.log(item)
}

const week1 = document.querySelector(".c_week_1");
const week2 = document.querySelector(".c_week_2");
const week3 = document.querySelector(".c_week_3");
const week4 = document.querySelector(".c_week_4");
const week5 = document.querySelector(".c_week_5");
const week6 = document.querySelector(".c_week_6");
const week7 = document.querySelector(".c_week_7");

// Getting data attribute value
let week1Calc = week1.dataset.calculate;
let week2Calc = week2.dataset.calculate;
let week3Calc = week3.dataset.calculate;
let week4Calc = week4.dataset.calculate;
let week5Calc = week5.dataset.calculate;
let week6Calc = week6.dataset.calculate;
let week7Calc = week7.dataset.calculate;

// let sum = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
//         return parseInt(accumulator) + parseInt(currentValue);
//     });

// Output price
let price = document.querySelector(".c_final_price_1_kid");

// Initalial num
let count = 0;

// Arrays
// Selecting all inputs
let allCheckboxes = [week1, week2, week3, week4, week5, week6, week7];
// Selecting all inputs data-calculate value
let allCheckboxesCalcValues = [week1Calc, week2Calc, week3Calc, week4Calc, week5Calc, week6Calc, week7Calc];
// Adding all inputs that are checked
let checkboxesCheckedArray = [];
// Getting checkboxesCheckedArray index numbers
let checkboxesCheckedArrayNumbers = [];
// Adding the checked checkbox data-calculate attribute in the array
let checkboxesCalculateValuesArray = [];


// Selecting all checkboxes and their index
allCheckboxes.forEach((box, index) => {

  box.addEventListener("change", (e) => {

    if (box.checked) {

      // Check how many checkboxes are checked
      count++;

      // console.log(count)

      // Adding checked checkboxes to the array
      checkboxesCheckedArray.push(box);

      // Adding checked index to the array
      checkboxesCheckedArrayNumbers.push(index);

      // Sorting numbers array 
      checkboxesCheckedArrayNumbers.sort();

      checkboxesCalculateValuesArray.push(e.target.dataset.calculate);

      price.textContent = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
        return parseInt(accumulator) + parseInt(currentValue);
      });


      for (let i = 1; i < checkboxesCheckedArrayNumbers.length - 1; i++) {

        // Here are the 2 if statements. I am looking for consecutive checkboxes. 3 up to 5 and 3 up to 7

        // Check if 3 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 1] === checkboxesCheckedArrayNumbers[i] - 1 && checkboxesCheckedArrayNumbers[i + 1] ===
          checkboxesCheckedArrayNumbers[i] + 1) {

          // When there are 3 up to 5 consecutive weeks then loop here to change data-calculate values to 84.15

          price.textContent = checkboxesCalculateValuesArray.reduce((accumulator, currentValue) => {
            return parseInt(accumulator) + parseInt(currentValue);
          });

          _log(checkboxesCalculateValuesArray)


        }


        // Check if 5 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 2] === checkboxesCheckedArrayNumbers[i] - 2 && checkboxesCheckedArrayNumbers[i + 2] ===
          checkboxesCheckedArrayNumbers[i] + 2) {



        }

        // end of Check if 5 or more are in cunsecutive order

      }
      // End for loop


    } else {

      count--;

      console.log(count);

      // Adding checked checkboxes to the array
      checkboxesCheckedArray.pop(box);

      // Adding checked index to the array
      checkboxesCheckedArrayNumbers.pop(index);

      // Sorting numbers array 
      checkboxesCheckedArrayNumbers.sort();

      checkboxesCalculateValuesArray.pop(e.target.dataset.calculate);

      for (let i = 1; i < checkboxesCheckedArrayNumbers.length - 1; i++) {
        // Check if 3 or more are in cunsecutive order
        if (checkboxesCheckedArrayNumbers[i - 1] === checkboxesCheckedArrayNumbers[i] - 1 && checkboxesCheckedArrayNumbers[i + 1] ===
          checkboxesCheckedArrayNumbers[i] + 1) {


        }
        // END OF Check if 5 or more are in cunsecutive order

        // Check if 5 or more are in cunsecutive order

        if (checkboxesCheckedArrayNumbers[i - 2] === checkboxesCheckedArrayNumbers[i] - 2 && checkboxesCheckedArrayNumbers[i + 2] ===
          checkboxesCheckedArrayNumbers[i] + 2) {



        }

      }

    }

  })

})

let customForm = document.getElementsByTagName("form")[0];
const submitButton = document.querySelector(".c-main-calc-submit--button");
// _log(submitButton)

customForm.addEventListener("submit", (e) => {
  customForm.submit();
})
<form id="form">
  <div class="c-checkbox-box">
    <span>1</span>
    <input type="checkbox" class="c_week_1" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>2</span>
    <input type="checkbox" class="c_week_2" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>3</span>
    <input type="checkbox" class="c_week_3" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>4</span>
    <input type="checkbox" class="c_week_4" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>5</span>
    <input type="checkbox" class="c_week_5" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>6</span>
    <input type="checkbox" class="c_week_6" data-calculate="99">
  </div>
  <div class="c-checkbox-box">
    <span>7</span>
    <input type="checkbox" class="c_week_7" data-calculate="99">
  </div>
</form>

<div class="c_final_price_1_kid"></div>



dimanche 19 mars 2023

CheckBox with DataTemplate Control

I am using a DataGrid to display tax accounts from the DB and calculate the balances for DataGrid selection. DataGrid is filled with an "ObservableCollectionList". Each tax account has a check box. Clicking on the checkbox updates the grid, row with tax account number is removed or added to the data grid. The CheckBoxes are created in a ListBox with DataTemplate and have "ObservableCollectionList" as ItemSource. CheckBoxes with the tax account number that appear in the DataGrid Selection are displayed. Now I have the problem to collecting other checkboxes in the method that are not sent by the method (object sender, RoutedEventArgs e). Without DataTemplate for CheckBoxes it worked fine: BEFORE:

`void OnCheckBoxClick(object sender, RoutedEventArgs e)
        {
            var checkedaccounts = new HashSet<int>();
            foreach (CheckBox checkBox in ListBoxOptions.Items)
            {
                if (checkBox.IsChecked == true)
                {
                    string kto = checkBox.Name.Replace("k_", "");
                    //MessageBox.Show("CheckBox Name: " + kto);
                    int intkto = Int32.Parse(kto);
                    checkedaccounts.Add(intkto);
                }
            }

            if(JobsCollectionView != null)
                JobsCollectionView.Filter =job => checkedaccounts.Contains((job as SaldenData).StKNrFk);
      `

This doesn‘t work anymore!

Question 1: How can I collect all CheckBoxes into a List and checking if they are Checked or Unchecked? Question 2: How can I remove or add them all at once from the JobsCollectionView (DataGrid)? My syntax now:


`

public ObservableCollection\<SaldenData\> SaldenListe { get; set; }
public ObservableCollection\<StKonten\> StKontoData { get; set; }

\

`\<ListBox Name="ListBoxOptions" ItemsSource="{Binding StKontoData}" Background="Transparent" 
                 BorderThickness="0" Grid.Row="1" SelectionMode="Multiple" \>
\<ListBox.ItemTemplate\>
\<DataTemplate\>
\<CheckBox  Content="{Binding StKNummer}" IsChecked="True"
FontSize="10" Height="20" Margin="20,0,0,0" Foreground="Beige"
UseLayoutRounding="True"  Checked="cb_CheckedTrue" Unchecked="cb_CheckedFalse"

                      VerticalAlignment="Bottom" BorderThickness="1,1,1,1" HorizontalAlignment="Left" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>`

Method:

private void cb_CheckedTrue(object sender, RoutedEventArgs e)
{
string st = tb_StNr.ToString();
CheckBox tb = (CheckBox)sender;
MessageBox.Show("Line 168 OnCheckBoxClick: "+ st + " " + tb.Content + " = " + tb.IsChecked);
var checkedaccounts = new HashSet\<int\>();
if (tb.IsChecked == true)
{
            string fkto = tb.Content.ToString();
            MessageBox.Show("Line 174 CheckBox Content: " + fkto);
            int intkto = Int32.Parse(fkto);
            checkedaccounts.Add(intkto);
        }

        if (JobsCollectionView != null)
            JobsCollectionView.Filter = job => checkedaccounts.Contains((job as SaldenData).StKNrFk);

    }



How to create a button to copy rows from one table to another - APEX

I have an interactive grid page and the checkbox was created using APEX$ROW_SELECTOR. I would like to copy the rows that was selected by the user to another table when the user clicks the button.

What I tried so far?

  • I created a button and a process for the button click event. Set the process point to "Button" and selected the button I created for copying rows.

I used the following code in the process.

DECLARE
   l_selected_rows apex_application_global.vc_arr2;
BEGIN
   -- Get the selected rows from the source table
   l_selected_rows := apex_application.g_f01;
   
   -- Insert the selected rows into the destination table
   INSERT INTO destination_table
      (col1, col2, col3)
   SELECT
      col1, col2, col3
   FROM
      source_table
   WHERE
      row_id IN (SELECT column_value FROM TABLE(l_selected_rows));
   
   -- Display a success message
   apex_application.g_message := 'Selected rows copied to destination table.';
END;

But, when I run the application and click the button the selected rows data doesn't copy to the other table. What could be the problem?




samedi 18 mars 2023

How do I change the color of the checkbox to a gradient in Flutter?

I'm trying to implement a beautiful CheckBox with a gradient color in a flutter Tell me, is there a way to somehow specify Linear Gradient instead of active color without messing with the Container color?

my checkbox code

CheckBox code:

ValueListenableBuilder CheckSex(ValueNotifier<String?> sexNotifier) {
  return ValueListenableBuilder(
    valueListenable: sexNotifier,
    builder: (context, pickedSex, child) {
      return Row(
        children: ["Мужской", "Женский", "Другой"].map((String sex) {
          return Row(
            children: [
              Text(sex),
              Checkbox(
                activeColor: Colors.indigo[500],
                value: sex == pickedSex,
                onChanged: (pick) {
                  sexNotifier.value = sex;
                },
              ),
            ],
          );
        }).toList(),
      );
    },
  );
}



How to add image to a customtkinter checkbox?

So I'm trying to make a login page (using customtkinter), I finished most of the code but when it came to show password I wanted to add a image to the checkbox, I tired many methods but none of them worked for me either nothing happened or it throws an error.

This is the checkbox I'm trying to add the image to:

entry2 = ctk.CTkEntry(master=frame1, width=220, placeholder_text="Password", show="*", font=('Segoe Ui', 17))
entry2.pack(padx=10, pady=12)
entry2.place(relx=0.5, rely=login_form_y + 0.06, anchor=ctk.CENTER)

cb_va = ctk.IntVar(value=0)

def my_show():
    if cb_va.get() != 0:
        entry2.configure(show='')
    else:
        entry2.configure(show='*')

checkbox1 = ctk.CTkCheckBox(master=frame1, width=220, text="Show Password", font=('Segoe Ui', 12), variable=cb_va, onvalue=1, offvalue=0, command=my_show)
checkbox1.pack(padx=10, pady=12)
checkbox1.place(relx=0.5, rely=0.62, anchor=ctk.CENTER)

I just started using tkinter and customtkinter a few weeks back for my school project, so I have no idea what to do now.




jeudi 16 mars 2023

Error when controlling inputs of type select through a checkbox array

I have a checkbox type input whose name attribute is analysisnames[ ] and I also have several selects that I need to control through these checkboxes. What I want to get is:

  1. All the select are missing when the page loads
  2. For each checkbox you select, you must save its value and the value of the select that will appear when clicking this checkbox
  3. If I click on any other checkbox, the select of the first clicked checkbox (without the checkbox being deselected) will disappear and the select of the currently clicked checkbox will appear, and if I click on a third checkbox, the select of the second will disappear checkbox keeping said checkbox active, but only the checkbox of the last element clicked would appear.
  4. When deselecting a checkbox, the stored value of this checkbox and its select is deleted
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="librerias/bootstrap/css/bootstrap.min.css">
</head
<body>
<form class="row formularioCrearPaciente" action="php/insertarAnalisis2.php" method="post" id="FormularioRegistrarPaciente"> 

               <?php 


include("php/conexion.php");

$sql = "SELECT * FROM tipo_analisis";
  $datosnombreAnalisis = $conexion->query($sql);
  $fila = $datosnombreAnalisis->fetch_array();
    
  ?>  


                 <div class="col-md-6 form-group">
                     <label for="nombre">Nombre:</label>

                     <select class="form-select" aria-label="size 3  select example" name="nombre">
                   <option selected>Seleccione los analisis</option>
                   <?php
                        while ($row = mysqli_fetch_array($datosnombreAnalisis))

                        {
                                         
                  ?>
         <option value="<?php echo $row['nombre_analisis'];?>"> <?php echo $row['nombre_analisis'];?> 

         <input type="checkbox" name="nombresdeAnalisis[]" value="<?php echo $row[0];?>" class="delete-checkbox" id ="nombresactivados" ><?php echo $row['id_tipoanalisis']?>

      </option>

                       <?php
                    }

        
                       ?>

                       <?php
 
                       ?>
               </select>
                <div >Ids seleccionados en matriz <span id="arr"></span></div>
  <div >Ids seleccionados <span id="str"></span></div>
                     <span id="errores" class="errores"></span>

                  <div class="col-md-6 form-group">
                     <label for="fecha">Select 1</label>
                     <select  class="form-select seleccion" id="opciones1" name="opciones" style="visibility: hidden;">
                        <option>
                          Seleccione la opcion--
                        </option>
                        <option value="positivo">
                           positivo
                        </option>
                        <option value="negativo">
                           negativo
                        </option>
                     </select>

                           <label for="fecha">Select 2</label>
                     <select  class="form-select seleccion" id="opciones2" name="opciones" style="visibility: hidden;">
                        <option>
                          Seleccione la opcion--
                        </option>
                        <option value="positivo">
                           positivo
                        </option>
                        <option value="negativo">
                           negativo
                        </option>
                     </select>
                      <label for="fecha">Select 3</label>
                     <select  class="form-select seleccion" id="opciones3" name="opciones" style="visibility: hidden;">
                        <option>
                          Seleccione la opcion--
                        </option>
                        <option value="positivo">
                           positivo
                        </option>
                        <option value="negativo">
                           negativo
                        </option>
                     </select>

                     <label for="fecha">Select 4</label>
                     <select  class="form-select seleccion" id="opciones4" name="opciones" style="visibility: hidden;" >
                        <option>
                          Seleccione la opcion--
                        </option>
                        <option value="positivo">
                           positivo
                        </option>
                        <option value="negativo">
                           negativo
                        </option>
                     </select>

                  </div>
                  </div>
            
                  </div>
                   
                  <div class="col-md-6 form-group">
                     <button type="submit"id="registrarAnalisis" class="btn btn-primary">Registrar Analisis</button>
                  </div>
                  
           


            </form>

</body>
</html> 

I have created an array that loops through the number of checkboxes I have in the array

<script>
var elementos = document.getElementsByName("nombresdeAnalisis[]");

for (x=0;x<elementos.length;x++){


}

Here I have count all the activated checkboxes and I have achieved that when clicking on a checkbox, its associated select appears, but if I select another checkbox, the select disappears but the select of the new clicked checkbox does not appear

$(document).ready(function() {

  $('[name="nombresdeAnalisis[]"]').click(function() {
      
    var arr = $('[name="nombresdeAnalisis[]"]:checked').map(function(){
      return this.value;

     if (this.value == "2") {

      alert(this.value);
     }

    }).get();
    
    var str = arr.join(',');
    
    $('#arr').text(JSON.stringify(arr));
    
    $('#str').text(str);

    if ($('nombresdeAnalisis[]')[2] =="checked") {

          $("#opciones2").css("visibility","visible");
    }else{

         $("#opciones2").css("visibility","hidden");

    }if(str== "3") {

      $("#opciones3").css("visibility","visible");
    }else{

         $("#opciones3").css("visibility","hidden");

    }if(str== "4") {

      $("#opciones4").css("visibility","visible");
    }else{

         $("#opciones4").css("visibility","hidden");

    }

Here I try that for each selected select, its value is stored but obviously, it doesn't work either


    $(".seleccion").change(function(){

    
    opcionseleccionada();

  });

function opcionseleccionada(){
  var array = [];

  //for each Select  selected,
  $(".seleccion :selected").each(function(){

  //Stores the value of this select 
    var valor = array[$(this).val()];
  });
</script>



populate checkboxes list on google form

I am working on attendance form, but it takes me long time to fill up the name lists as checkboxes,

how can I modify your code to be able to populate the groups names on the form.

thank you for your help




Rshiny : How to filter the columns of a dataset with the values of a checkboxinput

I have a modular Rshiny application where I want to retrieve selected values from a checkboxgroup. These values correspond to the columns of a dataset. I want to be able to filter/display these columns if they are checked or not.

The checkboxgroupinput is in a renderUi object because I want the choices offered to be automatically read by an internal variable.

library(shiny)

mod_1_ui <- function(id) {
  ns <- NS(id)
  
  fluidRow(
    column(
      width = 3,
      uiOutput(ns("my_ui_output"))
    ),
    column(
      width = 9,
      verbatimTextOutput(ns("result"), placeholder = TRUE),
      DT::DTOutput(ns('table'))
    )
  )
}


mod_1_server <- function(id, r_global) {
  moduleServer(id, function(input, output, session) {
    
    output$my_ui_output <- renderUI({
      checkboxGroupInput(inputId = "check_col",
                         label = "Select columns to display : ",
                         choices = colnames(iris),
                         selected = colnames(iris)
                         )
    })
    
  
    selected = reactive({
      input$check_col
    })
    
    output$result = renderPrint({
      paste(selected())
    })
    
    output$table = DT::renderDataTable({
      dt = data.table(iris)
      # dt[, selected(), with = F]
    })
    
    
  })
}



ui <- fluidPage(
  mod_1_ui("mod")
)

server <- function(input, output, session) {
  r_global <- reactiveValues()
  
  mod_1_server("mod", r_global = r_global)
}

if (interactive()) {
  shinyApp(ui, server)
}



mercredi 15 mars 2023

Customtkinter checkboxes are not starting at the same x axis

I want to make a python todo app with customtkinter. When i create a checkbox which has a longer text everytime something goes wrong and for something they just go away.

Here is my code so far:

from customtkinter import *
from tkinter import *
import random

root = CTk()
root.geometry('400x600')
root.title('Todo')
root.resizable(False, False)
set_appearance_mode('light')
set_default_color_theme('blue')


#Main label
main_label = CTkLabel(root, text='Your To Do list', font=CTkFont(size=30, weight='bold'))
main_label.place(x=20, y=20)

#Under label
under_label_choices_list = [
    'This will be your best day',
    'Be productive',
    'Willpower',
]
under_label_choices = StringVar()
under_label_choices.set(random.choice(under_label_choices_list))

under_label = CTkLabel(root, textvariable=under_label_choices, text_color='#6495ED', font=CTkFont(size=15, weight='bold'))
under_label.place(x=20, y=50)

#Scrollableframe
scrollableframe = CTkScrollableFrame(root, width=300, height=400)
scrollableframe.place(x=40, y= 100)

#Add button
**def make_checkbox(event):
    global todo_entry
    checkbox = CTkCheckBox(scrollableframe, text=todo_entry.get(), font=CTkFont(size=15))
    todo_entry.destroy()
    checkbox.grid(padx=5, pady=5)


def add():
    global todo_entry
    todo_entry = CTkEntry(scrollableframe)
    todo_entry.bind('<Return>', make_checkbox)
    todo_entry.grid(padx=5, pady=5)
    todo_entry.focus()**


add_button = CTkButton(root, text='Add', command=add)
add_button.place(x=20, y=540)



root.mainloop()

I think the problem is in the bold part

Here is a picture too how it's looks like




dimanche 12 mars 2023

Rendering a row of checkboxes in a table in React

I am trying to render a row of checkboxes in a table for every ingredient present in an array of ingredients. The problem I am facing is that when I check a checkbox for a particular ingredient, all the checkboxes of for all the ingredients get checked. Can anyone help me? I am attaching the JSON for the meal as well as my solution in the code snippet. any help would be highly appreciated.

const   ItemDetails = (props) => {

    const [MealDetails, setMEalDetails] = useState([{id:'',name:'',ingredients:[]}]);
    const [checkedOne, setCheckedOne] = useState(false);
    const [checkedTwo, setCheckedTwo] = useState(false);
    const [checkedThree, setCheckedThree] = useState(false);

    useEffect(()=>{
        const fetchMealDetails = async () =>{
            const getMeal = await fetch(""+`${props.mealId}`);
            const Meal = [];
            const getMealresponse = await getMeal.json();
            Meal.push(getMealresponse)
        
            setMEalDetails(Meal);
            console.log(getMealresponse)
            console.log(Meal);
        }

    fetchMealDetails()},[])

    
   const handleChangeOne = (event,) => {
     
        setCheckedOne((prevVal,index) => !prevVal);
        setCheckedTwo(false);
        setCheckedThree(false);}
  
     
   

    return(
            <div className={classes.itemDetailContainer} >
                        <div className={classes.topRow}>
                            <h1>{MealDetails[0].name}</h1>
                            <h3><i>Quality Score: </i>100%</h3>
                            <h3><i>Price: </i>$200</h3>
                        </div>

                        <div className={classes.IngredientsTable}>
                            <table className={classes.table}>
                            <tr className={classes.tr}>
                                <th className={classes.th}>Ingredients:</th>
                                <th className={classes.th}>low</th>
                                <th className={classes.th}>Medium</th>
                                <th className={classes.th}>High</th>
                            </tr>
                            {
                                MealDetails[0].ingredients.map(
                                        (ingredient,index) =>{
                                            return( 
                                                <tr key={index}>
                                                    <td className={classes.th} >{ingredient.name}</td>
                                                    {ingredient.options.map(
                                                       (entry,index) =>
                                                        {return  <td>
                                                        <input type="checkbox" value={entry.quality} key={index} id={index} checked={checkedOne} onChange={handleChangeOne} /> 
                                                        </td>}    
                                                    )}
                                                </tr>                                                                                             
                                                
                                                
                                            )
                                        }
                                )
                            }
                               
                            </table>
                        </div>
                        <div className={classes.ButtonContainer}>
                        <Button value="Close" onClick={props.onClick}  />
                        <Button value="Add to Cart" onClick={props.onClick} />
                        </div>
                        
             </div>
    
    )
}

export default ItemDetails;

Array(1)
0
: 
id
: 
1
ingredients
: 
Array(2)
0
: 
groups
: 
(2) ['vegan', 'vegetarian']
name
: 
"Rice"
options
: 
Array(3)
0
: 
name
: 
"Long grain white rice"
per_amount
: 
"kilogram"
price
: 
3
quality
: 
"high"
[[Prototype]]
: 
Object
1
: 
{name: 'Medium grain brown rice', quality: 'medium', price: 2, per_amount: 'kilogram'}
2
: 
{name: 'Quick cooking white rice', quality: 'low', price: 1.5, per_amount: 'kilogram'}
length
: 
3
[[Prototype]]
: 
Array(0)
quantity
: 
120
quantity_type
: 
"gram"
[[Prototype]]
: 
Object
1
: 
{name: 'Chicken', options: Array(3), quantity: 85, quantity_type: 'gram'}
length
: 
2
[[Prototype]]
: 
Array(0)
name
: 
"Rice and chicken bowl"
[[Prototype]]
: 
Object
length
: 
1



Setting an HTML Checkbox to checked false via clicking on it or next to it

I created a dropdown menu, which is activated and closed by setting display to block or none, depending on the state of a checkbox.

Everything is working as it is supposed to, but I want the menu to close when I click on the checkbox, which works by default or when I click anywhere else, which also works with my script.

BUT: I am not able to accomplish both. My script works fine, but then I am unable to close the menu by clicking on the checkboxes label.

window.onclick = function(unchceck) {
  let button = document.getElementById("toggle_button");

  if (unchceck.target != button) {
    button.checked = false;
  }
}
/* highly simplified version of the CSS, just to show the function */

.expM {
  display: none;
  }
#toggle_button {
  display: none
  }
#toggle_button:checked~.expM {
  display: block; 
  }
li {
  background-color: rgb(70, 70, 70);
  }
<!-- my checkbox with a label, the checkbox is set to display: none -->
<input type="checkbox" name="test" id="toggle_button">
<label for="toggle_button">
  <img id="menuBurger" src="https://picsum.photos/20"/>
</label>


<!-- simplyfied version of my menu -->
<ul class="expM">
  <li><a class="menuLink" href="index.html">Home</a></li>
  <li><a class="menuLink" href="pages/GetStarted.html">Get Started</a></li>
</ul>

I tried multiple solutions, but none them worked. They resulted in me not being able to check the checkbox anymore or in the original premisse, that I was only able to achieve one of the two ways to uncheck the box.

Some things I tried were setting a cooldown/ timeout for the checkbox, which also did not work. I also tried to stop the function as soon, as checked = false, which worked neither.

You would help me a lot with a clean solution, making it possible to close the menu by clicking on the checkbox and by clicking anywhere on the screen.




How to get select all checkboxes in react

   <table class="table align-middle table-row-dashed fs-6 gy-5">
                        {GAMgetGroupsRights?.map((gRights) => (
                          <tbody class="text-gray-600 fw-semibold">
                            <>
                              <tr className="row">
                                <td
                                  class="col-4 text-gray-800  px-4 text-start"
                                  key={gRights?.moduleId}
                                  style=
                                >
                                  {gRights?.moduleNameEn}
                                  <i
                                    class="fas fa-exclamation-circle ms-1 fs-7"
                                    data-bs-toggle="tooltip"
                                    title="Allows a full access to the system"
                                  ></i>
                                </td>
                                <td className="col-4">
                                  <label class=" form-check form-check-sm form-check-custom form-check-solid ">
                                    <input
                                      class="form-check-input"
                                      type="checkbox"
                                      value=""
                                      id={`select-all-${gRights.accessGroupId}`}
                                      onChange={() => handleSelectAll(gRights.moduleId, "read")}
                                      // checked={checkedState[gRights.accessGroupId].viewRights}
                    
                                    />
                                    <span
                                      class="form-check-label"
                                      for="kt_roles_select_all"
                                    >
                                      Select all
                                    </span>
                                  </label>
                                </td>
                              </tr>
                              <tr>
                                <td>
                                  {gRights?.accessGroupRightsList?.map(
                                    (item) => (
                                      <td className="d-flex justify-content-between ">
                                        <label class="text-gray-800 w-200px">
                                          {item?.features?.featureNameEn}
                                        </label>
                                        <td>
                                          <div class="d-flex mx-12 ">
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                id={`${item.features.featureNameEn}_viewRights`}
                                                disabled={!item?.features?.allowedView}
                                                name={`${gRights.moduleId}_${item.features.featureNameEn}_read`}
                                                onChange={() =>
                                                  handleCheckboxChange(
                                                    gRights.moduleId,
                                                    item.features.featureNameEn,
                                                    "read"
                                                  )
                                                }
                                                checked={
                                                  checkboxState[
                                                    `${gRights.moduleId}_${item.features.featureNameEn}_read`
                                                  ] || false
                                                }
                                              />
                                              <span class="form-check-label">
                                                Read
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedAdd}
                                                name={`${gRights.moduleId}_${item.features.featureNameEn}_create`}
                                                onChange={() =>
                                                  handleCheckboxChange(
                                                    gRights.moduleId,
                                                    item.features.featureNameEn,
                                                    "create"
                                                  )
                                                }
                                                checked={
                                                  checkboxState[
                                                    `${gRights.moduleId}_${item.features.featureNameEn}_create`
                                                  ] || false
                                                }
                                              />
                                              <span class="form-check-label">
                                                Create
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedEdit}
                                                name={`${gRights.moduleId}_${item.features.featureNameEn}_update`}
                                                onChange={() =>
                                                  handleCheckboxChange(
                                                    gRights.moduleId,
                                                    item.features.featureNameEn,
                                                    "update"
                                                  )
                                                }
                                                checked={
                                                  checkboxState[
                                                    `${gRights.moduleId}_${item.features.featureNameEn}_update`
                                                  ] || false
                                                }
                                              />
                                              <span class="form-check-label">
                                                Update
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedDelete}
                                                name={`${gRights.moduleId}_${item.features.featureNameEn}_delete`}
                                                onChange={() =>
                                                  handleCheckboxChange(
                                                    gRights.moduleId,
                                                    item.features.featureNameEn,
                                                    "delete"
                                                  )
                                                }
                                                checked={
                                                  checkboxState[
                                                    `${gRights.moduleId}_${item.features.featureNameEn}_delete`
                                                  ] || false
                                                }
                                              />
                                              <span class="form-check-label">
                                                Delete
                                              </span>
                                            </label>
                                          </div>
                                        </td>
                                      </td>
                                    )
                                  )}
                                </td>
                              </tr>
                            </>
                          </tbody>
                        ))}
                      </table>

this is my code and i want that when i click on "Select All" checkbox the other checkboxes of "Read" , "Create", "UPdate" and "Delete" of that module or moduleId which are enabled should be selected and if i unchecked "Select All" the other checkboxes of "Read" , "Create", "UPdate" and "Delete" of that module or moduleId which were checked must be unchecked and if i click on save button then all the checkboxes of checked and unchecked should be sent to server in the form of list. How can I achieve it? Can anyone help me? I will highly appreciate your help.Thanks




vendredi 10 mars 2023

Make Checkbox in WPF checked by default

I have a DataGrid in a WPF page. For reasons to do with making it instantly clickable, I am not using <DataGridCheckboxColumn> but instead using a different way:

<DataGrid.Columns>
   <DataGridTextColumn Header="PathID" Binding="{Binding Path.PathID}" Width="2*"/>
   <DataGridTextColumn Header="Path" Binding="{Binding Path}" Width="5*"/>
   <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="1*"/>
   <DataGridTextColumn Header="Item Name" Binding="{Binding Item}" Width="3*"/>
   <DataGridTextColumn Header="Type" Binding="{Binding Type}" Width="1*" IsReadOnly="True"/>
   <DataGridTemplateColumn Header="Write">
      <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
            <CheckBox IsChecked="{Binding Path=IsWriteChecked ,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
         </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
   </DataGridTemplateColumn>
   <DataGridTextColumn Header="Write Value" Binding="{Binding WriteValue}" Width="2*" IsReadOnly="True"/>
</DataGrid.Columns>

That Checkbox column (called Write) is the one I want to be checked by default but I am not sure how to make this happen. Normally I would have IsChecked = true but the code example I used for the one click box found here: https://mikeborozdin.com/post/wpf-datagrid-checkbox-single-click-checkingunchecking/

This makes me use the IsChecked to set the Binding instead of setting it to True. Does anyone know how I would get the boxes to be checked by default here?




jeudi 9 mars 2023

Get a list of data from a dynamic checkbox in Kotlin

need help. I want to get data on toppings from a dynamic checkbox. When a user clicks the order button, i want the data checked in the checkbox to be sent to another activity. As in the following image.

From Detail Activity :

enter image description here

To Checkout Activity :

enter image description here

I've got the topping list using ryclerview on the Detail Activity, so the checkbox indicates that the data is dynamic.

This is my Adapter :

class AdapterTopping(val listTopping: List<DataItem?>?) : RecyclerView.Adapter<AdapterTopping.MyViewHolder>() {
    class MyViewHolder(view : View) : RecyclerView.ViewHolder(view){
        val checkbox = view.findViewById<CheckBox>(R.id.ch_box)
        val price_topping = view.findViewById<TextView>(R.id.tv_price_topping)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_topping,parent,false)
        return MyViewHolder(view)
    }

    override fun getItemCount(): Int {
        if (listTopping != null){
            return listTopping.size
        }
        return 0
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        
        holder.checkbox.text = listTopping?.get(position)?.attributes?.name

        val priceTopping = listTopping?.get(position)?.attributes?.price
        val localID = Locale("in", "ID")
        val numberFormat = NumberFormat.getCurrencyInstance(localID)
        numberFormat.minimumFractionDigits = 0
        holder.price_topping.text = numberFormat.format(priceTopping)

    }
}

This is my Detail Activity :

val btn_pesan = findViewById<AppCompatButton>(R.id.btn_pesan)
        btn_pesan.setOnClickListener {
            val intent = Intent(it.context,CheckoutActivity::class.java)
            startActivity(intent)
            finish()
        }
        
        ApiConfigFood.getService().getToppings(id).enqueue(object : Callback<ResponseFoods>{
            override fun onResponse(call: Call<ResponseFoods>, response: Response<ResponseFoods>) {
                if (response.isSuccessful){
                    if (response.body()?.data?.isNotEmpty() == true){
                        val responseBody = response.body()
                        val responseList = responseBody?.data
                        val adapterTopping = AdapterTopping(responseList)
                        rv_topping.apply {
                            layoutManager = LinearLayoutManager(this@DetailActivity)
                            setHasFixedSize(true)
                            adapterTopping.notifyDataSetChanged()
                            adapter = adapterTopping
                        }
                    }
                    else{
                        // not found data
                    }
                }
                else{
                    // not found data
                }
            }

            override fun onFailure(call: Call<ResponseFoods>, t: Throwable) {
                // error server
                Toast.makeText(this@DetailActivity, t.localizedMessage, Toast.LENGTH_SHORT).show()
            }

        })

List of toppings for Textview like the image below:

enter image description here




mercredi 8 mars 2023

When trying to use ".checked", why is it not working in JavaScript? [duplicate]

When trying to use the ".checked" property, it does not return a true value and therefore I cannot get this test code to alert when checkbox is checked.

var lower = document.querySelector("#lower");

if (lower.checked === true) {
    alert('CHECKED!');
}
<li><label for="lower"><input type="checkbox" id="lower">lowercase</label></li>

I also tried the following javascript:

var lower = document.querySelector("#lower");

if (lower.checked) {
    alert('CHECKED!');
}

also tried it with document.getElementById("lower"). Any ideas?




mardi 7 mars 2023

In Angular 14 and PrimeNG, how do I get the state of a checkbox in the click handler?

I'm using PrimeNG and Angular 14. I have a checkbox in my p-table

<p-tableCheckbox (click)="onSelectAll($event)"></p-tableCheckbox>

I would like to know if the state of the box is checked or unchecked. So I tried

onSelectAll(event: any) { if (event.checked) { this.selectedCustomers = this.customers.slice(); // select all } else { this.selectedCustomers = []; // unselect all } }

but "event.checked" is repeatedly undefined. I also tried "event.target.checked" but to no avail. How do I tell if my checkbox is checked or not?




Checkboxes in React MUI stop working after applying an inital state

So I'm loading a todo list from a json. It looks something like this:

{ 
"todos": [
{"id":1,"todo":"Do something nice for someone I care about","completed":true,"userId":26},{"id":2,"todo":"Memorize the fifty states and their capitals","completed":false,"userId":48},{"id":3,"todo":"Watch a classic movie","completed":false,"userId":4}
] ,"total":150,"skip":0,"limit":30 
} 

So when I load it and apply the "completed" to the Checkbox checked the checkbox stops working. Absolutely nothing happens when I click it.

Code:

import './App.css';
import React, { Component }  from 'react';
import { Checkbox, FormControlLabel, FormGroup } from '@mui/material';

import data from './todo-list.json';

function App() {
  return (
    <div>
      <header>
        <FormGroup>
          {data.todos.map(todo => <FormControlLabel control={<Checkbox checked={todo.completed}
        
          />} label={todo.todo} /> )}
        </FormGroup>
      </header>
    </div>
  );
}

export default App;

I also get a warning Warning: Each child in a list should have a unique "key" prop..

I tried doing something like this:

  const [isTrue, setIsTrue] = React.useState(false);
  
  return (
    <div>
      <header>
        <FormGroup>
          {data.todos.map(todo => <FormControlLabel control={<Checkbox
          checked={isTrue}
        onChange={e=> {
          setIsTrue(e.target.checked)
        }}
          />} label={todo.todo} /> )}
        </FormGroup>
      </header>
    </div>
  );

But this doesn't apply the initial state and also when I click the checkbox it clicks all the checkboxes. So my click is applied to all of the checkboxes on the screen.