jeudi 30 juin 2022

Unable to set Checkbox to Checked after refreshing and storing in Local Storage

I am currently facing an issue where I am unable to set a input box to stay checked after a refresh. I have stored the values in the local storage, even though the value is stored in the local storage; the checkbox does not remain checked. Please do help me on this! Thank you

Here is the html code:

      <div style="color: #005e95">
        <input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;"  >
        Full Download
      </div>

Here is the JS code:

_test: function(){
        let checkBox = document.getElementById("checkboxFullDownload")

        if(localStorage.getItem(`${xmlTitle} ID:${this.item._id}`) === "AllowFullDownload"){
          checkBox.setAttribute("checked",true)
          console.log("set to true")
        }

        if(checkBox.checked){
          console.log("Checked")
          localStorage.setItem(`${xmlTitle} ID:${this.item._id}`,"AllowFullDownload")
          checkBox.checked = true;
          }
  
        if(!checkBox.checked){
          console.log("Unchecked")
          localStorage.removeItem(`${xmlTitle} ID:${this.item._id}`)
          checkBox.setAttribute("checked",false)
          }
}



mercredi 29 juin 2022

function check from wxCheckListBox crash when it is called (wxwidgets)

I'm working on a application project for me with wxWidgets, and I encounter some troubles with the wxCheckListBox class. I am looking for a solution, and I saw that the check function worked well in the constructor function, but not in an event function. I have a check box "select all" who handle an event to select all check box of a list, here is my code

CheckListWindow::CheckListWindow(const wxString& name, const wxPoint& pos, const wxSize& size)
    : wxFrame(nullptr, wxID_ANY, name, pos, size)
{
    wxBoxSizer* m_sizer = new wxBoxSizer(wxHORIZONTAL);
    wxCheckListBox* m_checklist = new wxCheckListBox(this, wxID_ANY, wxPoint(20, 20), wxDefaultSize, g_vecPDF);

    wxCheckBox* m_selectall = new wxCheckBox(this, ID_CHECKBOX, wxString("Tout sélectionner"), wxPoint(10, wxDefaultPosition.y));
    m_checklist->Check(1, true); // work

    m_sizer->Add(m_selectall);
    m_sizer->Add(m_checklist);

    m_sizer->SetSizeHints(this);
}

void CheckListWindow::OnCheckBox(wxCommandEvent& evt)
{
    for (int index{ 0 }; index < static_cast<int>(g_vecPDF.size()); index++)
    {
        m_checklist->Check(index, true); // doesn't work
    }
    evt.Skip();
}

If I do that, the application crash when the event function is called. My question is, is there a way to modify the check box after his construction ?

Thank you!




Checkbox : Change root Styles

How can I change the root styles in Checkbox. This does not work.

 <CheckboxItem
                      onChange={()}
                      checked={isChecked}
                      label="Show Checkbox"
                      classes=
                    />
className=

is erroring out as well. Thank you.




mardi 28 juin 2022

Android - List View `CHOICE_MODE_SINGLE` not working

Thanks in advance to resolve this issue with android list view. This is the row of the list view adapter.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:weightSum="13"
        android:orientation="horizontal"
        android:layout_marginStart="20dp">

        <CheckBox
            android:id="@+id/chkId"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/row_que_status"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="1dip"
            android:layout_weight="2"
            android:gravity="start"
            android:text="que_status"
            android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

And I have added the list view in fragment layout

    <ListView
       android:id="@+id/studentList"
       android:layout_height="match_parent"
       android:layout_width="match_parent"
       android:choiceMode="singleChoice">
    </ListView>

And also in my fragment I have set the mStudentListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); to disable the multiple selection of the list view.

But both options not working.




onChange Event not Triggered in React JS

export default function ActionRolesPage(props) {
      const [authorities, setAuthorities] = useState([]);
      const [name, setName] = useState("");
      let list = [];
      useEffect(() => {
        getAuthorities();
      }, []);
      const getAuthorities = () => {
        doGetAllAuthorities()
          .then((res) => {
            getValidatedData(res.data, "array").map((data) => (
              list.push({ authority: data})
            ))
            setAuthorities(list);
          }).catch((e) => {
            console.log(e);
          })
      }
      const handleChange = (e) => {
        console.log(e);
        const { name, checked } = e.target
        console.log(name,checked);
        let tempUser = authorities.map((user) => (
          user.authority === name ? { ...user, isChecked: checked } : user
        ));
        setAuthorities(tempUser);
      }
    
      if(authorities.length){
        console.log(authorities);
      }
    
      
      return (
        <React.Fragment>
          <Suspense fallback={<div>Loading....</div>}>
            <div className="page-content">
              <MetaTags>
                <title>Add Role | IG One</title>
              </MetaTags>
              <Container fluid>
                <Breadcrumb
                  title="Add Role"
                  breadcrumbItems={[{ title: "Settings" }, { title: "Roles" }, { title: "Add" }]}
                />
                <Form onSubmit={handleSubmit}>
                  <Card>
                    <CardBody>
                      <Row className="mb-3">
                        <label
                          htmlFor="example-text-input"
                          className="col-md-2 col-form-label"
                        >
                          Name
                        </label>
                        <div className="col-md-8 mx-0">
                          <Input
                            className="form-control"
                            type="text"
                            name="name"
                            required
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            placeholder="Name Of User "
                          />
                        </div>
                      </Row>
                      <br></br>
                      <br></br>
                      <Row className="mb-3">
                        <CardTitle>
                          Authorities
                        </CardTitle>
                        <div className="col-md-2">
    
                          {
                           
                              authorities.map((data,index) => (
                                <>
                                  <div key={index} style=>
                                    <div className='col-md-10 mx-0 mt-2'>
                                      <Input type={"checkbox"}
                                        checked={data?.isChecked || false}
                                        name={data.authority}
                                        onChange={(e) => console.log(e)}
                                        className="form-control"
                                        style=
                                      /></div>
                                    <div>
                                      <label style= htmlFor={data.authority} className="col-md-50 col-form-label"> {data.authority}</label>
                                    </div>
                                  </div>
                                </>
                              )) 
                          }
                        </div>
                      </Row>
                      <Row className="d-flex justify-content-center mt-4">
                        <Button color="dark" type='submit' className="btn-xs" style=
                        >
                          Add Role
                        </Button>
                      </Row>
                    </CardBody>
                  </Card>
                </Form>
              </Container>
            </div>
          </Suspense>
        </React.Fragment>
      )
    } 

Here is the whole code. I want to handle multiple checkboxes but onChange Event not triggered. There is a function handleChange it calls when onChange triggered but in my case there is no error seen in console as well as not display any event at console please resolve my doubt.

I also need to update the form getting respose from backend is checked authority name array How to handle checked state in checkbox.




WPF: set false as default for all checkbox controll

I have many checkbox binding nullable bool values and when I press on the control, if it's set to false, I have to press twice to get true. Is it possible to have true as the first value or false as default when I have null for all the checkbox, for example with a style?

I've tried with this before, and it works:

<CheckBox  IsThreeState="False" IsChecked="{Binding MY_NULLABLE_PROPERTY, TargetNullValue=false}"/>

but I would like a generic solution for each control




Required checkbox with custom label in WooCommerce product review form

Hi everyone! Nice to see so helpful community here.

Is there a way to add a required checkbox to WooCommerce product review form?

Thank you!




lundi 27 juin 2022

How to uncheck V-Checkbox by default, if the V-model is an array

Within a Salesforce Visualforce Apex Page, I have a V-Flex. Within it a row of V-Checkboxes is created dynamically. Like this:

<v-flex v-for="cluster in getCluster" v-bind:key="cluster.clusterName">
    <v-checkbox v-model="selectedCluster" v-bind:label="cluster.clusterName" v-bind:color="cluster.clusterColor" v-bind:value="cluster.clusterName" v-on:change="displayData"> 
  </v-checkbox>
</v-flex>

getCluster provides data like this:

let clusterData = [];
clusterData.push({ clusterName: 'A', clusterColor: 'red' });
[...]
clusterData.push({ clusterName: 'Z', clusterColor: 'blue' });

selectedCluster is an array containing, all the names/values of the checkboxes like this: ['A', [...], 'Z']

This results in a page, where at first all boxes are checked and you can filter out values from a set of data by unchecking the corresponding box. My Goal now is to disable some of the checkboxes, but not all, while keeping their functually intact, i.e. if a box is unchecked by default, then its respective data should be filtered out by default as well.

I have tried many things, like changing the v-bind:value or v-model but all of my attempts have either not changed the checked state of the checkbox, or have disabled the boxes functionality. I have also tried adding input-value="false", as described here or only having either v-model or v-bind:value, as desribed here, but neither if these have produced the desired outcome.




How to Handle multiple checkbox with default value checked using state with some array of object [React-JS Typescript]

i'm using multiple input checkbox for my form input in react. like image bellow:

enter image description here

this is some part of my code:

interface CheckType {
  id: any;
  desc: string;
  checked: boolean;
}

interface CheckListInputProps {
  options: Array<CheckType>;
  onChange: (e: React.ChangeEvent<HTMLInputElement>, data: Array<CheckType>) => void
}

const CheckListInput: React.FC<CheckListInputProps> = ({options, onChange}) => {
  const [initOpt, setInitOpt] = useState<Array<CheckType>([])

  useEffect(()=>{
    setInitOpt(options);
  },[options])

const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
  let {value, checked} = e.currentTarget
  let index = initOpt.findIndex(item => item.id===value);
  initOpt[index].checked = checked
  setInitOpt(initOpt)
  onChange(e, initOpt);
}

  return (
    <div>
      {
        initOpt.map((item, index) => (
          <div key={index}>
            <input value={item.id} checked={item.checked} onChange={changeHandler}/>
            <label>{item.desc}</label>
          </div>
       )}
    </div>)
}

when i called this function in other file:

const ChangeHandler = (e: React.ChangeEvent<HTMLInputElement>, data: Array<any>) => {
  console.log(data);
}

const options = [
  {id: 0, desc: "GET", checked: false},
  {id: 1, desc: "POST", checked: false},
  {id: 2, desc: "DELETE", checked: false}
]

return <CheckListInput options={options} onChange={ChangeHandler}/

everything works fine. the log show what i want. but the problem is in interface the checkbox won't change into checked or unchecked. how do i fix this? is it any wrong with this checked={item.checked}




Checkbox column not getting checked in datagridview c#

I have added checkbox column in datagridview and i want that checkboxes checked if one of my column value == 1 otherwise the checkbox should be unchecked i have written following code where content loads in datagridview and that method is called at form load event but checkboxes not showing checked when first time that method is calling when method gets called second time that is working correct

DataGridViewCheckBoxColumn chkboxcolumn = new DataGridViewCheckBoxColumn();
chkboxcolumn.HeaderText = "";
chkboxcolumn.Width = 30;
chkboxcolumn.Name = "checkBoxColumn";

      if (!dgvCompany.Columns.Contains(chkboxcolumn.Name))
      {
            dgvCompany.Columns.Insert(0, chkboxcolumn);
      }
               
      for (int i = 0; i < dgvCompany.Rows.Count; i++)
      {
            if (Convert.ToString (dgvCompany.Rows[i].Cells["CompanyLead"].Value) == "1")
            {
                   dgvCompany.Rows[i].Cells["checkBoxColumn"].Value = true;
                        
            }
      }



How to check/uncheck checkbox by clicking outside specific block?

So I have a div that appears/disappears on clicking checkbox.


    <input type="checkbox" id="btn">
    <div id="box"></div>

    #box {
        display: none;
        width: 100px;
        height: 100px;
    }

    #btn:checked + #box
        display: block;
    }

But I also want to add an option to close it by clicking anywhere outside this box. How can I do it?




dimanche 26 juin 2022

How to check if a checkbox is checked when programmatically added? [duplicate]

Is there a way to check if a checkbox is checked when you programmatically add another checkbox? For example, if I have a function that adds a checkbox and then it's checked and then add another checkbox, the second checkbox determines if the first checkbox is selected or not. If the first checkbox is selected, don't show the second added checkbox. If the first checkbox is not selected, you can check the second checkbox and the first one is hidden.

The code I have below is suppose to hide any checkbox that's added after the first checkbox is selected.

$(document).on( "click", '.add', function() {
// programmatically add checkboxes
      $('.add').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div><div class='add2'>+add</div>").remove();
});
$(document).on( "click", '.add2', function() {
      $('.add2').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div>").remove();
});
// function to check is checkboxes are selected
if ($("#cover_photo_set_featured input").is(':checked')) {
    $('#cover_photo_set_featured input[type=checkbox]').each(function() {
      //Check if the box is checked
      var x = $(this).is(':checked');

      //if checkbox is NOT checked
      if(x === false) {
        //Hide the choice
        $(this).parent().hide();
      }
    });
 } else {
    $('#cover_photo_set_featured input[type=checkbox]').parent().show();
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add">+add</div>



How to update the choices of a checkbox in shiny?

I want to create an app that takes a path of a dataset and shows the variables of the dataset as items of a checkbox. My code is this:

ui <- fluidPage(
  
  #geting a dataset
  textInput("df", "Enter the path of your dataset: "),
  
  #getting the variables of dataset
  uiOutput("variables")
)
server <- function(input, output){
  
  dataTable <- reactive({
    read.csv(input$df)
  })
  
  output$variables <- renderUI({
    checkboxGroupInput("variables", "Select your variables: ", choices = names(dataTable))
  })
)

But after entering the path of dataset, it shows nothing for checkbox. How can I fix this?




samedi 25 juin 2022

Why checkbox not getting checked even when its true? [duplicate]

I have used checkbox in my react application. I don't know why it is not getting checked/unchecked on click. I am using Hashmap to get true/false and passing same to the checked attribute.

In below code - variable "checkBoxSelectedHash" is hashmap having value true/false.

Note: I did checked the console of variable "checkBoxSelectedHash" also It is getting changed correctly But don't know why it is not getting reflected in checkbox.

                <tbody>

                        {reservationSourceDetail ? reservationSourceDetail.map((value, index) => (

                          <tr key={index}>
                            <td>{value.ota_name}</td>
                            {rateCodeDetail ? rateCodeDetail.map((val) => (

                              <td style=>

                                <input className="form-check-input" type="checkbox"
                                checked={checkBoxSelectedHash[value.ota_id+"_"+val.name]}
                                onChange={() => handleCheckBox(value.ota_id, val.name)}
                                /> 
                                
                              </td>

                            )) : ""}

                          </tr>
                        )) : ""

                        }
                      </tbody>

For on change handleCheckBox function below :

const handleCheckBox = (ota_id, rate_code_name) => {

    let temp_checkBoxSelectedHash = checkBoxSelectedHash;

    temp_checkBoxSelectedHash[ota_id+"_"+rate_code_name] = !temp_checkBoxSelectedHash[ota_id+"_"+rate_code_name];

    setCheckBoxSelectedHash(temp_checkBoxSelectedHash);
  }



Element ... is not clickable at point (323, 690). Other element would receive the click

I tried to build a code to repeat the search on a website. I follow a number of method from the forum but still failed to resolve the below issue. Below error message was popped up when I tried to click the checkbox "Ensuite". See if anyone knows how to resolve it.

Error Message selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at point (323, 690). Other element would receive the click: ...

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
web = webdriver.Chrome()
url = 'https://www.spareroom.co.uk/flatshare/search.p'
wait = WebDriverWait(web, 20)
web.get(url)
wait.until(EC.element_to_be_clickable((By.ID, 'onetrust-accept-btn-handler'))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.panel-tab > a:nth-child(2)'))).click()
web.find_element(By.ID, "search_by_location_field").clear()
web.find_element(By.ID, "search_by_location_field").send_keys("KT5")
web.find_element(By.ID,"search-button").click()
web.maximize_window()

#To check the "Ensuite" checkbox ==> failed to select the option and with error
wait.until(EC.element_to_be_clickable((By.XPATH, '/html[1]/body[1]/main[1]/div[2]/aside[1]/form[1]/div[1]/div[1]/section[7]/div[3]/div[1]'))).click()

#To click the button "Apply filters" 
wait.until(EC.element_to_be_clickable((By.XPATH, '/html[1]/body[1]/main[1]/div[2]/aside[1]/form[1]/div[1]/div[1]/div[1]/div[1]/button[1]'))).click()



How to convert a long checkbox to slider checkbox with search option in shiny?

I wanted to have a checkbox in my shiny app. But it has a lot of items. I wanted to have a slider with checkbox items with an option to search, too. Is there any way to do this in shiny?




vendredi 24 juin 2022

Check box not working when called as a function

I am working on a flutter-dart application. I have to make a check box. I tried making the text box in Row under scaffold and it worked. Now I made a checkBox function and tried calling it instead of having entire code twice(since I had to repeat the similar task) and I am not able to check the text box. I am not getting where I am going wrong

Defined boolean

bool agreeTerms = false;

Function

CheckBox(String conditionText, bool agree) {
return Row(
  children: [
    Material(
      child: Transform.scale(
        scale: 1.25,
        child: Checkbox(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5)),
          value: agreeTerms,
          onChanged: ((value) {
            setState(() {
              agree = value ?? false;
            });
          }),
        ),
      ),
    ),
    Text(
      conditionText,
      style: TextStyle(fontSize: 10),
      overflow: TextOverflow.ellipsis,
    ),
  ],
);

Calling the Function, inside the scaffold.

Row(
                  children: [
                    (CheckBox(
                        'Terms and condition here',
                        agreeTerms)),
                  ],
                )



jeudi 23 juin 2022

tristate || value != null': is not true for a list of CheckBoxListTiles

I am facing this error all of a sudden even when I havn't changed any logic in my code. So apparently the list of CheckBoxListTiles is not being built and this error is being thrown to me. I have no idea why it is being thrown since this is my first time facing this error. Thanks in advance for the help. Also I am attaching the Widget below to which the error is pointing to.

Widget checklistOptions1(String title) {
    return CheckboxListTile(
      title: Text(
        title,
        style: Theme.of(context).textTheme.subtitle1,
      ),
      value: values1[title],
      onChanged: (isFalse) {
        setState(() {
          values1[title] = isFalse!;
        });
      },
      activeColor: redAccentColor,
      checkboxShape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(4),
      ),
      controlAffinity: ListTileControlAffinity.trailing,
    );
  }

This is the widget to which the error is pointing to and I dont see anything wrong with it although this widget was working perfectly fine a while ago.




mercredi 22 juin 2022

CheckBox state saved on async Storage but checkbox is not saved

I've been trying to do this little demo for AsyncStorage, I can save a Profile successfully (username and password) but the checkbox is the problem, the value is saved successfully as true but the checkbox returns to false every time you refresh.

This is the App.js:

/* eslint-disable no-undef */
/* eslint-disable react-native/no-inline-styles */
// In App.js in a new project
import React, { useState, useEffect }from 'react';
//import type { Node } from 'react';
import {
  TextInput,
  Button,
  View
} from 'react-native';

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import AsyncStorage from '@react-native-async-storage/async-storage';
import BouncyCheckbox from "react-native-bouncy-checkbox";


class App extends React.Component {
  static navigationOptions = { headerShown: false };

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      checked: false
    }
    this.getData();
  }

  componentDidMount () {
    console.log('success')
  }


  onSubmit = async () => {
    try {
      await AsyncStorage.setItem('userprofile', JSON.stringify({
        username: this.state.username,
        password: this.state.password
      }))

      console.log('Username saved =====> ', this.state.username)
      console.log('Password saved =====> ', this.state.password)
      console.log('State Checkbox saved =====> ', this.state.checked)
    } catch (e) {
      console.log(e)
    }
  }

  storeData = () => {
    this.setState(prevState => ({ checked: !prevState.checked }))
    if (this.state.checked == true) {
      AsyncStorage.setItem("@storage_Key", JSON.stringify(this.state.checked));
      console.log('State Checkbox saved =====> ', this.state.checked)
    }
  }

  getData = async () => {
    try {
      //Asyn state on full profile
      const userprofile = await AsyncStorage.getItem('userprofile')
      const _userprofile = JSON.parse(userprofile)

      if (_userprofile !== null) {
        this.setState({ ..._userprofile })
      }

      AsyncStorage.getItem("@storage_Key").then((value) => {
      if (value != null) {
        this.setState({
          checked: true
        })
        console.log('State Checkbox recovered 3: ', this.state.checked)
      }
    })
    console.log('State Checkbox recovered 2: ', this.state.checked)


      console.log('Username recovered: ', this.state.username)
      console.log('Password recovered: ', this.state.password)
      console.log('State Checkbox recovered: ', this.state.checked)
    } catch (e) { console.log(e) }
  }

  clearData = async () => {
    try {
      await AsyncStorage.clear();
      console.log('Credenciales eliminadas')
    } catch (e) { console.log(e) }
  }




  render() {
    return (
      <View style=>
        <View style=></View>
        <KeyboardAwareScrollView>
          <View style=>
            <View style=>
              <TextInput
                placeholder="E-Mail..."
                value={this.state.username}
                onChangeText={val => this.setState({ username: val })}
              />
            </View>
            <View style=>
              <TextInput
                placeholder="Password..."
                value={this.state.password}
                onChangeText={val => this.setState({ password: val })}
              />
            </View>
            <View style=></View>
            <BouncyCheckbox
              fillColor="red"
              unfillColor="#FFFFFF"
              text="Recuérdame"
              isChecked={this.state.checked}
              onPress={() => this.storeData}
            />
            <View style=></View>
            <Button title="Submit Login" onPress={this.onSubmit} />
            <Button title="Clean" onPress={this.clearData} />
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }
}

export default App;

The purpose on this demo is to be able to remember the credentials like username and password when the checkbox is toggled and to clear them when untangle it. Any help or corrections you can point would be appreciated.




checkbox django return all false

My checkbox always return False value my model

ho_so_giu=models.BooleanField(default=False)

my form

 ho_so_giu = forms.BooleanField(label="Hồ sơ giữ", widget=forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'ho_so_giu_text', 'name': 'ho_so_giu_text',}),required=False)

in my html template

<div class="form-check form-switch">
     
     <label class="form-check-label" for="ho_so_giu_text">Hồ sơ giữ</label>
</div>

in my view,

print(form.cleaned_data["ho_so_giu"])  ## return False
print(request.POST.get("ho_so_giu"))   ## return None
print(request.GET.get("ho_so_giu"))    ## return None

if I try to print ho_so_giu_text it show errors

    print(form.cleaned_data["ho_so_giu_text"])
KeyError: 'ho_so_giu_text'

I am using ajax to return my value from code

ho_so_giu =$('#ho_so_giu_text').val() //return on

Thanks for reading anh help me




mardi 21 juin 2022

React checkbox show and hide card

I'm new in react and i'm trying to do a catalog with checkbox. I want to hide "x" card base on the checkbox selected and show all if none checkbox is checked. But i'm absolutly lost and don't have any idea about how i can do it.

I'm using react components, router-dom and Material UI for the checkbox.

So far this is the Checkbox component:

const CheckBox = () => {
const [checked, setChecked] = useState(
    listItems.map((i) => false)
);

const handleCheck = e => {
    setChecked(!checked)
    const result = e.target.value;
    checked === true ? handleCategory(result) : handleAllCategory();
}

const handleCategory = value => {
    const card = document.getElementsByClassName(value);
    const allCards = document.getElementsByClassName('container-card');

    for(let i = 0; i < allCards.length; i++){
        allCards[i].style.display = 'none'
    }

    for(let i = 0; i < card.length; i++){
        if(card[i].classList.contains(value)){
            card[i].style.display = 'block';
        }
    }
}

const handleAllCategory = () => {
    const allCards = document.getElementsByClassName('container-card');

    for(let i = 0; i < allCards.length; i++){
        allCards[i].style.display = 'block'
    }
}

return (
<>
    <Box sx=>
        <FormGroup >
            {listItems.map((item) => {
                return(
                    <FormControlLabel key={item.id} label={item.title} 
                        control={<Checkbox 
                            value={item.value}
                            onChange={(e) => handleCheck(e)}
                        />}
                    />
                )
            })}
        </FormGroup>
    </Box>
</>
)

}

This is the list of items i'm mapping:

const listItems = [
{
    id: 1,
    title: 'Todos los Productos',
    value: 'Todos',
},
{
    id: 2,
    title: 'Bateas Ultrasonido',
    value: 'Batea',
},
{
    id: 3,
    title: 'Diagnostico Directo',
    value: 'DiagnosticoDirecto',
},
{
    id: 4,
    title: 'Electrónica / Portones automáticos',
    value: 'Porton',
},
{
    id: 5,
    title: 'Escáneres',
    value: 'Escaner',
},
{
    id: 6,
    title: 'Escáneres Profesionales AUTEL',
    value: 'EscanerProfesional',
},
{
    id: 7,
    title: 'GNC',
    value: 'Gnc',
},
{
    id: 8,
    title: 'Proyectos Especiales',
    value: 'ProyectosEspeciales',
},
{
    id: 9,
    title: 'Tacómetro',
    value: 'Tacometro',
},
{
    id: 10,
    title: 'Testers',
    value: 'Testers',
},

]

And all of that should display, or not, this component:

const CardCatalogo = () => {
return (
<>
    <div className='card-section'>
        {CardAllItems.map(item => {
            return(
            <div className={`container-card ${item.type}`} key={item.id}>
                <div className="img-card">
                    <img src={require('../assets/' + item.image + '.png')} alt={item.title} />
                </div>
                <div className="info-card">
                    <h3 className="title-card">{item.title}</h3>
                    <p className="price-card">{'$' + item.price}</p>
                    <div className="buttons-card">
                        <button className="more-button">Info</button>
                        <button className="buy-button">Comprar</button>
                    </div>
                </div>
            </div>
            )
        })}       
    </div>
</>

) }

The object i use for the card is something like this:

{
    id: 1,
    image: 'diagnostico_directo/osciloscopio_automotriz',
    title: 'Osciloscopio Automotriz',
    price: '28.400,00',
    type: 'DiagnosticoDirecto',
},
{
    id: 2,
    image: 'diagnostico_directo/probador_mariposas_motorizadas',
    title: 'Probador Mariposas Motorizadas',
    price: '22.176,00',
    type: 'DiagnosticoDirecto',
},
{
    id: 3,
    image: 'diagnostico_directo/probador_motores_paso_a_paso',
    title: 'Probador de Motores Paso a Paso',
    price: '4.400,00',
    type: 'DiagnosticoDirecto',
},{
    id: 4,
    image: 'escaneres/escanes_autolink_629',
    title: 'Escaner Autolink 629',
    price: '35.213,00',
    type: 'Escaner',
},
{
    id: 5,
    image: 'escaneres_profesionales/maxiCheck_MX808',
    title: 'MaxiCheck MX808',
    price: '78.000,00',
    type: 'EscanerProfesional',
},
{
    id: 6,
    image: 'escaneres_profesionales/maxisys_Cv',
    title: 'Maxisys Cv',
    price: '496.000,00',
    type: 'EscanerProfesional',
},
{
    id: 7,
    image: 'escaneres_profesionales/maxiSys_MS906',
    title: 'MaxiSys MS906',
    price: '240.000,00',
    type: 'EscanerProfesional',
},

There are 64 items but all of them have the same keys.

The Checkbox component and the itemList are in the same file. The CardCatalogo is in a different file. In the function "handleCategory" and "handleAllCategory" i'm taking the class as reference an the value of the checkbox to compare. I know, it is an absolute mess, but i have no more ideas of what i should do. If someone wants to take a closer look this is my repo https://github.com/Alvaro0096/Fabianesi-page Both files and the one that contains the object for the card are in src/components...




lundi 20 juin 2022

When the checkbox checked I want to appear a select tag

In my template i'm writing a form. But there is a problem. I want to show a dropdown select menü if checkbox is checked. Otherwise it won't be visible. Here is my codes:

<label for="webcam">Webcam*</label>

    <input type="checkbox" name="webcam" value="checkbox">

     <select>
       <option value="1">1</option>
       <option value="2">1</option>
       <option value="3">1</option>
       <option value="4">1</option>
     </select>



Checkboxes not working, they all control the original one created I have adjusted many times and cant seem to get it right

Checkboxes are being created in displayBookCard() but Im not understanding whats causing this. I ended up adding a spexific class to each individual checkbox but doesnt seem to help.

https://codepen.io/migijc/pen/QWQRwvN

let displayBookCards = function (index){
    let bookCard= document.createElement("div");
    let removeButton=document.createElement("button")
    removeButton.textContent="Remove Book"
    let titleToDisplay=document.createElement('h4');
    titleToDisplay.classList.add("titleToDisplay")
    let authorToDisplay=document.createElement("h4");
    let pagesToDisplay= document.createElement('h4');
    let hasReadToDisplay=document.createElement('h4')
    booksGrid.appendChild(bookCard)
    bookCard.appendChild(titleToDisplay)
    bookCard.appendChild(authorToDisplay)
    bookCard.appendChild(pagesToDisplay)
    bookCard.appendChild(hasReadToDisplay);
    bookCard.appendChild(removeButton);
    removeButton.classList.add("removeButton")
    bookCard.classList.add("bookCards")
    body.appendChild(booksGrid)
    myLibrary.forEach((item) => {
        titleToDisplay.textContent=item.bookName
        authorToDisplay.textContent= `By: ${item.bookAuthor}`;
        pagesToDisplay.textContent=`Pages: ${item.bookPages}`;
        hasReadToDisplay.textContent=`Book Read: ${item.bookRead}`;
    });
        // bookCard.appendChild(toggleButtonContainer)
        booksGrid.classList.add("showing")
        removeBook(removeButton);
        bookCard.setAttribute("data-index", index)
        addClassToRemoveButton(removeButton)
        removeClassFromRemoveButton(removeButton)
        appendToggle(bookCard, index)
     

};

  let appendToggle= function (bookCard,index) {
    let toggleButtonContainer=document.createElement("div")
    let toggleButton=document.createElement("input")
    let toggleLabel=document.createElement('label')
    toggleButtonContainer.setAttribute("class", "toggleButtonContainer")
    toggleButton.setAttribute("value", "notRead")
    toggleButton.setAttribute("type","checkbox")
    toggleButton.setAttribute("class", "toggle")
    toggleButton.setAttribute("name", "toggleStatus")
    toggleButton.setAttribute("id", "toggleStatus")
    toggleLabel.setAttribute("for", "toggleStatus")
    toggleButtonContainer.appendChild(toggleButton)
    toggleButtonContainer.appendChild(toggleLabel)
    bookCard.appendChild(toggleButtonContainer)
    toggleButton.classList.add(index)
  }



Saving CheckBox States When Switching Between Activities (Kotlin)

I'm making an Android app in Android Studio for my girlfriend to help her keep track of her tasks at work. The app has multiple to-do lists using RecyclerView. Since each checklist has their own activity, and she will be switching between them, how do I save which boxes have been checked so that they remained checked when switching between activities? Here is the RecyclerView adapter code for one of the to-do lists that also contains the Checkbox code.

package com.mattkalichman.coffee

import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.checkbox_row.view.*

class ThreeHourPullAdapter(var list: ArrayList<Data>) :
    RecyclerView.Adapter<ThreeHourPullAdapter.ViewHolder>() {

    private var titles =
        arrayOf(
            "Log into the handheld under Pull to Thaw.",
            "Count anything left on pastry cart (BOH).",
            "Count everything on front pastry cart (FOH).",
            "Put remaining pastries from BOH on FOH cart. Remember to FIFO!",
            "Pull from freezer to BOH cart. Adjust number of pulled items according to inventory.",
            "When pull is done, press complete pull at the bottom of the screen.",
            "Date all pastries with sticker gun by standards. (Marshmallow Dream Bars, Madelines, Chocolate Madelines, All Other Pastries)",
            "Make sure to hang sticker gun back on cart & plug handheld back in."
        )

    var checkBoxStateArray = SparseBooleanArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val context = parent.context
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.checkbox_row, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.checkbox.isChecked = checkBoxStateArray.get(position, false)

        holder.checkbox.text = titles[position]

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var checkbox: CheckBox = itemView.checkbox

        init {

            checkbox.setOnClickListener {
                if (!checkBoxStateArray.get(adapterPosition, false)) {
                    checkbox.isChecked = true
                    checkBoxStateArray.put(adapterPosition, true)
                } else {
                    checkbox.isChecked = false
                    checkBoxStateArray.put(adapterPosition, false)
                }

            }
        }
    }
}



Mat-Checkbox not working: What could the problem be?

This is what I tried doing:


<h1 mat-dialog-title> Service settings </h1>
<div class="inputgrid">
    <label for="visualizationInput"> Visualization server address </label>
    <input id="visualizationInput" matInput type="text" name="visualization" [value]="server"
        (input)="server = $event.target.value">
    <label for="lookupInput"> Assembly service address </label>
    <input id="lookupInput" matInput type="text" name="lookup" [value]="lookup" (input)="lookup = $event.target.value">
    <label for="gatewayInput"> API gateway address </label>
    <input id="gatewayInput" matInput type="text" name="gateway" [value]="gateway"
        (input)="gateway = $event.target.value">
    <input type="checkbox" id="gltf" (click)="ShowGLTFDataFormat()" /> Activate GLTF Data Transfer Format
</div>
    <mat-checkbox (change)="ShowGLTFDataFormat()">Activate GLTF Data Transfer Format</mat-checkbox>
<div mat-dialog-actions>
    <button mat-button (click)="onNoClick()">Discard</button>
    <button mat-button cdkFocusInitial (click)="updateAddresses()">Save</button>
</div>

My module.ts looks somewhat like this.

import { NgModule } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PortalModule } from '@angular/cdk/portal';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { CdkStepperModule } from '@angular/cdk/stepper';
import { CdkTableModule } from '@angular/cdk/table';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
import { OverlayModule } from '@angular/cdk/overlay';
import { MatFormFieldModule } from '@angular/material/form-field';

@NgModule({
    exports: [
        A11yModule,
        ClipboardModule,
        CdkStepperModule,
        CdkTableModule,
        CdkTreeModule,
        DragDropModule,
        MatAutocompleteModule,
        MatBadgeModule,
        MatBottomSheetModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatDividerModule,
        MatExpansionModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatNativeDateModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatFormFieldModule,
        OverlayModule,
        PortalModule,
        ScrollingModule,
    ]
})
export class MaterialModule { }

But I keep getting this error: 5 - error NG8001: 'mat-checkbox' is not a known element:

  1. If 'mat-checkbox' is an Angular component, then verify that it is part of this module.
  2. If 'mat-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

13 <mat-checkbox (change)="ShowGLTFDataFormat()">Activate GLTF Data Transfer Format

I don't know what's wrong and I would extremely appreciate any help whatsoever about this as I am new to coding and I need this done as soon as possible.




How to get a checkbox in Angular?

My code looks somewhat like this.

<div class="inputgrid">
    <label for="visualizationInput"> Visualization server address </label>
    <input id="visualizationInput" matInput type="text" name="visualization" [value]="server"
        (input)="server = $event.target.value">
    <label for="lookupInput"> Assembly service address </label>
    <input id="lookupInput" matInput type="text" name="lookup" [value]="lookup" (input)="lookup = $event.target.value">
    <label for="gatewayInput"> API gateway address </label>
    <input id="gatewayInput" matInput type="text" name="gateway" [value]="gateway"
        (input)="gateway = $event.target.value">
    <mat-checkbox [checked]="gltf"> Activate GLTF Data Format </mat-checkbox> 
</div>

And on the typescript end, my code looks somewhat like this.

constructor(public settingsDialogRef: MatDialogRef<SettingsDialog>, public asmLoadServ: AssemblyFetchService, public engServ: EngineService) { }

    onNoClick(): void {
        this.settingsDialogRef.close();
    }

    public ngOnInit(): void {
        this.server = this.asmLoadServ.serverAddress;
        this.lookup = this.asmLoadServ.customLookupAddress;
        this.gateway = this.asmLoadServ.customGatewayAddress;
        this.gltf = this.engServ.isGLTF;
    }

    public updateAddresses(): void {
        this.asmLoadServ.customLookupAddress = this.lookup;
        this.asmLoadServ.customGatewayAddress = this.gateway;
        this.asmLoadServ.serverAddress = this.server;
        this.engServ.isGLTF = this.gltf;
        this.settingsDialogRef.close();
    }

I added the at the end and the subsequent value for the same will be value of gltf in typescript which is a boolean. In a different file, if the value of 'gltf' is marked as true, a different function is invoked. Now that I have explained what I intend on doing, I just wanted to know how to properly make the checkbox in this regard? All help will be appreciated. I am very new in coding so this question might appear trivial but it would mean a lot if it's answered with the exact code. :)




dimanche 19 juin 2022

Two download buttons(download all and download selected)

I have many data with checkbox in each row. If I click download all, all the list items are downloaded but if I select a few checkboxes and download selected only the selected items are downloaded. So my question is I have two buttons, how to make two separate "actions" for two buttons in the same "form"?




Is checkbox checked true or false // C# Selenium

I am struggling with a simple Checkbox on Side:

https://eas.forexsb.com/

Navigate on top into the blue line to the second DropDown and switch from Generator to Reactor. Than navigate to "3. Generator settings"

The Checkbox "Generate strategies with Preset Indicators" make trouble for me.

My goal is to identify if this is checked or not. If not it should be checked.

In HTML i always find the same.

Checked=
<input class="busy-disabled" id="use-preset-indicators" type="checkbox">
Unchecked=
<input class="busy-disabled" id="use-preset-indicators" type="checkbox">

Than i searched a lot around and found some nice looking examples. Like this one: But there is no Attribute(?)

                //if (!element.GetAttribute("disabled").isEmpty())// && element.GetAttribute("disabled").contains("disabled"))
                //{
                //    //System.out.println("Disabled must be present");
                //    checkBoxStatus = "disabled";
                //    Assert.assertTrue(true);
                //}
                //else
                //{
                //    //System.out.println("Should not it be enabled  ?  or do we need if-else to handle that part as well.");
                //    Assert.assertTrue(false);
                //}

Or another Example starts with this line. But i got the response that IWebelement cannot be convertet to Webelement:

WebElement element = webdriver.FindElement(By.XPath("//span[@title='fieldItem']//preceding-sibling::input"));

Than there is a pretty cool looking code, but i have no isEnabled()...

boolean enabled = driver.findElement(By.xpath("//xpath of the checkbox")).isEnabled();

Did you have an idea how to solf my problem? I only want to check the status and enable/check the checkbox if it is not checked.




using checkbox hack to close a dialog

I learned checkbox hack on stackoverflow the other day and I successfully applied it to making a dialog to open on click of a text. However, now I want to close the dialog when "X" is clicked. Below is what I have attempted up to now, but to no avail:

https://jsfiddle.net/gmcy12zv/5/

HTML

<div style="height:100px">

</div>

<div class="tooltip">
        <input type="checkbox" id="clickhere" />
        <label for="clickhere">
           <div class="click-msg">click here</div>
        </label>
        <div class="tooltiptext">
            <input type="checkbox" id="closeCheck"/>
            <label for="closeCheck">
              <div class="close">
                X
              </div>
            </label>
            <h1 class="tooltip-title">should open on click</h1>
            <p class="tooltip-msg"> close when X is clicked</p>
        </div>
</div>

I want "tooltiptext" to disappear when X button for div "close" is clicked.

CSS

#clickhere {
  display: none;
}

#clickhere:not(:checked) ~ .tooltiptext {
  display:none;
} 

#clickhere:checked ~ .tooltiptext {
  visibility: visible;
}

#closeCheck {
  display: none;
}

/* #closeCheck:not(:checked) ~.tooltiptext {
  visibility: visible;
} */

#closeCheck:checked ~.tooltiptext {
  display:none;
}

.click-msg{
 font-weight: 400;
font-size: 10px;
line-height: 20px;
}

.tooltip-title {
font-weight: 700;
font-size: 10px;
line-height: 20px;
}
.tooltip-msg{
  font-weight: 400;
font-size: 10px;
line-height: 20px;
}

.tooltip .close{
  position: absolute;
  top: 5px;
  right: 5px;
}

.tooltip {
  text-align: right;
  position: relative;
  display: block;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;

  position: absolute;
  z-index: 1;
}

/* .tooltip:hover .tooltiptext {
  visibility: visible;
} */

.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  border-style: solid;
  border-width: 5px;
}

.tooltip .tooltiptext {
  width: 120px;
  bottom: 150%;
  left: 80%;
  margin-left: -60px;
}

.tooltip .tooltiptext::after {
  top: 100%;
  left: 90%;
  margin-left: -5px;
  border-color: black transparent transparent transparent;
}

where am I going wrong in my approach ? is this because two checkboxes are almost nexted?




samedi 18 juin 2022

Is there a way to get a checkbox to make several elements disappear without js?

I'm trying to make a sort of "cover" for a text post. However, the checkbox I coded with display: none is not working. I am not sure if it's because of the hierarchy, or because I added a hover to make it spin. I've tried moving it around and taking out the hover but it doesn't work. While I know this would be easier made with js, the platform I'm going to use this at doesn't support Js.

Here is the part of the html code, I'm working on. I want everythin inside "doubleport" to disapear, with a fade out transition.

<div class="doubletrouble"> 
   
   <div class= "doubleport" id="porting"> <div class= "menu"><label id=portbtnx> <input type="checkbox"> Double<br>Trouble</label> 
        <div id= portdata> Dato desu </div>
         <div id= portdata> Dato largo </div> 
      </div>
<div class= "doubledisp">
  <div id= "portleft"></div><div id="portright"></div>
</div></div>

then the css for the checkbox formating

.menu #portbtnx{
  width: 125px;
  height: 125px;
  background: radial-gradient( 
    rgba(252,255,200,1) 5%,
    rgba(229,180,59,1) 35%,
     rgba(91,16,134,1) 90%);
  margin: 5px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  clip-path: polygon(20% 0%, 0% 20%, 30% 50%, 0% 80%, 20% 100%, 50% 70%, 80% 100%, 100% 80%, 70% 50%, 100% 20%, 80% 0%, 50% 30%);
  color: (--spacepurp);
  font-family: 'Lobster', cursive;
  font-size: 20px;}

.doubletrouble #portbtnx:hover {
  animation: spin 6s;}

@-moz-keyframes spin { 
    100% { -moz-transform: rotate(360deg); } 
}
@-webkit-keyframes spin { 
    100% { -webkit-transform: rotate(360deg); } 
}
@keyframes spin { 
    100% { 
        -webkit-transform: rotate(360deg); 
        transform:rotate(360deg); 
    } 
}

Lastly the code I have for the checkbox and transition:

.doubletrouble input[type=checkbox]{display:none}

input[type=checkbox label="portbtnx"]:checked~ .doubleport .menu .doubledisp {
    display: none;
  animation: disapear 4s;
}

@keyframes disapear{ from {opacity:1} to {opacity:0;}}

If anyone can help it'd be extremely appreciated. Cheers!

Here is the full code so far, please note that the css is not finished. Since it's quite long I decided to keep the snips as well.

.doubletrouble{
  height: 815px;
  width: 640px;
  background-color: var(--spacepurp, #3f1d59);
  padding: 10px;
}

.doubletrouble .doubleport{
 height: 795px;
 width: 620px; 
background:  linear-gradient(0deg, rgba(175,135,34,1) 0%, rgba(91,16,134,1) 50%, rgba(175,135,34,1) 100%);; 
  padding: 10px;}

.doubleport .doubledisp{
  display: flex;
  possition: relative;
  z-index: 1;
}

.doubleport #portleft{  
  height: 795px;
  width: 325px;
   background-image: url(https://i.imgur.com/nJr1QCa.png);
  clip-path: polygon(0 0, 100% 0%, 90% 100%, 0 100%);
  margin-right: -10px;
  
}
.doubleport #portright{
  height: 795px;
  width: 325px;
  clip-path: polygon(10% 0%, 100% 0%, 100% 100%, 0% 100%);
  background-image: url(https://i.imgur.com/SuO1nGg.png);
  margin-left: -10px;
}
.doubleport .menu{
  position: absolute;
  display: inline;
padding: 270px;
  width: 150px;
  margin-top: 100px;
  margin-left: -30px;
  z-index: 2;
}
.menu #portbtnx{
  width: 125px;
  height: 125px;
  background: radial-gradient( 
    rgba(252,255,200,1) 5%,
    rgba(229,180,59,1) 35%,
     rgba(91,16,134,1) 90%);
  margin: 5px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  clip-path: polygon(20% 0%, 0% 20%, 30% 50%, 0% 80%, 20% 100%, 50% 70%, 80% 100%, 100% 80%, 70% 50%, 100% 20%, 80% 0%, 50% 30%);
  color: (--spacepurp);
  font-family: 'Lobster', cursive;
  font-size: 20px;}

.doubletrouble #portbtnx:hover {
  animation: spin 6s;}

@-moz-keyframes spin { 
    100% { -moz-transform: rotate(360deg); } 
}
@-webkit-keyframes spin { 
    100% { -webkit-transform: rotate(360deg); } 
}
@keyframes spin { 
    100% { 
        -webkit-transform: rotate(360deg); 
        transform:rotate(360deg); 
    } 
}

.doubleport #portdata{
  margin: 5px;
  margin-left: -5px;
  margin-top: 10px;
  text-align: center;
  background: linear-gradient(90deg, rgba(91,16,134,1) 0%, rgba(229,180,59,1) 50%, rgba(252,255,200,1) 100%);
  color: (--spacepurp);
  font-family: 'Lobster', cursive;
  opacity: .8;
}
#portdata:hover{background: linear-gradient(90deg, 
   rgba(252,255,200,1) 0%, 
   rgba(229,180,59,1) 50%, rgba(91,16,134,1) 100%);
opacity: 1;
transition: opacity .35s ease-in-out;
   -moz-transition: opacity .35s ease-in-out;
   -webkit-transition: opacity .35s ease-in-out; }

.doubletrouble input[type=checkbox]{display:none}

input[type=checkbox label="portbtnx"]:checked~ .doubleport .menu .doubledisp {
    display: none;
  animation: disapear 4s;
}

@keyframes disapear{ from {opacity:1} to {opacity:0;}}
<head> <link rel="stylesheet" href="https://files.jcink.net/uploads2/nikudoesthings/nikullection_icons/nikuicons.css"/> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">  </head>
<body> 
 <div class="doubletrouble"> 
   
   <div class= "doubleport" id="porting"> <div class= "menu"><label id=portbtnx> <input type="checkbox"> Double<br>Trouble</label> 
        <div id= portdata> Dato desu </div>
         <div id= portdata> Dato largo </div> 
      </div>
<div class= "doubledisp">
  <div id= "portleft"></div><div id="portright"></div>
</div></div>
  
  <div class= "dobletitle">
    
    <div class= "mojinaka">
      <div class="mojihako">
        <div class= "mojisoto"> 
        </div>
          </div>
  </div>
      </div>
  
  
  </div> </body> 



How to compile a list of other lists by checkbox?

I'm trying to write a cell formula which can essentially create a single playlist of songs.

Currently the songs are grouped by decade, but I'd like to be able to see a single list of everything that has been ticked.

I tried an array formula, but it only returned the first ticked song. Plus not sure how to make the array formula include the adjacent lists.

Attempt 1

I tried a FILTER function, it works for one list of songs, but I don't know how to get it to append the other lists on the end.

Attempt 2

Could I use a QUERY function? Not sure how though.

Many thanks!

Song lists




vendredi 17 juin 2022

Disable tkinter checkbuttons when a button is pressed

I am working with Tkinter and I am trying to use some checkbuttons.

Last time I wrote about them, our colleagues helped me in this question.

Here's what I am doing:

  1. get a list with some ingredients
  2. get a tkinter GUI with some checkbuttons (one for each ingredient)
  3. select some of the checkbuttons (tick them)
  4. press a button and obtain a list containing the ingredients I selected

What I am trying to do now is the following:

  1. make the checkbuttons unusable (so, disable them) after the "confirmation" button is pressed.

My code is basically the same as the accepted answer of my other question. I report it below:

import tkinter as tk

root = tk.Tk() 
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce'] 
txt = tk.Text(root, width=40, height=20) 
variables = [] 
for i in INGREDIENTS: 
    variables.append( tk.IntVar( value = 0 ) ) 
    cb = tk.Checkbutton( txt, text = i, variable = variables[-1] ) 
    txt.window_create( "end", window=cb ) 
    txt.insert( "end", "\n" ) 
txt.pack() 
 
def read_ticks(): 
    # result = [( ing, cb.get() ) for ing, cb in zip( INGREDIENTS, variables ) ] 
    result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ] 
    print( result ) 
  
but = tk.Button( root, text = 'Read', command = read_ticks) 
but.pack()  
  
root.mainloop()

Thank you in advance.




How to create dynamic Checkboxlist in Yii?

I would like a help to solve this problem. I'm using Yii 1.1 and trying to create a dynamic CheckBox list in which its elements change depending on the value selected in a DropDown element.

I created this DropDown element with the arguments in Ajax to perform the function update in the Controller. The function in the Controller is doing the lookup in the table according to the value passed.

Up to this point, the code is working fine, generating an array with the values that should be displayed. The problem is that I'm not able to configure the return of these data and I can't even display them in the View.

Below is the code data:

View - DropDown element:

echo CHtml::activeDropDownList($model, 'standard',
                array(CHtml::listData(standard::model()->findAll(), 'name','name')),
                array('empty'=>'',
                    'ajax'=>array(
                    'type'=>'POST',
                    'url'=>CController::createUrl('/getTeam',array('form'=>'Team','field'=>'standard')),
                    'update'=>'#Audit_team'),
                )
            );?>

Controller:

public function actionGetTeam($form,$field) {
    $post = $_POST;
    $standard = $post[$form][$field];
    $Lists = TblAuditStandard::model()->findAll("standard = $standard");
    foreach ($Lists as $List){
       $AuditTeam[] = $List->name." - ".$List->login;     
       asort($AuditTeam);
       foreach ($AuditTeam as $id=>$value )
           echo CHtml::tag('option',array('value'=>$id),$value,true);
    }
}

View - Checkbox element:

<div class="row">
    <?php echo $form->labelEx($model,'team'); ?>
    <?php echo CHtml::activeCheckBoxList($model,'team',array()); ?>
    <?php echo $form->error($model,'team'); ?>
</div>

I hope someone can help me solve this problem. Thanks.




jeudi 16 juin 2022

how to get the xPath of checkbox with ::after

element image

Can someone help me to get the state of checkbox if checked? I need to get the XPath of that.




Form Input Checkbox Resets API Response Value When Unchecked?

So I have this app that you select a checkbox & tip and it will show the total amount and add/subtract when you unselect/select other options.

Here is a codepen of the basic app not including the API function https://codepen.io/jaysomo10/pen/mdXoRWz

So you can see from the codepen, the basic checkboxes and tips work completely fine.

I am connected to an API and after I add my delivery address, it will calculate the delivery fee and add it to my total value.

My problem is that once I calculate the delivery fee, then I select a checkbox option, and then I unselect that option, it will reset the total value and now my total value doesn't show the delivery fee included.

Example: I select $10 menu option and then $5 tip so my total is now $15. Then, I go and calculate my delivery fee and it will show $7 delivery fee + the $15 food total which equals $22 for everything. The problem is if I unselect the $10 food item, it will reset the order total from $22 back to the tip value of $5 but my delivery fee is still showing in the HTML as $7 yet the order value total isn't including the delivery fee in the total.

Here is my JS function for the delivery fee. Note this code works completely fine as long as I only select checkboxes and never unselect any. The moment I unselect a checkbox is when the values reset and the order total becomes wrong because it no longer includes the delivery fee.

async function getFee() {
  const payload = getFormValues();
  const finalPayload = JSON.stringify(payload);

  const formInput = document.querySelector("form");
  console.log(formInput);

  if (formInput.checkValidity()) {
    console.log("YES");

    const response = await fetch("/get-fee", {
      method: "POST",
      body: finalPayload,
      headers: { "Content-Type": "application/json" },
    })
      .then(async (response) => {
        const resp = await response.json();
        return resp;
      })
      .catch((rejected) => {
        console.log(rejected);
      });

    const deliveryField = document.getElementById("fee");
    const orderTotal = document.getElementById("total");
    tipVal = document.querySelector(".tips:checked").value;
    window.tips = tipVal;

    foodTotal.textContent = `$${(window.menuItems / 100).toFixed(2)}`;
    tipTotal.textContent = `$${(window.tips / 100).toFixed(2)}`;
    deliveryField.innerHTML = `$${(response.fee / 100).toFixed(2)}`;
    orderTotal.textContent = `$${(
      (Number(window.menuItems) + Number(window.tips) + response.fee) /
      100
    ).toFixed(2)}`;
  } else {
    console.log("You need to fill out the form");
  }

}

My issue is I don't know how to get the response.fee value into my other JS file that allows me to add/subtract the checkbox values and tips.

Basically, the JS file in my codepen doesn't know the delivery fee until after I submit an address, hence the logic for the code simply adds/subtracts the values and it can't include the delivery fee in the total because it doesn't know what it is until I submit that info




mercredi 15 juin 2022

Add checkbox in dataframe

I would like to add a column in a dataframe in the streamlit and this column be a checkbox, so that later I could list the lines that the checkboxes were marked, is this possible?




Keeping checkbox flagged when navigating to another page. (Angular)

In the "Pricing" component I check "Accept payment in all currencies", however when I return to "General" to edit something and go back to "Pricing" the checkbox is unchecked, how can I make it not happen and keep it checked ? Below images and code (Sorry I don't have yet reputations for attach images, follow links.) 1: https://i.stack.imgur.com/H6bZ0.png [2]: https://i.stack.imgur.com/nNHM2.png [3]: https://i.stack.imgur.com/n3oz6.png

 <div class="inline-vertical-align input-convert-values minimun-height">
                <div class="inputs-value-container">
                    <div class="big-value-container">
                        <mat-checkbox [disabled]="mode === 'view'" [checked]="active?.bothMandatory" (change)="onCheckBoxChange($event, '')" 
                        color="primary">managePackages.bothMandatory</mat-checkbox>
                    </div>
                </div>
                <div class="inputs-value-container" *ngIf="active?.bothMandatory">
                    <p [ngClass]="{'disabled': mode === 'view'}" class="underline-button" (click)="distributeEqualy()" >managePackages.distributeEqualy</p>
                </div>
            </div>
        
            <div class="inline-vertical-align input-convert-values minimun-height">
                <div class="inputs-value-container">
                    <div class="big-value-container">
                        <mat-checkbox [disabled]="active?.bothMandatory || mode === 'view'" [checked]="active?.acceptBnb || active?.bothMandatory"
                        color="primary" (change)="onCheckBoxChange($event, 'BNB')">BEP20 - Binance</mat-checkbox>
                    </div>
                </div>
                <div class="inputs-value-container" *ngIf="active?.bothMandatory">
                    <div class="big-value-container">
                        <input [disabled]="mode === 'view'" (keydown.ArrowDown)="blockNegativeNumber($event, $event.target.value)" type="text" 
                        class="input big-value" (input)="verifyCompleteData()" [(ngModel)]="bnbPrice" placeholder="00,0%"
                        appMaskPercentual>
                    </div>
                </div>
            </div>
        
            <div class="inline-vertical-align input-convert-values minimun-height">
                <div class="inputs-value-container">
                    <div class="big-value-container">
                        <mat-checkbox [disabled]="active?.bothMandatory || mode === 'view'"  [checked]="active?.acceptCoin || active?.bothMandatory"
                        color="primary" (change)="onCheckBoxChange($event, 'Coin')" >TOKEN</mat-checkbox>
                    </div>
                </div>
                <div class="inputs-value-container" *ngIf="active?.bothMandatory">
                    <div class="big-value-container">
                        <input [disabled]="mode === 'view'" (keydown.ArrowDown)="blockNegativeNumber($event, $event.target.value)" type="text" 
                        class="input big-value" (input)="verifyCompleteData()" [(ngModel)]="coinPrice" placeholder="00,0%"
                        appMaskPercentual>
                    </div>
                </div>
            </div>



How to customize position of checkboxes, drop down list, etc. in Python tkinter?

I want to achieve the exact appearance of this image

I want to learn how to position the tickboxes, checkbox, dropdown menu, and menu list that exactly looks like the image that I have inserted. I do not know the syntax on how to write the positioning of each

from tkinter import *

import ttk

windows = Tk()
gender = ["male", "female"]
sport = ["Cricket", "Tennis"]
numbers = ['one', 'two', 'three', 'four']

windows.title("Hello Python")
windows.geometry("350x300")

x = IntVar(windows)
for index in range(len(gender)):
    radiobutton = Radiobutton(windows,
                              text=gender[index],
                              variable=x,
                              value=index,)
    radiobutton.pack(side=LEFT,ipadx=10,ipady=10)


for index in range(len(sport)):
    checkboxgui = Checkbutton(windows,
                               text=sport[index], onvalue=1,
                               offvalue=0)

    checkboxgui.pack(side=LEFT, anchor=CENTER, ipadx=10, ipady=10)

clicked = StringVar(windows)
clicked.set("one")
drop = ttk.Combobox(windows, textvariable=clicked,values=numbers)
drop.pack()

listbox = Listbox(windows,selectmode=MULTIPLE)
listbox.pack()
listbox.insert(1,"one")
listbox.insert(2,"two")
listbox.insert(3,"three")
listbox.insert(4,"four")
listbox.config(height=listbox.size())



windows.mainloop()



mardi 14 juin 2022

Sending unchecked multiple checkboxes

I'm adding multiple checkboxes to a form in Wordpress that lets you check and uncheck certain features that a user should have, saved as a meta field value on the particular user in question that you're editing when submitting the form. I have set up a "user edit page" for this, so that you can make these edits directly on the front end.

The problem, that I understand is quite common but that I still couldn't find answers for in my specific case, is that unchecked boxes doesn't get sent by the form.

Let's say for example that the there would be multiple checkboxes with the same name like this:

<label><input type="checkbox" name="meta[entity_access][]" value="entity1" />Entity 1</label>
<label><input type="checkbox" name="meta[entity_access][]" value="entity2" />Entity 2</label>
<label><input type="checkbox" name="meta[entity_access][]" value="entity2" />Entity 3</label>

If I were to check any of these boxes and submit the form, that checkbox would then already be checked when I edit the user another time. But if I then uncheck the same checkbox and send the form, returning to the user edit page it would still be checked, since the form isn't sending unchecked boxes.

I have seen solutions where you would have a hidden field for each of the checkboxes, with 0 as the value:

<input type="hidden" name="meta[entity_access][]" value="0" />
<label><input type="checkbox" name="meta[entity_access][]" value="entity1" />Entity 1</label>

But wouldn't that leave a lot of zeroes in the array of the meta[entity_access][]?

In the end, I would like the meta[entity_access][] array to contain the checkbox values that have been checked. And if a value gets unchecked, it should remove that value from the array. So using the example above, if all checkboxes apart from entity1 were unchecked, it would return an array only containing entity1. If I then uncheck entity1 and submit again, the field should return an empty array.




lundi 13 juin 2022

Is there a function that ressembles find_in_set for sparql or ARC2?

This is my first post,so I'm not sure how to ask the question ,but I have been working on a e-learning website using a classic search engin and a semantic one,I created my ontology,and used ARC2 and fuseki server, and the sparql query works when it comes to searching the keywords like I needed it to . In adition to the search engin, I'm also using a checkbox where the user can select the types of articles they wish to get for their search ,audio,video,pdf ,an image or a word file. While in classic search I used find_in_set and an array,which works perfectly,yet I don't seem to find a way when it comes to the semantic search ,this is my sparql query :

PREFIX  xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX  owl:  <http://www.w3.org/2002/07/owl#>
PREFIX  article: <http://127.0.0.1/Index.php/learning#>
SELECT  *
WHERE
  { ?Publication  article:HasLevel  ?niveau ;
              article:HasLanguage   ?Langue ;
              article:HasType       ?Type ; 
              article:HasDispo      article:Pub ;
              article:Timepub       ?Temps ;
              article:AnneePub      ?Annee ;
              article:AuteurPub     ?Auteur ;
              article:DescriptionPub ?Description ;
              article:FichierPub    ?Fichier ;
              article:IDPub         ?ID ;
              article:TaillePub     ?Taille ;
              article:TitrePub      ?Titre ;
              article:Unipulication  ?Universite ;
              article:PubliéPar     ?Professeur .
              ?Professeur article:NomUti ?NomProf.
              ?Professeur article:PrenomUti ?PrenomProf
  FILTER( REGEX(STR(?Titre), "'.$r.'","i") || REGEX(STR(?Description), "'.$r.'","i"))}
  ORDER BY DESC(?Temps)
  ';```
the $r is for the keyword 
Do I need to use an other way,or is there a function close to find_in_set for sparql or ARC2?



dimanche 12 juin 2022

Get selected checkbox values from parent and child in angular

I am trying to generate a new array from this data and show only selected checkbox values from parent as well child.

this.data.ParentChildchecklist = [ { id: 1,value: 'Elenor Anderson',isSelected: false,isClosed:false, childList: [ { id: 1,parent_id: 1,value: 'child 1',isSelected: false }, { id: 2,parent_id: 1,value: 'child 2',isSelected: false } ] }, { id: 2,value: 'Caden Kunze',isSelected: false,isClosed:false,childList: [ { id: 1,parent_id: 1,value: 'child 1',isSelected: false }, { id: 2,parent_id: 1,value: 'child 2',isSelected: false } ] }, { id: 3,value: 'Ms. Hortense Zulauf',isSelected: false,isClosed:false, childList: [ { id: 1,parent_id: 1,value: 'child 1',isSelected: false }, { id: 2,parent_id: 1,value: 'child 2',isSelected: false } ] } ];

Tried this code to filter the selected list from parent and child to push to new List but its not working.

https://stackblitz.com/edit/angular-ivy-hfvrqa?file=src/app/app.component.ts




Set Checkbox to Checked with JavaScript window.onload and make persistent page refresh or click event

reference: Set Checkbox to Checked with JavaScript after page Load

I have following code

    window.onload = function() {
    document.getElementById("gui-form-newsletter").checked = true;
    }

What I notice that after onload when a some other radio button events are clicked the checked state on checkbox disappears. How can I prevent this?




How to make checkbox checked according to a value in Jquery

I need to make checked status of my checkbox according to a data value. Up to now I am using below method.

$(document).ready(function(){  
      $('#add').click(function(){  
           $('#insert').val("Insert");  
           $('#update_form')[0].reset();  
      });  
      $(document).on('click', '.update_data', function(){ 
           var row_id = $(this).attr("id");  
           
           $.ajax({  
                url:"./project/userdetail.php",  
                method:"POST",  
                data:{row_id:row_id},  
                dataType:"json", 
                success:function(data){  
                      ...........
                     if(data.accesslocations=='ABC,DEF,GHI'){
                      document.getElementById("check1").checked = true;
                      document.getElementById("check2").checked = true;
                      document.getElementById("check3").checked = true;
                      
                     }

                     if(data.accesslocations=='ABC,GHI'){
                      document.getElementById("check1").checked = true;
                      document.getElementById("check3").checked = true;
                      
                     }
                     if(data.accesslocations=='ABC'){
                      document.getElementById("check1").checked = true;
                     }

                    
                     
                     
                     ...........

                 $('#employee_id_update').val(data.row_id);  
                 $('#insert').val("Update");
                 $('#new_data_Modal').modal('show'); 
                        
                      
                }, 
                error: function(req, status, error) {
               alert(req.responseText);      
                }   
           });  
      });  

My intention is to check the data.accesslocations and check whether it contains ABC or ABC,DEF likewise,

If ABC contains need to check1 status as checked.
If DEF contains need to check2 status as checked.
If GHI contains need to check3 status as checked.

I have tried below method as well. But then I could not open my dialogbox, new_data_Modal.

               if(strstr(data.accesslocations, "ABC")){
                  document.getElementById("check1").checked = true;
                 }



samedi 11 juin 2022

Multiple Checkbox in Ruby

I'm trying to create an "ingredient" checkbox list derived from my "recipes", I'd like for the values to be saved in the database so that when it's checked and I refresh the page, it still shows as checked.

The error says "uninitialized constant #Class:0x00007f8f2d360830::Parties"

Here's an example of what i am trying to do

Controller:

# parties_controller.rb

def ingredients
  @party = Party.find(params[:party_id])
  @party_recipe = @party.recipes
  @party_recipe.each do |recipe|
  @ingredients = recipe.ingredients
end

The models:

Party model

#party.rb

class Party < ApplicationRecord
  has_many :party_recipes
  has_many :recipes, through: :party_recipes
end

Recipe model

#recipe_ingredient.rb

class RecipeIngredient < ApplicationRecord
 belongs_to :recipe
 belongs_to :ingredient
end

Ingredient model

#ingredient.rb

class Ingredient < ApplicationRecord
 has_many :recipe_ingredients
 has_many :recipes, through: :recipe_ingredients
end

Form:

#ingredients.html.erb

<% form_for "/parties/#{@party.id}/ingredients" do |f| %>
  <% Parties::Recipes::Ingredients.each do |ingredient| %>
    <%= check_box_tag(ingredient) %>
    <%= ingredient %>
  <% end %>
<% end %>

Schema:

create_table "ingredients", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "parties", force: :cascade do |t|
    t.string "title"
    t.string "address"
    t.bigint "user_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "theme"
    t.date "date"
    t.integer "attendancy"
    t.integer "appetizers"
    t.integer "mains"
    t.integer "desserts"
    t.string "status", default: "pending"
    t.index ["user_id"], name: "index_parties_on_user_id"
  end

  create_table "party_recipes", force: :cascade do |t|
    t.bigint "recipe_id", null: false
    t.bigint "party_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["party_id"], name: "index_party_recipes_on_party_id"
    t.index ["recipe_id"], name: "index_party_recipes_on_recipe_id"
  end

  create_table "recipe_ingredients", force: :cascade do |t|
    t.bigint "recipe_id", null: false
    t.bigint "ingredient_id", null: false
    t.string "amount"
    t.boolean "included", default: false
    t.index ["ingredient_id"], name: "index_recipe_ingredients_on_ingredient_id"
    t.index ["recipe_id"], name: "index_recipe_ingredients_on_recipe_id"
  end

  create_table "recipes", force: :cascade do |t|
    t.string "title"
    t.text "description"
  end

add_foreign_key "party_recipes", "parties"
add_foreign_key "party_recipes", "recipes"
add_foreign_key "recipe_ingredients", "ingredients"
add_foreign_key "recipe_ingredients", "recipes"

I'm not entirely sure where exactly needs to be corrected, any help appreciated, thank you so much!




Can't get checkboxes to work google sheets script

I have little to no experience with google scripts, and I find myself in a pickle. I want to execute a script when a checkbox is checked. I got this working. The problem is i can't make the script take into account other checkboxes - say i have 3 options for the script -> log ALL, log only fruits and add the store. It runs when i click RUN, but it won't take into account my "log fruit" checkbox. At the end it will set the checkbox that runs the script back to FALSE.

function onEdit(e) {
  const sh = e.range.getSheet();
  if (e.range.columnStart == 6 && e.range.columnEnd == 6 && e.range.rowStart == 7 && e.range.rowEnd == 7 && e.value == "TRUE") {
    if (e.range.columnStart == 6 && e.range.columnEnd == 6 && e.range.rowStart == 4 && e.range.rowEnd == 4 && e.value == "TRUE") {
      sh.getRange(e.range.rowStart, 6).setValue(10);
    }
    sh.getRange(e.range.rowStart, 8).setValue(20);
    sh.getRange(e.range.rowStart, 6).setValue("FALSE");
  }
}

Any ideas ?

https://docs.google.com/spreadsheets/d/1BtDoO3QIGaiZxUYTld5Si8die1W-O_1FiqczqgN8diI/edit#gid=1776658601




jeudi 9 juin 2022

Bootstrap Center Checkboxes

How can I get the check input to be vertically and horizontally centered within the parent column?

Image below shows the parent column and checkbox, I've tried text-centered, d-flex justify-content-center, align-self-center and none have worked. I think it has to do with the nested columns?

Checkbox not centered within parent column

<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

<div class="container-lg">
  <div class="row">
    <div class="col-2">
      <div class="row align-items-center h-100">
        <div class="col-4 d-flex border justify-content-center align-items-center h-100">
          <div class="form-check align-items-center d-flex justify-content-center align-items-center">  
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked> <!-- CENTER THIS ITEM -->
          </div>
        </div>
        <div class="col-4 d-flex justify-content-center h-100 border">
          <div class="form-check d-flex justify-content-center align-items-center">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked> <!-- CENTER THIS ITEM -->
          </div>
        </div>
        <div class="col-4 h-100 border d-flex align-items-center justify-content-center">
          <div class="form-check d-flex justify-content-center align-items-center">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked> <!-- CENTER THIS ITEM -->
          </div>
        </div>
      </div>
    </div>
    <div class="col-10">
      <div class="row align-items-center h-100">
        <div class="col-2 h-100 border d-flex align-items-center justify-content-center">
          <span>Name</span>
        </div>
        <div class="col-8 h-100 border d-flex align-items-center">
          <span>Desc</span>
        </div>
        <div class="col-1 h-100 border d-flex align-items-center">
          <span>Total</span>
        </div>
        <div class="col-1 wg-right-bottom-border h-100">
          <div class="form-check d-flex justify-content-center">
            <input class="form-check-input align-self-center" type="checkbox" value="" id="flexCheckDefault">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Bonus points for it being vertically and horizontally centered while printing as well.




Tkinter CheckBox command line failing - missing 1 required positional argument: 'self'

I have some code which I intend to run calculations every time a user makes a change to a tkinter widget. If you click in an edit box, or alter the dropdown box the functions run fine. The problem I am having is that I can't get the command line of the CheckBox to accept the functions. It throws a "missing 1 required positional argument: 'self'" while the code works on all other widgets. Can anyone let me know what I'm doing wrong please? Code below:

      #Import everything from tkinter, messageboxes, ttk and math
      from tkinter import *
      from tkinter import ttk

      Form1=Tk()

      # Calculate Variables - Main function. Run every time a change is made to the form
      def CalcVariables(Msg):
      Msg = "Run Calculations"    
      print(Msg)

      #Run Multiple Funtions - Tied to command lines of box functionality
      def MultipleFunctions(*funcs):
          def FuncLoop(*args, **kwargs):
              for f in funcs:
                  f(*args, **kwargs)
          return FuncLoop    

      #Check Length Box entry is Valid
      def LthCheck(Msg):

          #Check entry is numeric - give warning if not and exit
          try:
              float(Lth.get())
          except:
              Msg = "Length box only numbers."
              print(Msg)
              Lth.focus()
              return   

      #Check Width Box Entry is Valid
      def WthCheck(Msg):
          #Check entry is numeric - give warning if not and exit
          try:
              int(Wth.get())
          except ValueError:
              Msg = "Width box only accepts numbers."
              print(Msg)
              Wth.focus()
              return

      #Length EditBox
      Lth = Entry(Form1,width=10)
      Lth.grid(row=0, column=1, sticky=W)
      Lth.insert(0,10)
      Lth.bind("<FocusOut>",MultipleFunctions(LthCheck, CalcVariables))
      Label (Form1, text="Length") .grid(row=0, column=0, sticky=W)

      #Width EditBox
      Wth = Entry(Form1,width=10)
      Wth.grid(row=1, column=1, sticky=W)
      Wth.insert(0,1)
      Wth.bind("<FocusOut>",MultipleFunctions(WthCheck, CalcVariables))
      Label (Form1, text="Width") .grid(row=1, column=0, sticky=W)

      #Type DropDownBox
      Type = [
          "Type 1", 
          "Type 2",
          ]
      PartStyle = StringVar()
      PartStyle.set(Type[0])
      PartStyleDrop = OptionMenu(Form1, PartStyle, *Type, command=MultipleFunctions(LthCheck, WthCheck, CalcVariables))
      PartStyleDrop.grid(row=3, column=1,sticky=W)
      Label (Form1, text="Part") .grid(row=3, column=0, sticky=W)

      #Check Button
      MT = IntVar()
      ModType = Checkbutton(Form1, text = "Modify", variable = MT, onvalue = 1, offvalue =0, command= MultipleFunctions(LthCheck, WthCheck))
      ModType.grid(row=4,column=0)

      Lth.focus()

      Form1.mainloop()



Linking html pages

i am working on a web application. i came across a problem: if i want to hide text in for example 03.hoofdstuk 3.html pages i have a checkbox that can be checked in 01.algemeen.html

  1. What is the best code for hiding headers and paragraphs (with all an unique id)?
  2. How do i stop the html from reloading when you go back to the page? (for example: when i check the checkbox in 01.algemeen.html, i take a look in 03.hoofdstuk 3.html if the headers and paragraphs are hidden and go back, the checkbox in 01.algemeen.html is back unchecked.)

how i linked the pages: linked pages

how it looks in the browser: browser

note: the checkbox is on another page than where the text needs to be hidden. Btw: i am testing it all by opening the html in chrome (not hosting it yet, so it still needs to work without hosting.)

hope you understand the problem. Feel free to ask questions!!

looking forward hearing from you guys!




"v-model" with checkboxes but the data is "1" or "0" not "true" or "false"

Because of some reason on the backend, they use 0 or 1 and not false or true for booleans.

So, when I try to use the boolean data from API, TS complains:

// settings.crawl_on outputs 0 or 1
<input
 v-model=“settings.crawl_on”
 type="checkbox"
/>

I tried adding the below code it doesn't work either:

true-value="1"
false-value="0"

TS says:

(property) InputHTMLAttributes.checked?: any[] | Set | Booleanish Type 'number' is not assignable to type 'any[] | Set | Booleanish'.ts(2322)runtime-dom.d.ts(629, 3): The expected type comes from property 'checked' which is declared here on type 'ElementAttrs'

Is there a way to override this or what is the correct use?




mercredi 8 juin 2022

Bootstrap Nested Column Checkbox Padding

I have two nested columns in one row, one set of columns height is greater than the other. It seems that bootstrap is adding some additional padding/margin to the checkboxes that I am unable to figure out (see image below). If I remove checkboxes for text, the layout is fine.

Is there a way to make the second nested columns have the same height (Right bordered item in picture)?

Orange seems to be additional padding?

<div class="container mt-3">
  <div class="row">
    <div class="col-2">
        <div class="row">
            <div class="col-4 d-flex justify-content-center">
                <span class="">1</span>
            </div>
            <div class="col-4 d-flex justify-content-center">
                <span class="">2</span>
            </div>
            <div class="col-4 d-flex justify-content-center">
                <span class="">3</span>
            </div>
        </div>
    </div>
    <div class="col-10">
        <div class="row">
            <div class="col-2 d-flex">
                <span>Service List</span>
            </div>
            <div class="col-8 text-center">
                <span>Description</span>
            </div>
            <div class="col-1 px-1 text-start">
                <span >Amount</span>
            </div>
            <div class="col-1">
                <span></span>
            </div>
        </div>
    </div>
  </div>
  <div class="row">
    <div class="col-2">
      <div class="row align-items-center">
        <div class="col-4 d-flex justify-content-center align-items-center ">
          <div class="form-check align-items-center d-flex justify-content-center align-items-center">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked>
          </div>
        </div>
        <div class="col-4 d-flex justify-content-center">
          <div class="form-check d-flex justify-content-center align-items-center">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked>
          </div>
        </div>
        <div class="col-4 d-flex justify-content-center border">
          <div class="form-check d-flex justify-content-center align-items-center">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked>
          </div>
        </div>
      </div>
    </div>
    <div class="col-10">
      <div class="row align-items-center">
        <div class="col-2 border">
            <span>Line Item Name</span>
        </div>
        <div class="col-8">
            <span>Line Item Description</span>
        </div>
        <div class="col-1">
            <span>Total</span>
        </div>
        <div class="col-1">
            <div class="form-check d-flex justify-content-center">
                <input class="form-check-input align-self-center" type="checkbox" value="" id="flexCheckDefault" >
            </div>
        </div>
      </div>
    </div>
</div>