jeudi 30 septembre 2021

CSS, Javascript, XSL, Moving a row in a table to the bottom of the table

I have a stylesheet that I am working on where the html file generated from the stylesheet has a toggle button to change a buttom, in a row, in a table ,from a tick to a cross. All buttons come in by default as checked (ticked) ... when the buttom is clicked the tick changes to a cross. What I would like to happen but cannot do is to move the ENTIRE row to the bottom of the table when clicked. The end result is as a row is clicked the toggle changes to a cross and moves to the base of the table.

Thanks for any help

Tick/cross code

/* Customize the label (the container) */
.customcheck {
  position: relative;
}

.customcheck input {
  display: none;
}

.customcheck input~.checkmark {
  background: #ee0b0b;
  width: 25px;
  display: inline-block;
  position: relative;
  height: 25px;
  border-radius: 2px;
  vertical-align:middle;
  margin-right:10px;
}

.customcheck input~.checkmark:after,
.customcheck input~.checkmark:before {
  content: '';
  position: absolute;
  width: 2px;
  height: 16px;
  background: #fff;
  left: 12px;
  top: 4px;
}

.customcheck input~.checkmark:after {
  transform: rotate(-45deg);
  z-index: 1;
}

.customcheck input~.checkmark:before {
  transform: rotate(45deg);
  z-index: 1;
}

.customcheck input:checked~.checkmark {
  background: #3d8a00;
  width: 25px;
  display: inline-block;
  position: relative;
  height: 25px;
  border-radius: 2px;
}

.customcheck input:checked~.checkmark:after {
  display: none;
}

.customcheck input:checked~.checkmark:before {
  background: none;
  border: 2px solid #fff;
  width: 6px;
  top: 2px;
  left: 9px;
  border-top: 0;
  border-left: 0;
  height: 13px;
  top: 2px;
}

....Stylesheet entry....

<tr class="clickable">
          
<td>
<label class="customcheck">
  <input type="checkbox" checked="checked"/>
  <span class="checkmark"></span>
</label>
</td>



Angular checkbox checked by default in template driven form

I have a template driven Angular form, containing a checkbox, which I want to be checked by default. Here is the minimized code:

app.component.html:

<form #form="ngForm" (ngSubmit)="submit(form.value)">
  <input #cb1 type="checkbox" name="cb1" ngModel checked />
  <input #cb2 type="checkbox" name="cb2" ngModel checked="true" />
  <input #cb3 type="checkbox" name="cb3" [(ngModel)]="value" />
  <button type="submit">Submit</button>
</form>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent {
  value=true;
  submit(x: any) {
    console.log(x);
  }
}

StackBlitz

In my project, I add the checkbox to the Angular form using the syntax in the first two checkboxes, by adding the ngModel directive, without using two-way binding. I tried two different ways to make the checkbox checked by default, but neither worked. I only managed to make it work by using two way binding on ngModel, as shown in the third checkbox. Is there a way to make it work without two way binding?




How does a Tkinter checkbox control corresponding textbox widget? Python

I have a simple tkinter program, where upon clicking a "Create boxes" button, it creates a Checkbutton and a Text widget. I was trying to enable/disable the Text widget based on the Checkbutton. eg- if the Checkbutton is ticked the corresponding Text button will be disabled.

And the following code does work as desired, but I have no idea how? How does a Checkbutton keep track of the corresponding Text widget?

I have tried it with multiple Checkbuttons and they all don't seem to interfere with the other's Text widgets.

from tkinter import *

root = Tk()
root.geometry('500x300')

def create_boxes():

    def disable_text():
        if textbox['state'] == NORMAL:
            textbox['state'] = DISABLED
        else:
            textbox['state'] = NORMAL


    checkbox = Checkbutton(root, command = disable_text)
    textbox = Text(root, height= 1, width = 30)

    checkbox.pack()
    textbox.pack()

create_chechkbutton = Button(root, text= 'Create a checkbox and textbox', command= create_boxes)
create_chechkbutton.pack()

root.mainloop()

Any explanation is appreciated.




como criar função, selecionando um checkbox para des/habilitar botão para acesso à link e mudar a cor de vermelho para verde? [closed]

como criar função, selecionando um checkbox para des/habilitar botão para acesso à link e mudar a cor de vermelho para verde?

Selecionando um item no checkbox, torna-se verde e desabilita o botão para o publico ter acesso á pagina.

Estou tendo dificuldade para criar.




Python Selenium Selecting Nested Checkboxes

I have been fighting with some checkboxes for a couple of days, and finally at the point that I need some assistance. I am using Selenium Webdriver on Chrome, can get through the entire site login, selecting multiple other elements, and selecting from a dropdown box on the same window that these checkboxes are on.

Here is the block of code from the website I am working with, a list of checkboxes: Screenshot of Code - cant embed yet

<div class="panel-body">
   <!-- ngRepeat: category in ctrl.categories | orderBy:['Title'] -->
   <div class="checkbox ng-scope" ng-repeat="category in ctrl.categories | orderBy:['Title']" style="">
      <label style="padding-left: 14px;" class="ng-binding"> 
         <div class="icheckbox_minimal" style="position: relative;">
            <input type="checkbox" icheck="" ng-model="ctrl.selectedCategories[category.Code]" class="ng-pristine ng-untouched ng-valid ng-empty" style="position: absolute; opacity: 0;">
            <ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
         </div>
         " Hardscapes " 
      </label>
   </div>
   <!-- end ngRepeat: category in ctrl.categories | orderBy:['Title'] -->
<div class="checkbox ng-scope" ng-repeat="category in ctrl.categories | orderBy:['Title']">
       <label style="padding-left: 14px;" class="ng-binding"> 
          <div class="icheckbox_minimal" style="position: relative;">
               <input type="checkbox" icheck="" ng-model="ctrl.selectedCategories[category.Code]" class="ng-pristine ng-untouched ng-valid ng-empty" style="position: absolute; opacity: 0;">
               <ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
         </div>
         " Irrigation " 
        </label>
      </div>
      <!-- end ngRepeat: category in ctrl.categories | orderBy:['Title'] -->
<div class="checkbox ng-scope" ng-repeat="category in ctrl.categories | orderBy:['Title']"> 
   <label style="padding-left: 14px;" class="ng-binding">
      <div class="icheckbox_minimal" style="position: relative;">
          <input type="checkbox" icheck="" ng-model="ctrl.selectedCategories[category.Code]" class="ng-pristine ng-untouched ng-valid ng-empty" style="position: absolute; opacity: 0;">
         <ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
     </div> 
     " Landscape Supplies "
  </label> 
</div>
<!-- end ngRepeat: category in ctrl.categories | orderBy:['Title'] --><div 

Here is a whole bunch of the different attempts I have tried to get selenium to click a checkbox:

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.CSS_SELECTOR,'.icheckbox_minimal:nth-child[3] input'))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.CSS_SELECTOR,'icheckbox_minimal:nth-child[3] input'))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.CSS_SELECTOR,'.icheckbox_minimal:nth-of-type(3) input'))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.CSS_SELECTOR,'icheckbox_minimal:nth-of-type(3) input'))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.XPATH,"//*[@class='panel-body']/div/div[1]/label/input"))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.XPATH,"//*[@class='icheckbox_minimal']/div/div[1]/label/input"))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.XPATH,"//*[@class='icheckbox_minimal']/div/label/div[3]/input"))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.XPATH,"//*[@class='panel-body']/div/label/div[3]/input"))).click()

driver.find_element_by_link_text("Hardscapes").click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.XPATH,'/html/body/div[10]/div/div/div/div[2]/div/div[2]/div/div/div[2]/div[3]'))).click()

WebDriverWait(driver,120).until(EC.visibility_of_element_located((By.CSS_SELECTOR , "panel-body:nth-child(3) input"))).click()

WebDriverWait(driver , 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR , "//div[@class='panel-body']/div/div[3]/label/input"))).click()

driver.find_element_by_css_selector('panel-body:nth-of-type(3) input').click()

WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CLASS_NAME,"ng-binding"))).click()

WebDriverWait(driver,30).until(EC.visibility_of_element_located((By.XPATH,"//span[contain(text(),'Hardscapes')]"))).click()

Hopefully someone out there can point me in the right direction on what I am missing to get these nested checkboxes checked.

Thanks for any help!




Kivymd: How to add checkbox in List item without creating custom class?

How can I add checkbox with MDList item? In my project I need an event as like, 'Store selected items texts in a python list after clicking a button.' It can be done easily when I create a custom class for List with checkbox (As shown in kivymd documentation).

from kivy.lang import Builder

from kivy.properties import StringProperty
from kivymd.app import MDApp
from kivymd.uix.list import IRightBodyTouch, TwoLineAvatarIconListItem
from kivymd.uix.selectioncontrol import MDCheckbox

KV = """
<ListItemWithCheckbox>:
    IconLeftWidget:
        icon: root.icon
    RightCheckbox:
        id: cb

BoxLayout:

    ScrollView:

        MDList:
            id: scroll
            
    MDRaisedButton:
        text: "Save"
        on_release: app.save_checked()
"""

class ListItemWithCheckbox(TwoLineAvatarIconListItem):
    """Custom list item."""
    icon = StringProperty("android")

class RightCheckbox(IRightBodyTouch, MDCheckbox):
    """Custom right container."""

class MainApp(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        for i in range(15):
            self.root.ids.scroll.add_widget(
                ListItemWithCheckbox(text=f"Item {i}", secondary_text=f"Item {i+10}", icon='User_images/s.jpg')
            )
    def save_checked(self):
        mdlist = self.root.ids.scroll  # get reference to the MDList
        selected_item = []
        for wid in mdlist.children:
            if isinstance(wid, ListItemWithCheckbox):  # only interested in the ListItemWithCheckboxes
                cb = wid.ids.cb  # use the id defined in kv
                if cb.active:  # only append selected items

                    selected_item.append(wid.text)
        selected_item = selected_item[::-1]
        print(selected_item)


MainApp().run()

When I try to apply this thing with screen manager(for handling multiple screen) it is not working. Can I create a list with checkbox without creating custom class for list?

NB: My requirement is, I need a list with checkbox. After selecting list item when press a button the selected item should print (or used in other purpose)




mercredi 29 septembre 2021

Filter products with checkbox and data-category

I intent to create a filter by showing and hiding divs with checkbox.

I have seen posts like this, but I have yet to achieve the result I´m expecting. This is a part of the code:

<div class="container">
            <h3 style="font-size:14px; font-weight:normal;">Products by Room</h3>
            <p style="font-size:12px;"><strong>Filter items by room:</strong></p>
            <form>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="office" id="red" /> Office</label><br>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="bedroom" id="yellow" /> Bedroom</label><br>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="living-room" id="pink" /> Living Room</label><br>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="dining-room" id="purple" /> Dining Room</label><br>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="library" id="green" /> Library</label><br>
                <label style="font-size:12px;"><input type="checkbox" name="room" value="hallway" id="other" /> Hallway</label>
            </form>

            <div class="products-by-room">
                <div data-category="office library">Office, Library</div>
                <div data-category="office">Office</div>
                <div data-category="hallway library">Hallway, Library</div>
                <div data-category="living-room dining-room">Living-room & Dining-room</div>
                <div data-category="living-room">Living-room</div>
                <div data-category="bedroom dining-room">Bedroom & Dining-room</div>
                <div data-category="dining room">Dining room</div>
                <div data-category="office">Office</div>
                <div data-category="bedroom">Bedroom</div>
                <div data-category="living-room">Living-room</div>
                <div data-category="living-room dining-room office library">Living-room, Dining-room, Office & Library</div>
                <div data-category="library">Library</div>
                <div data-category="office">Office</div>
                <div data-category="bedroom">Bedroom</div>
            </div>
        </div>

As you can see, in some divs there is only one data-category:

<div data-category="office">Office</div>

but I also have divs with multiple data-categories:

<div data-category="office library">Office & Library</div>

The result I am looking for is when I check the checkbox for "Office" I want it to show all the divs that contains office in the data-category attribute, wether it´s only office or office and other types of rooms.

So, if I selected the checkbox office, I would want to show only the following divs:

<div data-category="office library">Office, Library</div>
<div data-category="office">Office</div>                
<div data-category="living-room dining-room office library">Living-room, Dining-room, Office & Library</div>                
<div data-category="office">Office</div>            

Any tips on how can I achieve this?




Powershell and XAML checkboxes problem while executing

I made a XAML form from visual studio 2012, the XAML form have checkboxes that you select to get the information.

Every checkbox have a powershell function behind.

When executing the form, if I select one checkbox and unselect it, when I press the button to execute the function, even if the checkbox is unchecked at the moment I press the execution button its continuing thinking that the checkbox is selected. But I unchecked the checkbox before clicking the execution button. So it's continuing executing other functions that I don't want it to execute.

Do we have a kind of code that force PowerShell to think the checkbox is $false while the form is in execution ?

Here an example of code:

 $apps_checkbox = $Window.FindName("apps_checkbox")
    $apps_checkbox.Add_Click({ 
    if($apps_checkbox.isChecked -eq $true){
       $retrievebutton.add_click({
       IF(!(GCI ".\$FOLDERNAME\$COMP" | WHERE-OBJECT NAME -EQ "APPS")){ 
        NEW-ITEM -ITEMTYPE DIRECTORY -NAME APPS -PATH ".\$FOLDERNAME\$COMP" 
       }
       NEW-ITEM -ITEMTYPE FILE -PATH 
       ".\$FOLDERNAME\$COMP\APPS\APPS-$COMP.TXT" 
       LIST-APPS 
        }) 
       } 
      })



mardi 28 septembre 2021

Dynamically call function corresponding to html checkboxes

In my code I created chef class which can have three function I have another ItalianChef which inherits chef class and additionally have two function. What I want to do is in a user form user will first choose a chef and choose dish after that I will show which image of the dish user have choosen. If selected chef doesn't have any dish he can cook I will show cannot cook. The problem is how can I call the function in 'chef' and 'ItalianChef' class according to the checkbox choosen from user. here is the code

        <?php 
        class chef{
            function makeFrenchFry()
            {
                echo "made french fry <br>";
                ?>
                <img src="media/frenchfry.gif" alt="">
                <?php
            }
            function makeCrabFry()
            {
                echo "made crab  fry <br>";
                ?>
                <img src="media/crabfry.gif" alt="">
                <?php
            }
            function makeRamen()
            {
                echo "made ramen  <br>";
                ?>
                <img src="media/ramen.gif" alt="">
                <?php
            }
        }
        class ItalianChef extends chef{
            
            function makeLasagna()
            {
                echo "made lasagna   <br>";
                ?>
                <img src="media/lasagna.gif" alt="">
                <?php
            }
            function makeRatatouille()
            {
                echo "made ratatouille".   "</br>";
                ?>
                <img src="media/ratatouille.gif" alt="">
                <?php
            }
        }

        $jhon  = new chef();
        // $jhon->makeFrenchFry();
        // $jhon->makeCrabFry();
        // $jhon->makeRamen();

        $marconi = new ItalianChef();
        // $marconi->makeLasagna();
        // $marconi->makeRatatouille();

        if(isset($_POST['submit']))  { 
            if(isset($_POST['oneChef'])) {
                if(isset($_POST['frenchfry'])
                ||isset($_POST['crabfry'])
                ||isset($_POST['ramen'])
                ||isset($_POST['lasagna'])
                ||isset($_POST['ratatouille']) 
                ) {

                $chefType = $_POST['oneChef'];
                $frenchfry = $_POST['frenchfry'];
                $crabfry = $_POST['crabfry'];
                $ramen = $_POST['ramen'];
                $lasagna = $_POST['lasagna'];
                $ratatouille = $_POST['ratatouille'];

                }else{
                    echo "select one dish";
                }

            } else{
                echo "select one chef";
            }
        }
        

    ?>

    <form action="chef.php" method="post">
    <p>Please select your Chef</p>
      <input type="radio" id="chef" name="oneChef" value="chef">
      <label for="chef">chef</label><br>

      <input type="radio" id="ItalianChef" name="oneChef" value="ItalianChef">
      <label for="ItalianChef">ItalianChef</label><br> 


    <input type="checkbox" id="frenchfry" name="frenchfry" value="frenchfry">
    <label for="frenchfry"> frenchfry</label><br>

    <input type="checkbox" id="crabfry" name="crabfry" value="crabfry">
    <label for="crabfry"> crabfry</label><br>

    <input type="checkbox" id="ramen" name="ramen" value="ramen">
    <label for="ramen"> ramen</label><br><br>

    <input type="checkbox" id="lasagna" name="lasagna" value="lasagna">
    <label for="lasagna"> lasagna</label><br><br>

    <input type="checkbox" id="ratatouille" name="ratatouille" value="ratatouille">
    <label for="ratatouille"> ratatouille</label><br><br>


    <input type="submit" value="Submit" name="submit">

    </form>



React - My checkbox box are not rendering when I click twice in the same item

I'm having an issue to set make a checkbox list to work properly.

I'm rendering my checkbox from a an array of objects, and displaying it properly. When I click on a checkbox, it renders properly, and if I then click in another one, it works fine.

The issue happens when I click in a checkbox, and then again click on the same one. Even though the state changes, it doesn't rerender. So When I click on another checkbox, everything rerenders, and the previous one that was clicked twice is also updated.

My products.js file:

const products = [
    {name: "CZ15B29XTD", img: "", checked: false},
    {name: "CZ16B17IPRO", img: "", checked: false},
    {name: "CZ26B47I2X", img: "", checked: false},
    {name: "CZ36B96I2X", img: "", checked: false},
    {name: "CZ37B39I2X", img: "", checked: false},
    {name: "CZ37B60IPRO", img: "", checked: false},
    {name: "CZ48B18IPRO", img: "", checked: false},
    {name: "CZ58B23I2X", img: "", checked: false},
    {name: "2607XTD", img: "", checked: false},
]

export default products

My Forms.jsx file (that is rendered inside the App.js, and receives data and setThanks as props - these are not relevant, as they are not used for the checkbox)

import React, { useState } from 'react'
import Select from 'react-select'
import axios from 'axios'
import products from '../products'

function Form({ data, setThanks }) {
    // Configure states
    const [state, setState] = useState('')
    const [city, setCity] = useState('')
    const [customer, setCustomer] = useState('')
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [errMessage, setErrMessage] = useState(null)
    const [productsState, setProductsState] = useState(products)
    const [selectedValue, setSelectedValue] = useState(null);

    // Configure options
    let statesArr = []
    let citiesArr = []
    let customersArr = []

    // Populate the stateArr with all the possible states
    data.forEach(item => {
        statesArr.push(item.state)
        citiesArr.push(item.city)
        customersArr.push(item.customer)
    })
    // Remove duplicates
    const states = [...new Set(statesArr)].sort()

    const filteredCities = data.filter(item => item.state === state)
    // Add all cities to the citiesArr
    citiesArr = filteredCities.map(function(obj){
        return obj.city;
    })
    // Remove duplicates and sort
    const singleCities = filteredCities.filter(function (el, i, arr) {
        return citiesArr.indexOf(el.city) === i;
    });
    const sortedCities = singleCities.sort((a, b) => a.city < b.city? -1 : 1)

    
    const filteredCustomers = data.filter(item => item.state === state && item.city === city)
    // Add all cities to the customersArr
    customersArr = filteredCustomers.map(function(obj){
        return obj.city;
    })
    // Remove duplicates and sort
    const singlesCustomer = filteredCustomers.filter(function (el, i, arr) {
        return customersArr.indexOf(el.city) === i;
    });
    const sortedCustomers = singlesCustomer.sort((a, b) => a.city < b.city? -1 : 1)


    // HANDLER functions
    // ***********************************

    const handleStateChange = (e) => {
        setState(e.value)
        setCity(null)
        setCustomer(null)
    }

    const handleCityChange = (e) => {
        setCity(e.value)
        setCustomer(null)
    }

    const handleCustomerChange = (e) => {
        setCustomer(e.value)
    }

    const handleChangeName = e => {
        setName(e.target.value)
    }

    const handleChangeEmail = e => {
        setEmail(e.target.value)
    }

    const handleCheckboxChange = (e, product) => {
        setSelectedValue(e.target.value)

        let checkboxList = productsState
        checkboxList.forEach(chkItem=>{
            if(chkItem === product){
              chkItem['checked'] = !chkItem['checked'];
            }
        })
        setProductsState(checkboxList)
        console.log(productsState)
    }

    console.log(selectedValue)

    const handleSubmit = e => {
        e.preventDefault()

        if(name && state && city && customer) {
            axios.post('removed',{
                "data": {
                    "Nome": name, 
                    "Email": email, 
                    "Estado": state, 
                    "Cidade": city, 
                    "Distribuidor": customer,
                    "Email Sent": "false",
                    "Customer Email Sent": "false"
                }
            }).then( response => {
                console.log(response.data);
                setThanks(true)
            });
        }
        else {
            setErrMessage('Por favor preencher todos os campos acima')
        }
        
    }

    // Log all the values
    console.log(state, city, customer, name, email)

    return (
        <div className="form-container">
            <h4>Nome Completo</h4>
            <input type="text" id="client-name" name="client-name" placeholder="Digite seu nome" onChange={handleChangeName} required/>
            
            <h4>Email</h4>
            <input type="text" id="client-email" name="client-email" placeholder="Digite seu email" onChange={handleChangeEmail} required/>
            
            <h4>Selecione o Estado</h4>
            <Select 
                name="form-name"
                value=
                options={states.map((state) => {
                    return {value: state, label: state}
                })} 
                onChange={handleStateChange}
                />

            {state && 
            <div className="city-select">
                <h4>Selecione a Cidade</h4>
                <Select
                    name="form-city" 
                    value=
                    options={sortedCities.map((item) => {
                        return {value: item.city, label: item.city}
                    })} 
                    onChange={handleCityChange}
                    /> 
            </div> }

            {state && city &&
            <div className="customer-select">
                <h4>Selecione o Canal</h4>
                <Select 
                    name="form-customer"
                    value=
                    options={sortedCustomers.map((item) => {
                        return {value: item.customer, label: item.customer}
                    })} 
                    onChange={handleCustomerChange}    
                    />
            </div> }
            
            <h4>Selecione os Produtos</h4>
            {productsState.map(product => {
                return (
                <div key={product.name}>    
                    <input type="checkbox" 
                        id={product.name} 
                        name={product.name} 
                        value={product.name} 
                        checked={product.checked}
                        onChange={(e) => handleCheckboxChange(e, product)}
                        />
                    <label htmlFor={product.name}> {product.name}</label><br/>
                </div>
            )})}

            <button onClick={handleSubmit}> Enviar </button>
            <h4 className="error-message">{errMessage}</h4>
        </div>
    )
}

export default Form

I've removed the url that I'm posting the data, and also I'm still not sending the checkbox data, because it's not working.

handleCheckboxChange is the name of the function that is called whenever a checkbox is select (onChange).

It's my first question here, so sorry if the format is not the best or some more information is needed.

Could someone help me out? Thanks in advance!




lundi 27 septembre 2021

CSS check box problem should select when Ill checked it

I created a check box into a div and I created a label.I want that when Ill click to check box(#check_box) that time it (#pop_hidden)will be hidden{display: none}. no problem if I use javascript. I just need a solution

#check_box[type=checkbox]:checked : #pop_hidden {
  display: none;
}
<div>
  <input type="checkbox" id="check_box">
</div>
<div>
  <label id="pop_hidden">CSS is Awesome</label>
</div>
Its Working if I use
<!DOCTYPE html>
<html>
<head>
<style> 
#checkbox[type=checkbox]:checked + #pop_hidden {
    display:none;
} 
</style>
</head>
<body>

<input type="checkbox" id="checkbox" name="ossm"> 
<label id="pop_hidden">CSS is Awesome</label>



</body>
</html>

but I want to use it into the div like the first example




Make checkBox not clickable in React

I want to have a read-Only checkbox and disable the toggle( checked /unchecked) when I click the checkbox. Which possiblities I have? This is my code:

<label className="checkbox">
  <input type="checkbox"/>
</label>

I read a post where this workaround is proposed:

<input type="checkbox" onclick="return false" />

...but how can I use it in React?




In R Shiny, how to make the unchecking of a checkbox input to cause an action?

Below MWE code works as originally intended. When invoking the App, a matrix of checkboxes appears in sidebar panel with the option of show/hide/reset (only show/hide are working for simplicity of illustration) for a 2nd input matrix and a 3rd input matrix (only 2nd input matrix presents for simplicity of illustration), either/both of which appear (or would appear in case of 3rd input matrix) in sidebar panel.

However the hide function is better addressed by simply unchecking "Show", and I would like to eliminate the "Hide" checkbox. Does anyone know how to accomplish this? Check "Show" and 2nd input matrix appears; uncheck it and 2nd input matrix disappears. By default when invoking the App the 2nd input matrix needs to be hidden. (I ended up with show/hide as separate checkboxes because I had switched from action buttons to checkboxes...oops).

This will probably need to be put in a separate post, but for the checkbox matrix in the sidebar panel I'll also need to keep the columns for "Show" and "Reset" the same width and widen the 1st column which currently show "2nd input" and "3rd input".

MWE code:

library(shiny)
library(shinyjs)

### Begin checkbox matrix ###
f <- function(action,i){as.character(checkboxInput(paste0(action,i),label=NULL))}
actions       <- c("show", "hide", "reset")
tbl           <- t(outer(actions, c(1,2), FUN = Vectorize(f)))
colnames(tbl) <- c("Show", "Hide", "Reset")
rownames(tbl) <- c("2nd input", "3rd input")
### End checkbox matrix ###

firstInput <- function(inputId){
  matrixInput(inputId, 
              value = matrix(c(5), 1, 1, dimnames = list(c("1st input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

secondInput <- function(inputId,x){
  matrixInput(inputId, 
              value = matrix(c(x), 1, 1, dimnames = list(c("2nd input"),NULL)),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(extend = FALSE, names = FALSE, editableNames = FALSE),
              class = "numeric")}

ui <- fluidPage(
  tags$head(
    tags$style(HTML(
      "td .checkbox {margin-top: 0; margin-bottom: 0;}
       td .form-group {margin-bottom: 0;}"
    ))
  ),
  br(),
  sidebarLayout(
    sidebarPanel(
      uiOutput("panel"),
      hidden(uiOutput("secondInput")),
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server <- function(input, output){
  
  input1      <- reactive(input$input1)
  input2      <- reactive(input$input2)
  
  output$panel <- renderUI({
    tagList(
      useShinyjs(),
      firstInput("input1"),
      strong(helpText("Generate curves (Y|X):")),
      tableOutput("checkboxes") 
    )
  })
  
  ### Begin checkbox matrix ###
  output[["checkboxes"]] <- 
    renderTable({tbl}, 
      rownames = TRUE, align = "c",
      sanitize.text.function = function(x) x
    )
  observe({
    print(input[["show1"]])
    shinyjs::show("secondInput")
  })
  
  observe({
    print(input[["hide1"]])
    shinyjs::hide("secondInput")
  })
  ### End checkbox matrix ###
 
  output$secondInput <- renderUI({
    req(input1())
    secondInput("input2",input$input1[1,1])
  })
  
  outputOptions(output,"secondInput",suspendWhenHidden = FALSE) 
  
  output$plot1 <-renderPlot({
    req(input2())
    plot(rep(input2(),times=5))
  })
  
  observeEvent(input$show,{
    shinyjs::show("secondInput")
    updateCheckboxInput(session, "hide", value = FALSE)
  })
  
  observeEvent(input$hide,{
    shinyjs::hide("secondInput")
    updateCheckboxInput(session, "show", value = FALSE)
  })
   
}

shinyApp(ui, server)



wpf checkbox change color runtime

I have a pretty pain question that I just cannot figure out. I have a WPF application that should change a checkbox Text color on runtime. The checkbox is created through code because its a dynamic window with a lot of controls. If I change the Foreground color of the checkbox then it works until the first checking, then the Foreground color falls back to the deafult color. Can you suggest me a simple solution?




How should i display my checked results in different component,?

I have two checkboxes called slack and teams. If i check slack i wanted slack image to be displayed on different component.I almost made it but its displaying both slack and teams.Please have a look at my image, you may get idea what i am trying to askHere i selected one checkbox But the results are its displaying both




dimanche 26 septembre 2021

How to make the total correct according the selected checkboxes - PHP

The problem is that the first value of the first items is the only one getting read and the second value is not and then the Total price is not exact as the selected item. We were so confused on what would be causing the incorrect total price and why is the first value is the only one being read even though the second value is flash in the website but not read as it is being increment and used in the function. Here's the code of the said problem:

P.S. Thank you so much in Advance! and God Bless! <3

<script>
                            function totalSum() {
                                var price = document.getElementById("price");
                                var food = document.getElementsByName("foodSelection");
                                var quantity = document.getElementById("quantity");
                                var totalValue = document.getElementsByName("total");
                                var total = 0;
                                var multiply = 0;
                                var sum = 0;
                                for (var i = 0; i < food.length; i++) {
                                    if (food[i].checked) {
                                        // sum = parseInt(food[i].value) + parseInt(price.value);
                                        sum += parseInt(price.value);
                                        multiply = sum * parseInt(quantity.value);
                                        total += multiply;
                                        // total += parseInt(price.value);
                                    }
                                    quantity.value = parseInt(quantity.value);
                                    totalValue[0].value = total.toFixed(2) + "php";
                                }
                                
                            }
        </script>

            <div class = "food-recommendations">
                <h2>Food Recommendations</h2>

                <table class = "food-recommendation-table">
                    
                    <tr>
                        <th colspan ="3" style = "text-align: right;">Name</th>
                        <th>Price</th>
                        <th>Quantity</th>
                        <th>Description</th>
                    </tr>
                <?php

                        $sql = "SELECT * FROM foods";
                        $result = mysqli_query($conn, $sql);
                        
                        // $rows = mysqli_num_rows($result);
                                while($row = mysqli_fetch_assoc($result)) { 
                                    $name = $row['name'];
                                    $descrip = $row['foodDesc'];
                                    $pic = $row['pic'];
                                    $price = $row['price'];
                                    $foodID = $row['foodID'];
                                    $quanty = $row['quantity']; ?>
                                <?php echo '<tr><td valign = "center"><input name = "foodSelection" type="checkbox"  value = "'. $foodID .'"
                                                onclick="totalSum()"></td>
                                            <td><img src = "../admin/foods/img/'. $pic .'" height = "200px" width = "300px" 
                                            style = "border-radius: 30px;"></td>
                                            <td><h3>'. $name . '</h3></td>
                                            <td><p align = "center"><input type = "text" name="price" id = "price"  onblur = "totalSum()" value = "'.$price.'" style = "border:none; background: transparent;" hidden>₱'. $price .'</p></td>
                                            <td><input type="number" name="quantity" id="quantity" min="1" onclick="totalSum()" value = "'.$quanty.'"></td>
                                            <td><p class = "accomp-text">'. $descrip .'</p></td></tr>
                                            ';
                                            ?>
                        
                                <?php }?>
                    <tr>

                        <th colspan = "5" style = "text-align: right;">TOTAL</th>
                        <th><input type="text" name="total" id="total" value="0.00php" onclick = "totalSum()" readonly></th>
                    </tr>
                
                </table>
            </div>



how can i add multiple radio checked in one column

I want multiple radio checkboxes. In one line it should be private or shared and in the second line, it should be with ATV or Without ATV so people on my web can select shared and with ATV or many variables. so basically two selections are needed and 4four checkboxes are divided into two groups.

<!doctype html>
<html lang="en">

<head>
  <title>Title</title>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <style>
    .small-img-group {
      display: flex;
      justify-content: space-between;
    }
    
    .small-img-col {
      flex-basis: 24%;
      cursor: pointer;
    }
    
    .counter1 {
      float: left;
      display: flex;
      justify-content: space-between;
      overflow-x: hidden;
      overflow-y: hidden;
    }
    
    .counter2 {
      float: left;
      display: flex;
      justify-content: space-between;
      overflow-x: hidden;
      overflow-y: hidden;
      padding-left: 15px;
    }
    
    .up,
    .down {
      display: inline-block;
      color: rgb(0, 0, 0);
      font-size: 20px;
      margin: 1px 1px;
      cursor: pointer;
      width: 15px;
      line-height: 14px;
      height: 16px;
      text-align: center;
      font-weight: bold;
      border: 1px solid #000;
      user-select: none;
    }
    
    .up:hover,
    .down:hover {
      color: #fd0b3f;
      text-align: center;
    }
    
    .adults {
      padding-right: 5px;
    }
    
    .children {
      padding-right: 5px;
    }
    
    input {
      appearance: none;
      height: 21px;
      text-align: center;
      width: 42px;
      line-height: 24px;
      font-size: 15px;
      border-radius: 5px;
    }
    
    .container {
      display: flex;
    }
    
    input[type="radio"] {
      display: none;
    }
    
    label[for=private] {
      position: relative;
      color: orangered;
      font-size: 20px;
      border: 2px solid orangered;
      border-radius: 5px;
      align-items: left;
      display: flex;
      cursor: pointer;
      margin-right: 10px;
    }
    
    label[for=shared] {
      position: relative;
      color: orangered;
      font-size: 20px;
      border: 2px solid orangered;
      border-radius: 5px;
      align-items: left;
      display: flex;
      cursor: pointer;
    }
    
    input[type="radio"]:checked+label {
      background-color: orangered;
      color: white;
    }
    
    input[type="radio"]:checked+label:before {
      height: 16px;
      width: 16px;
      border: 10px solid white;
      background-color: orangered;
    }
  </style>

</head>

<body>
  <section class="container sproduct my-5 pt-5">
    <div class="row mt-5">
      <div class="col-lg-5 col-md-12 col-12">
        <img class="img-fluid w-100 pb-1" src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg" alt="" id="MainImg" width="450">

        <div class="small-img-group">
          <div class="small-img-col">
            <img src="https://media.tacdn.com/media/attractions-splice-spp-674x446/09/99/99/87.jpg" width="100%" class="small-img" alt="">
          </div>
          <div class="small-img-col">
            <img src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg" width="100%" class="small-img" alt="">
          </div>
          <div class="small-img-col">
            <img src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg" width="100%" class="small-img" alt="">
          </div>
          <div class="small-img-col">
            <img src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg" width="100%" class="small-img" alt="">
          </div>
        </div>
      </div>
      <div class="col-lg-6 col-md-12 col-12">
        <h6>Home / Morning Safari</h6>
        <h3>Morning Safari</h3>
        <h2> <label> Total:</label><label class="total Price"></label> </h2>
        <div class="counter1">
          <Label class="Adults">Adults</Label>
          <div class='down' onclick='decreaseCount(event, this)'>-</div>
          <input type='text' value='1' readonly>
          <div class='up' onclick='increaseCount(event, this)'>+</div>
        </div>
        <div class="counter2">
          <Label class="Children">Children</Label>
          <div class='down' onclick='decreaseCount2(event, this)'>-</div>
          <input type='text' value='0' readonly>
          <div class='up' onclick='increaseCount(event, this)'>+</div>
        </div>
        <div class="container" style="padding-left: 0;padding-top: 5px;">
          <input type="radio" name="occupancy" id="private" checked="checked">
          <label for="private">Private</label>
          <input type="radio" name="occupancy" id="shared">
          <label for="shared">Shared</label>
          <input type="radio" name="occupancy" id="private" checked="checked">
          <label for="private">With ATV</label>
          <input type="radio" name="occupancy" id="shared">
          <label for="shared">Without ATV</label>
        </div>

      </div>
    </div>
  </section>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <script>
    function increaseCount(e, el) {
      var input = el.previousElementSibling;
      var value = parseInt(input.value, 10);
      value = isNaN(value) ? 0 : value;
      value++;
      input.value = value;
    }

    function decreaseCount(e, el) {
      var input = el.nextElementSibling;
      var value = parseInt(input.value, 10);
      if (value > 1) {
        value = isNaN(value) ? 0 : value;
        value--;
        input.value = value;
      }
    }

    function decreaseCount2(e, el) {
      var input = el.nextElementSibling;
      var value = parseInt(input.value, 10);
      if (value > 0) {
        value = isNaN(value) ? 0 : value;
        value--;
        input.value = value;
      }
    }

    var MainImg = document.getElementById('MainImg');
    var smallimg = document.getElementsByClassName('small-img');

    smallimg[0].onclick = function() {
      MainImg.src = smallimg[0].src;
    }
    smallimg[1].onclick = function() {
      MainImg.src = smallimg[1].src;
    }
    smallimg[2].onclick = function() {
      MainImg.src = smallimg[2].src;
    }
    smallimg[3].onclick = function() {
      MainImg.src = smallimg[3].src;
    }
  </script>
</body>

</html>

Hi, I want multiple radio checkboxes. In one line it should be private or shared and in the second line it should be with ATV or Without ATV so people on my web can select shared and with ATV or many variables. so basically two selections are needed and 4four checkboxes are divided into two groups.




How to delete an item from recyclerview, in adapter class, when the checkbox in the itemview is checked [Android Studio]?

I have a tasks app where a checkbox is attached to the item. I want the item in recyclerview to be deleted or set invisible when the user checks the checkbox. But how do i delete an item in the adapter class?

My code so far -

static class TaskHolder extends RecyclerView.ViewHolder {
    private final TextView a_tname;
    private final TextView a_tdate;
    private  final TextView a_ttime;
    private final TextView a_tprior;
    ImageView priorityIndicator;
    CheckBox checkbox;

    public TaskHolder(View itemView) {
        super(itemView);
        a_tname = itemView.findViewById(R.id.a_tname);
        a_tdate=itemView.findViewById(R.id.a_tdate);
        a_ttime = itemView.findViewById(R.id.a_ttime);
        a_tprior = itemView.findViewById(R.id.a_tprior);
        priorityIndicator = itemView.findViewById(R.id.priorityIndicator);
        checkbox = itemView.findViewById(R.id.checkbox);
        checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkbox.isChecked()){
                    //how should i delete the item here?
                }
            }
        });

PS: I know how to delete it in the MainActivity through viewmodel and getAdapterPosition() but if I do the same thing in my adapter class, it shows NullPointerException. I am using android studio and Room database.




samedi 25 septembre 2021

Why there's a update state delay in checkbox, React

Something very weird is going on with my code and it does not makes any sense. Every time I save/store some data it has a "delay" like for example if I click 2 checkboxes, when I click the first one nothing happens, when I click the second one it grabs the value of the first one I clicked. let me show you:

enter image description here

Now the same happens when I click the one that selects all of them but it does not affects the maths at least (which is the most important part) here:

enter image description here

if I unselect all it shows that all the values where being saved at least:

enter image description here

now comes the even more weird part if I do one by one then the maths doesn't match and is because is not "adding" the one I click first:

enter image description here

Here is my piece of code I mean technically is working but clearly I'm missing something idk let me know if you require something else:


// "librosnuevos" get updated on the firebase I will not add it cause I think is not necessary 

const [librosNuevos, setLibrosNuevos] = useState([]);
const [LibrosID, setLibrosID] = useState([]);
    const handleChange = (e, data) => {
    const { name, checked } = e.target;
    if (checked) {
      // if cheked and selectall checkbox add all fileds to selectedList
      if (name === "allSelect") {

        setLibrosID(librosNuevos);
        let x = 0
        librosNuevos.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })

      } else {
        // if cheked and specific checkbox add specific field to selectedList
        setLibrosID([...LibrosID, data]);

        let x = 0
        LibrosID.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })
      }
    } else {
      // if uncheked and selectall checkbox add remove all fileds from selectedList
      if (name === "allSelect") {
        setLibrosID([]);

        let x = 0
        librosNuevos.map((i) => {
          x = 0
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })

      } else {
        // if uncheked and specific checkbox remove specific field from selectedList
        let tempuser = LibrosID.filter((item) => item.id !== data.id);
        setLibrosID(tempuser);

        let x = 0
        tempuser.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })
      }
    }
    console.log(LibrosID)
  };

//Parent Checkbox
<input
type="checkbox"
className="form-check-input"
name="allSelect"
checked={LibrosID?.length === librosNuevos?.length}
onChange={(e) => handleChange(e, librosNuevos)}
/>

//Mapped checkbox-child

{librosNuevos.map((libros, index) => (
<tr key={libros.id || index}>
<td >
<input
type="checkbox"
className="form-check-input"
 name={libros.id}
checked={LibrosID.some((item) => item?.id === libros.id)}
onChange={(e) => handleChange(e, libros)}
/>

... some smart code that finish the table
}



changing default behavior of a checkbox

I am using a plugin on my WordPress that displays a checkbox. When that checkbox is checked then only the "In stock" items are displayed. By default that checkbox is unchecked. I want the check box checked by default. How do I edit the code to make that happen?

Code when the checkbox is unchecked

<input type="checkbox" class="cwpf_checkbox_instock" id="cwpf_checkbox_instock" name="stock" value="0">

Code when the checkbox is checked

<input type="checkbox" class="cwpf_checkbox_instock" id="cwpf_checkbox_instock" name="stock" value="0" checked="checked">

is it possible to modify the code to have the checkbox checked by default?

Thanks




how to display check button after select item in combo box in tkinter

I need help with my program I have a combo box with a set of items. I want to show me a set of check box when I select any of these items. Checkbox options are different for each item of the combo box




vendredi 24 septembre 2021

How to implement keyboard navigation with custom checkboxes in React

I am trying to create a custom checkbox that removes the checked icon and instead uses the text as the button. However, when I implement this, the keyboard navigation is removed. How can I bring back, or not get rid of keyboard navigation with a custom checkbox?

Note: I am using Formik to handle the validation and submission and Tailwind for the styling.

<div
        key={index}
        className="rounded-md ring-offset-primary ring-offset-2 focus:ring-quad focus:outline-none focus:ring-2 flex gap-2"
      >
        <label htmlFor={player.name} className="cursor-pointer">
          <Field
            type="checkbox"
            onClick={() => handleSetChecked(index)}
            id={player.name}
            name="players"
            value={player.name}

            className="opacity-0 cursor-pointer hidden"
          />
          <span
            className={`block h-full py-1 px-2 rounded-md transition-all border-2 border-quad text-base ${
              checkedStatus[index] ? 'bg-quad text-primary' : 'bg-transparent'
            }`}
          >
            {player.name}
          </span>
        </label>
      </div>




How to change the UI state of a group of Checkboxes with Formik

I have a series of checkboxes that need to change their UI when they are clicked. For example, if the first checkbox is clicked, it should change color independently from the others.

This is my current work, but it works like a radio button because only one checkbox is checked at a time.

function RecordGame() {
const [checkedStatus, setCheckedStatus] = useState(members.map(() => false))

  const handleSetChecked = async (index) => {
    let newState = members.map(() => false)
    console.log(newState)
    newState[index] = true
    setCheckedStatus(newState)
  }

  
const playerCheckboxes = members.map((player, index) => {
  return (
    <div key={index} className="flex gap-2">
      <label htmlFor={player.name}>
        <Field
          checked
          type="checkbox"
          onClick={() => handleSetChecked(index)}
          id={player.name}
          name="players"
          value={player.name}
        />
        <span
          // Change the checkbox UI based on the checkedStatus
          className={`${checkedStatus[index] ? 'bg-quad text-primary' : 'bg-transparent'}`}
        >
          {player.name}
        </span>
      </label>
    </div>
  )
})

return( {playerCheckboxes} }



Why there's a "delay" when values are being stored using checkbox select?

Something very weird is going on with my code and it does not makes any sense. Every time I save/store some data it has a "delay" like for example if I click 2 checkboxes, when I click the first one nothing happens, when I click the second one it grabs the value of the first one I clicked. let me show you:

enter image description here

Now the same happens when I click the one that selects all of them but it does not affects the maths at least (which is the most important part) here:

enter image description here

if I unselect all it shows that all the values where being saved at least:

enter image description here

now comes the even more weird part if I do one by one then the maths doesn't match and is because is not "adding" the one I click first:

enter image description here

Here is my piece of code I mean technically is working but clearly I'm missing something idk let me know if you require something else:


// "librosnuevos" get updated on the firebase I will not add it cause I think is not necessary 

const [librosNuevos, setLibrosNuevos] = useState([]);
const [LibrosID, setLibrosID] = useState([]);
    const handleChange = (e, data) => {
    const { name, checked } = e.target;
    if (checked) {
      // if cheked and selectall checkbox add all fileds to selectedList
      if (name === "allSelect") {

        setLibrosID(librosNuevos);
        let x = 0
        librosNuevos.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })

      } else {
        // if cheked and specific checkbox add specific field to selectedList
        setLibrosID([...LibrosID, data]);

        let x = 0
        LibrosID.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })
      }
    } else {
      // if uncheked and selectall checkbox add remove all fileds from selectedList
      if (name === "allSelect") {
        setLibrosID([]);

        let x = 0
        librosNuevos.map((i) => {
          x = 0
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })

      } else {
        // if uncheked and specific checkbox remove specific field from selectedList
        let tempuser = LibrosID.filter((item) => item.id !== data.id);
        setLibrosID(tempuser);

        let x = 0
        tempuser.map((i) => {
          x += i.precio
          setTPLibrosNuevos(parseFloat(x).toFixed(2))
        })
      }
    }
    console.log(LibrosID)
  };




MySql Entry Shows NULL

When you tick the optional checkbox to subscribe to my newsletter on my html form and when you submit the form, my Mysql Database entry "newsletter_subscribe_yes" column shows NULL entry. Why ?

Particular Form Input

<label for="newsletter_subcribe_yes">Newsletter Subcribe:Yes</label>
<input type="checkbox" name="newsletter_subcribe_yes" id="newsletter_subcribe_yes" value="Newsletter Subcribe:Yes">
<br>

Full Form Submission Script

<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
?>

<form method="POST" name="textfield" id="textfield" action="" required>
<label for="domain">Domain:</label><br>
<input type="text" name="domain" id="website_domain" maxlength="255" size="25">
<br>
<label for="email">Email:</label><br>
<input type="email" name="domain_email" id="email_address" maxlength="255" size="20">
<br>
<label for="url">Url:</label><br>
<input type="url" name="url" id="website_address" maxlength="255" size="50">
<br>
<label for="text">Title:</label><br>
<input type="text" name="title" id="title" value="" maxlength="255" size="60">
<br>
<label for="text">Anchor:</label><br>
<input type="text" name="anchor" id="link_text" value="" maxlength="255" size="60">
<br>
<label for="description">Description:</label><br>
<textarea name="description" id="website_description" cols="50" rows="10"></textarea>
<br>
<label for="keywords">Keywords:</label><br>
<textarea name="keywords" id="website_keywords" cols="50" rows="10"></textarea>
<br>
<b>Terms & Conditions:</b>
<input type="radio" name="tos_agree" id="yes" value="Agree to TOS: Yes:"><label for="yes">Agree to TOS: Yes:</label>
<input type="radio" name="tos_agree" id="no" value="Agree to TOS: No:"><label for="no">Agree to TOS: No:</label>
<br>
<label for="newsletter_subcribe_yes">Newsletter Subcribe:Yes</label>
<input type="checkbox" name="newsletter_subcribe_yes" id="newsletter_subcribe_yes" value="Newsletter Subcribe:Yes">
<br>
<button type="reset">Reset!</button>
<br>
<button type="submit" name="submit" id="submit">Submit!</button><br>
</form>

<?php

$labels_assoc = array("domain_email"=>"required","domain"=>"required","url"=>"required","title"=>"not required","anchor"=>"required","description"=>"required","keywords"=>"required","tos_agree"=>"required","newsletter_subscribe_yes"=>"not required");
$labels_keys = array_keys($labels_assoc);

if($_SERVER['REQUEST_METHOD']==='POST')
{
    $errors = array();
    //Form Labels (name="") & MySql Table Column Names.
    $labels_assoc = array("domain_email"=>"required","domain"=>"required","url"=>"required","title"=>"not required","anchor"=>"required","description"=>"required","keywords"=>"required","tos_agree"=>"required","newsletter_subscribe_yes"=>"not required");
    $labels_keys = array_keys($labels_assoc);

    foreach($labels_assoc as $key=>$value)
    {
        if($value=="required")
        {
            if(empty($_POST[$key])||!is_string($_POST[$key]))
            {
                $errors[] = '<b>' .ucfirst($key) .'</b>'  .' is required!';
            }
            else
            {
                //Required Input
                if($key == 'domain_email' && !filter_input(INPUT_POST,"domain_email",FILTER_VALIDATE_EMAIL))
                {
                    die('Enter a valid Email!');
                }
                //Required Input
                elseif($key == 'domain' && !filter_input(INPUT_POST,"domain",FILTER_VALIDATE_DOMAIN))
                {
                    die('Enter a valid Domain!');
                }
                //Required Input
                elseif($key == 'url' && !filter_input(INPUT_POST,"url",FILTER_VALIDATE_URL))
                {
                    die('Enter a valid Url!');
                }
                //Optional Input
                elseif($key == 'title' && !EMPTY($key['title']) && !filter_input(INPUT_POST,"title",FILTER_SANITIZE_STRING))
                {
                    die('Enter a valid Page Title!');
                }
                elseif($key == 'anchor' && !filter_input(INPUT_POST,"anchor",FILTER_SANITIZE_STRING))
                {
                    die('Enter a valid Page Anchor!');
                }
                elseif($key == 'description' && !filter_input(INPUT_POST,"description",FILTER_SANITIZE_STRING))
                {
                    die('Enter a valid Page Description!');
                }
                elseif($key == 'tos_agree' && EMPTY($_POST['tos_agree']))
                {
                    die('You must agree to tos (terms & conditions)!');
                }
            }
        }
    }

    if(!empty($errors))
    {
        foreach($errors as $error)
        {
            echo '<b>Line ' .__LINE__ .': </b>'; echo 'Error Alert: ' .$error; echo '<br>';
        }
    }
    
    //TEST RESULT:
    //$_POST[''] outputs the value of value="".
    //For php to extract user input, the radio html needs to have the value="". Php cannot extract without it.


    //MYSQLI CONNECTION.
    mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

    $server = 'localhost';
    $user = 'root';
    $password = '';
    $database = 'index';

    if(!$conn = mysqli_connect("$server","$user","$password","$database"))
    {
        echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
        echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
    }

    mysqli_set_charset($conn,'utf8mb4');


    $col1 = $labels_keys["0"];
    $col2 = $labels_keys["1"];
    $col3 = $labels_keys["2"];
    $col4 = $labels_keys["3"];
    $col5 = $labels_keys["4"];
    $col6 = $labels_keys["5"];
    $col7 = $labels_keys["6"];
    $col8 = $labels_keys["7"];
    $col9 = $labels_keys["8"];

    $sql = "INSERT into links ($col1,$col2,$col3,$col4,$col5,$col6,$col7,$col8,$col9) VALUES (?,?,?,?,?,?,?,?,?)";
    $stmt = mysqli_stmt_init($conn);
    mysqli_stmt_prepare($stmt,$sql);
    mysqli_stmt_bind_param($stmt,'sssssssss',$_POST["$col1"],$_POST["$col2"],$_POST["$col3"],$_POST["$col4"],$_POST["$col5"],$_POST["$col6"],$_POST["$col7"],$_POST["$col8"],$_POST["$col9"]);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
    }

?>

I'd appreciate any mentions of any other coding errors on my script apart from the problem I mentioned.

Thank You!




Allign Textboxes with label inside form & table

I've started learning HTML-CSS new for the last 2 days and build this. So please upvote if I'm doing well. or leave feedback too. suggestions are welcome.

enter image description here

I'm not able to align checkboxes with labels under a form & a table.

I went through these answers & some websites too. I'm still not getting it. How to align checkboxes and their labels consistently cross-browsers

I removed the CSS i wrote, as it didn't work.

td{
    color:#FFFFFF;
    background-color: #548EA3;
    border-spacing: 5px;
    border: 1px solid #FFFFFF;
        }

table,td{
    font-size: 15px;
    font-family: Georgia;
    border-radius: 6px;
    padding: 3px;
        }
<tr>
        <td>Possible charges involved</td>
        <td>
        <label><input type="checkbox" name="category" id="packing">Packing Charges</label>
        <label><input type="checkbox" name="category" id="Loading">Loading Charges</label>
        <label><input type="checkbox" name="category" id="Transportation">Transportation Charges</label>
        <label><input type="checkbox" name="category" id="Unloading">Unloading Charges</label>
        <label><input type="checkbox" name="category" id="Unpacking">Unpacking Charges</label>
        <label><input type="checkbox" name="category" id="Escort">Escort Charges</label>
        <label><input type="checkbox" name="category" id="Octroi">Octroi Charges</label>
        </td>
    </tr>



JS Increment value for each onclick after checking if true

I want to check if all checboxes are checked.

For this, I got this code :

bind() {
    this.checks = document.getElementsByClassName("checkdoc");
    const len = this.checks.length;
    this.validCheckbox = 0;

    for (let i = 0; i < len; i++) {
        this.checks[i].onclick = this.updateValid;
    }

    if (this.validCheckbox === len) {
        this.allChecked = true;
        this.update();
    }
}

updateValid() {
    if (this.checked === true) {
        this.validCheckbox += 1;
    } else {
        this.validCheckbox -= 1;
    }
    console.log(this.validCheckbox);
}

But it don't work because this.validCheckbox is NaN so undefined. If I add it as parameters in this.updateValid like this :

this.updateValid(this.validCheckbox)
...

updateValid(nb) {
    if (this.checked === true) {
        nb += 1;
    } else {
        nb -= 1;
    }
    console.log(nb);
    return nb;
}

First, my console.log give me -1 on the 2nd method, then I can't do multiple calls. If I click on the 1st checkbox, nothing happens because onload, the first call is made. If you got any tips, I'll take it




How to check Dynamic Checkbox in React JS

I have a dynamic form with the following implementation. The problem is that I want to "check" the checkbox IF the answer of that "questionID" exists in the answers array with the selected option (i.e A,B). so the condition of the check should be answers[index].userChoice.option is equal to Object.keys(x). enter image description here

import fieldsL from "./fields.json"; 

function App() { 
  let [Fields , setFields] = useState([]);
  let [answers, setAnswers] = useState([]);
const updateAnswer = ((qid,option,optionValue) => {
      let ans = answers;
      let singleAns = {
        questionId : qid,
        userChoice: 
        { 
          option: option, 
          optionValue: optionValue, 
          isChecked: true
        }
      };
      if(answers.length > Fields) return console.warn("Invalid Question ID")
      if(answers.find((sp) => sp.questionId === qid)) {
        var index = answers.map(function(x1) {return x1.questionId}).indexOf(qid);
        answers[index].userChoice.option = option;
        answers[index].userChoice.optionValue = optionValue;
        console.log("Existing Answer Updated");
      }
      else ans.push(singleAns)
      ans.sort((a, b) => parseFloat(a.questionId) - parseFloat(b.questionId)); 
      setAnswers(ans)
      console.log(answers)
  })

useEffect(()=>{
  console.log("useEffect")
  setFields(fieldsL.data)
},[])
let Questions = fieldsL.data.question;
let displayFields = Questions.map((e,index)=>{
return <div key={index} >
<label className="label">{e.content}</label>

<div className="control">
{
e.radio?  e.option.map((x,index2) => {

  console.log(index)
  //console.log(x)
 return <div classID="field" key={index2}>
<div classID="control">
  <label classID="checkbox">
    <label> {Object.keys(x)[0]}     </label>

    <input type="checkbox" name="question" onChange={()=> updateAnswer(e.questionId,Object.keys(x)[0],Object.values(x)[0])}/>
    &nbsp; {Object.values(x)[0]}
    { 

    }
  </label>
</div>
</div> }
) : <span>Empty</span>
}
</div>
</div>;
})




Does Microsoft provide any API to access Macro enabled Excel files

I am trying to create a JSON file by getting data from a macro enabled Excel file which has radio buttons and checkboxes. Can anyone tell me if MS provides any API to do so or how I can do it otherwise.

Thanksenter image description here




jeudi 23 septembre 2021

How to handle data display with multiple checkboxes in React Js

I'm working on a app where on component load after fetch GET API, list of cars are displayed to user. There're also multiple checkboxes which allow user to filter displayed data. I'm filtering the results depending on selected checkbox value, but the problem is that I don't know how to display first whole list of cars, and only then filtered results ( if user selects any checkbox). My code is:

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

export default function CarsMain() {
  const [filterList] = useState([
    {
      value: "BMW"
    },
    {
      value: "Hyundai"
    },
    {
      value: "Mercedes"
    }
  ]);
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);

  useEffect(() => {
   
      fetch(url)
        .then(function (response) {
          return response.json();
        })
        .then(function (res) {
          setData(res);
        })
        .catch(function (e) {
          console.log(e);
        })
    );
  }, []);


  function handleCheckbox(value, e) {
    if (e.target.checked) {
      let selectedData = data.filter((d) => d.model === value);

      setFilteredData([...filteredData, ...selectedData]);
    } else {
      let unselected = filteredData.filter((d) => {
        return d.model !== value;
      });
      setFilteredData(uncheckedData);
    }
  }

  return (
  
          <div >
            {filterList?.map((v) => {
              return (
                <div key={v.model}>
                  <input
                    type="checkbox"
                    onChange={(e) => handleCheckbox(v.model, e)}
                  />
                </div>
              );
            })}
          </div>
           {filteredData.map((d) => {d.model})

        </div>
      </div>
    </div>
  );
}

checkbox select works fine, when BMV is selected, only cars with model === "BMV" are displayed, the issue is that when page loads there is no data displayed, only after I select one of the checkboxes, the list of cars would be displayed. I can't seem to figure out how to display the whole list at page load an then filteredData ( when/if user selects checkbox). I'm mapping over filteredData because if I map over data(stored from API), checkbox selection doesn't work. How can I display data received from API on page load and when no checkbox is selected, and only selected car models after user clicks checkbox. Any help and advise are greatly appreciated.




checkbox Enable/disable with struts

I would like to show 2 checkboxs in my page (called box1 and box2). The default value is box1 = false and box2 = false. But I also have to enable box2 only if box1 = true. So I have created the following JS function :

function myTest() {
  var check = document.getElementById('box1');
  if (check.checked == false) {
    $('#box2').prop('disabled', true);
  } else {
    $('#box2').prop('disabled', false);
  }
}

Now I don't really understand how to use my test function in the jsp file. I have tried to use it with onload="myTest()" as follow, but it doesn't work (box2 is always disabled).

<body onload="myTest()" />

<div class="form-group row">
    <label class="col-sm-3 col-form-label required">
        <s:text name="box1" />
    </label>
    <div class="col-sm-9">
        <s:checkbox id="box1" name="box1"> </s:checkbox>
    </div>
</div>
<div class="form-group row">
    <label class="col-sm-3 col-form-label required">
        <s:text name="box2" />
    </label>
    <div class="col-sm-9">
        <s:checkbox id="box2" name="box2"></s:checkbox>
    </div>
</div>

Any help please?




Dynamically add checkboxes to a listview

I am trying to make an app that takes the number of sets, and number of reps for each set from the user, and adds rows ( for each set) and checkboxes (for each rep) that is what is should look like:

for the reps: i made a method that takes the number of reps from the SQLite server, and loops through the number of reps to make the checkboxes.

for the sets: i made list adapter to make each row.

the final results for 2 sets, and 2 reps each look like this: enter image description here

how can i make the reps be contained inside the rows? thanks.

Java class:

package com.example.workouttracker;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;

public class WorkoutInterface extends AppCompatActivity implements View.OnClickListener {

    String workoutName;
    int workoutSets;
    int workoutReps;
    LinearLayout linearLayout;
    ListView listView;
    String TAG = "Test";
    ArrayList<String> sets;// array for each set, so we can show list of sets, and the reps for each set.
    ArrayAdapter<String> adapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.workout_interface);
        linearLayout=findViewById(R.id.ll1);
        sets=new ArrayList<>();
        sets.add("Set Number: ");
        listView=findViewById(R.id.listview);
        adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1,sets);
        listView.setAdapter(adapter);
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                workoutName = null;
                workoutSets = 0;
                workoutReps=0;
            } else {
                workoutName = extras.getString("workout_name");
                workoutSets = extras.getInt("workout_sets");
                workoutReps=extras.getInt("workout_reps");
            }
        } else {
            workoutName = (String) savedInstanceState.getSerializable("workout_name");
            workoutSets = (int) savedInstanceState.getSerializable("workout_sets");
            workoutReps = (int) savedInstanceState.getSerializable("workout_reps");

        }
        System.out.println("workout name is - " + workoutName + ", and workout sets number is - " + workoutSets + " NOTICCEEEE MEEEEEEEE!!@#TYU&^%$#$%");

        int numberOfSets = workoutSets;// the TOTAL number of sets.
        int numberOfReps =workoutReps;

//        addRepsCheckBox(numberOfReps);
        addSet(numberOfSets,numberOfReps);

    }

private void addSet(int numberOfSets,int numberOfReps){
        for (int j=1;j<=numberOfSets;j++){
            sets.add("Set Number: "+ j);
            addRepsCheckBox(numberOfReps);
            listView.setAdapter(adapter);


        }
}

    private void addRepsCheckBox(int numberOfReps) {
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        for (int i = 1; i <= numberOfReps; i++) {
            CheckBox checkBox=new CheckBox(this);
            checkBox.setId(View.generateViewId());
            checkBox.setText("Rep: "+checkBox.getId());
            checkBox.setOnClickListener(this);
            listView.addFooterView(checkBox);

        }
        }

    @Override
    public void onClick(View v) {
        Log.d(TAG, " Name " + ((CheckBox)v).getText() +" Id is "+v.getId());

    }

}

XML:

'''

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >



    <LinearLayout
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/ll1">

      <ListView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:id="@+id/listview"
          tools:ignore="InvalidId"/>





    </LinearLayout>

</RelativeLayout> '''



Select all checkboxes by group in laravel 8

I want to make select all but divided by group, all I can do is select all checkboxes, not by group

here's is my blade:

<div class="row">
    @php $i = 1; @endphp
    @foreach($permissions as $group => $permission)
    <div class="col-md-6 ">
        <div class="row mb-3 ">
            <div class="col-md-6">
                <b></b>
            </div>
            <div class="col-md-6 d-flex justify-content-end">
                <div class="custom-control custom-checkbox  custom-control-right">
                    <input id="" type="checkbox" class="custom-control-input" onchange="checkAll(this)" />
                    <label for="" class="custom-control-label">
                        Select All
                    </label>
                </div>
            </div>
        </div>


        @foreach($permission as $p)
        <div class="row ">
            <div class="col-md-6">
                <p></p>
            </div>
            <div class="col-md-6 d-flex justify-content-end">
                <div class="custom-control custom-checkbox  custom-control-right">
                    <input id="ekspor_dashboard" name="permission_id[]" type="checkbox"
                        class="custom-control-input" value="" />
                    <label for="ekspor_dashboard" class="custom-control-label mr-auto"></label>
                </div>
            </div>
        </div>
        @endforeach
    </div>

    @php $i += 1 @endphp
    @endforeach
</div>
</div>

this is the screenshot of the view: enter image description here

I already add select all but it's select all checkboxes, I don't know if I should fix the loop so I can get id from the permission. I just stuck on this.

here's the javascript that I use for the select

<script>
    function checkAll(ele) {
        var checkboxes = document.getElementsByTagName('input');
        if (ele.checked) {
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].type == 'checkbox' && !(checkboxes[i].disabled)) {
                    checkboxes[i].checked = true;
                }
            }
        } else {
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].type == 'checkbox') {
                    checkboxes[i].checked = false;
                }
            }
        }
    }
</script>



Why checkbox checked does not work for element in different element / div?

I am trying to have hamburger menu in header and menu to toggle from side inside content, under header, but I have problem with it. I think that for some reason selector input[type="checkbox"]:checked ~ #sidebarMenu does not want to work if checkboox is in different div than #sidebarMenu itself.

#sidebarMenu, .sidebarMenu {
    height: 100%;
    width: 250px;
    transform: translateX(-270px);
    transition: transform 250ms ease-in-out;
    background: #fff;
    z-index: 1;
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    vertical-align: middle;
    margin-top: 0px;
    box-shadow: 0px 2px 5px 5px rgb(0 0 0 / 16%), 0 0px 10px 1px rgb(0 0 0 / 12%);
}

input[type="checkbox"]:checked ~ #sidebarMenu {
    transform: translateX(0) !important;
}

This does not work:

<div class="container">     
<input type="checkbox" class="openSidebarMenu" id="openSidebarMenu">
<label for="openSidebarMenu" class="sidebarIconToggle">
<div class="spinner diagonal part-1"></div>
<div class="spinner horizontal"></div>
<div class="spinner diagonal part-2"></div>
</label>
</div>

<div id="content" class="site-content container clear">   
<div id="sidebarMenu">
<ul class="sidebarMenuInner">
</ul>
</div>
</div>

This works:

<div class="container">     
<input type="checkbox" class="openSidebarMenu" id="openSidebarMenu">
<label for="openSidebarMenu" class="sidebarIconToggle">
<div class="spinner diagonal part-1"></div>
<div class="spinner horizontal"></div>
<div class="spinner diagonal part-2"></div>
</label>
<div id="sidebarMenu">
<ul class="sidebarMenuInner">
</ul>
</div>
</div>



Need your help in how to link a check box with macro

I have some check boxes in google sheet, and I need if I checked some of it (1 of pic) then run macro do the next copy specific cells with its formats (2 of pic) and paste it in the cell beside the check box

enter image description here




mercredi 22 septembre 2021

How to 'Indeterminate' checkboxs?

Hello I want to know how to apply "Indeterminate" to my code Checkbox example:

enter image description here

I know the documentation is right there but I wasn't able to make it work this was my attempt and I would say I was close but clearly missing something very important

enter image description here

The idea is that when I click the "parent" one all of them get clicked, all of them changed to checked and all of them send the data to a variable and when I unclick they should remove it, and when I remove one in particular it should only remove that one in particular (that one is already working but idk if I have to add something else for the parent)

Individually they do what I want but I wanted to add the parent/main one so I can just check all of them:

enter image description here

This is my code:

//Functions

//set all students attempt
const [allStudentsID, setAllStudentsID] = useState();
const setAllStudents = () => {
  setAllStudentsID(Array.isArray(estudiantes)?estudiantes.map(x=> x.label):[]);
  console.log(allStudentsID)
}


//set individual one by one (works)
const [studentID, setStudentID] = useState([])
const setStudent = (estudiante) => {
  if(!studentID.find(id => id === estudiante)){
    setStudentID([ ... studentID, estudiante]); 
 }  
  else {
   setStudentID(studentID.filter(studentId => studentId !== estudiante)) 
   }  

   console.log(studentID)
}

Mapping/Render:

//Titles (not sure if I'm setting up correctly the checkbox)
                <thead>
                    <tr className="Lista">
                        <th ><Checkbox 
                              color = "primary" 
                              id = "checkBox" 
                              onChange = {() => setAllStudents()}
                              />
                        </th>
                        <th>Nombre</th>
                        <th>Colegio</th>
                        <th>Grado</th>
                        <th>Accion</th>
                    </tr>
                </thead>

//Table (this works)
{estudiantes.map((estudiantes, index) => (
                <tr key={estudiantes.id || index}>
                <td>
                <Checkbox
                checked={!!studentID.find( id => id === estudiantes.uid)}
                color = "primary"
                id = "checkBox"
                onChange = {() => setStudent(estudiantes.uid, index)}
                inputProps=aria-label
                />
                </td>

... some code that will finish the table



Spinner with Checkbox and Textboxes recognize, when Item Checked State is change, in the Adapter

i have in my RecylcerViewAdapter a Spinner, with a SpinnerAdapter, because i have Checkbox - TextView, with dynamic Items.

I want to recognize in my RecylcerViewAdapter, when a SpinnerItem checked, to do things in my RecyclerViewAdapter. The View works fine.

How i add:

AdditionSpinnerAdapter adapter = new AdditionSpinnerAdapter(context, 0, categoryProductAddition.Product_Additions);
vh.AdditionSpinner.Adapter = adapter;

My SpinnerAdapter

namespace AndroidRegFirstApp.Adapter
{
public class AdditionSpinnerAdapter : ArrayAdapter<ProductAddition>
{
    private Context mContext;
    private List<ProductAddition> additions;
    
    public AdditionSpinnerAdapter(Context context, int resource, List<ProductAddition> objects) :base (context, resource, objects)
    {
        this.mContext = context;
        this.additions = objects;
    }

    public override View GetDropDownView(int position, View convertView, ViewGroup parent)
    {
        return this.GetCustomView(position, convertView, parent);
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        return this.GetCustomView(position, convertView, parent);
    }

    public View GetCustomView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.From(mContext);
        convertView = inflater.Inflate(Resource.Layout.additionSpinnerItem, null);

        TextView AdditionText = convertView.FindViewById<TextView>(Resource.Id.additionText);
        CheckBox AdditionSelected = convertView.FindViewById<CheckBox>(Resource.Id.additionSelected);

        AdditionText.Text = additions[position].Product_Addition_Name;
        AdditionSelected.Checked = additions[position].Product_Addition_Selected;

        AdditionSelected.Tag = position;

        if (position == 0)
        {
            AdditionSelected.Visibility = ViewStates.Gone;
        }

        AdditionSelected.SetOnCheckedChangeListener(new Interface.OnCheckedListener(additions));

        return convertView;
    }
}

}

My OnCheckedListener:

public OnCheckedListener(List<ProductAddition> list)
    {
        this.additions = list;
    }

    public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
    {
        int position = (int)buttonView.Tag;
        this.additions[position].Product_Addition_Selected = isChecked;
    }

Now i want to when the OnCheckedChanged is change the state, that a methode in my RecylcerViewAdapter calls.




How can I call a method from inside another method without getting a ReferenceError?

I have the following method in a StimulusJS controller that sets the state of a "master" checkbox depending on the children checkboxes' state.

I'm trying to refactor it and move the arrow function behaviour to a private method but I'm getting ReferenceErrors when calling the private method from the main one.

I've tried declaring the private method within the main one to no success.

What is the correct way to do it?

main function:

  updateSelectAllCheckboxState() {
    let selectAllCheckBox = this.selectAllTarget
    const allChecked = (checkbox) => checkbox.checked; // I want to move this to a private method

    if (allChecked()) {
      selectAllCheckBox.indeterminate = false
      selectAllCheckBox.checked = true
    }
  }

refactor. I get ReferenceError: allChecked is not defined:

  updateSelectAllCheckboxState() {
    let selectAllCheckBox = this.selectAllTarget

    if (allChecked()) {
      selectAllCheckBox.indeterminate = false
      selectAllCheckBox.checked = true
    }
  }


// private

  allChecked() {
    const allChecked = (checkbox) => checkbox.checked;
    
    if (this.checkboxTargets.every(allChecked) {
      return true
    }
  }



How to align HTML checkbox to left when adjusting its size with CSS?

I'm having some troubles with CSS. In particular, whenever I increase the width of a checkbox, it increases the size of a container around it, moving its alignment away from the start of the page. It is hard to explain, instead I will include a picture below to better detail my problem.

Here is how I would prefer it to be aligned, but larger:

Screen shot of checkbox aligned correctly

And here is how it aligns itself when I increase the width:

Screen shot of larger checkbox but aligned incorrectly

Again, my goal is to increase the width of the checkbox, while keeping its alignment to the start of the page. I am not using any third-party CSS libraries like Bootstrap incase anyone is wondering. I've tried adjusting the margin, text-align, and float CSS attributes with no luck so far. Anyone have any ideas? I'll post the relevant code below.

input[type=text],
input[type=tel],
select {
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .1);
  border-radius: 4px;
  height: 20px;
  line-height: 20px;
  padding-left: 5px;
}

input[type=text],
input[type=tel],
label {
  color: rgba(0, 0, 0, .8);
  width: 176px;
}

label {
  margin: 5px;
}

input[type=checkbox] {
  height: 20px;
  width: 176px;
}
<!DOCTYPE html>
<html lang="en-US">

<head>
  <title>Learning Jquery</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body>
  <h1 class="header">Header</h1>

  <form id="input__form" action="" method="POST">
    <!-- Additional inputs -->
    <label for="input__zip">Zip</label><br />
    <input type="text" id="input__zip" name="input__zip" /><br />
    <label for="input__current__employee">Current Employee</label><br />
    <input type="checkbox" id="input__current__employee" name="input__current__employee" /><br />
    <input type="submit" id="input__submit" name="input__submit" value="submit" />
  </form>

</body>

</html>



Select2: adding checkbox to options but not to optgroup

using Select2, i need to add a checkbox to left of each option. i also have the options grouped using optgroup. however, a checkbox is appearing on a blank line before the group. i lifted code from a couple of postings and was able to hide the checkbox to left of the group but i cant figure out how to remove the blank line before the group. attached blank line before the group is the picture of what i am encountering and following is my code thanks in advance.

 $(".js-select2").select2({
            closeOnSelect : false,
            placeholder : "Placeholder",
            allowHtml: true,
            allowClear: true,
            tags: true 
        });
body { 
    font-family: 'Ubuntu', sans-serif;
    font-weight: bold;
}
.select2-container {
  min-width: 400px;
}

.select2-results__option {
  padding-right: 20px;
  vertical-align: middle;
}

.select2-results__option:before {
  content: "";
  display: inline-block;
  position: relative;
  height: 20px;
  width: 20px;
  border: 2px solid #e9e9e9;
  border-radius: 4px;
  background-color: #fff;
  margin-right: 20px;
  vertical-align: middle;
}
.select2-results__option[aria-selected=true]:before {
  font-family:fontAwesome;
  content: "\f00c";
  color: #fff;
  background-color: #f77750;
  border: 0;
  display: inline-block;
  padding-left: 3px;
}


.select2-container--default .select2-results__option[aria-selected=true] {
    background-color: #fff;
}
.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: #eaeaeb;
    color: #272727;
}
.select2-container--default .select2-selection--multiple {
    margin-bottom: 10px;
}
.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple {
    border-radius: 4px;
}
.select2-container--default.select2-container--focus .select2-selection--multiple {
    border-color: #f77750;
    border-width: 2px;
}
.select2-container--default .select2-selection--multiple {
    border-width: 2px;
}
.select2-container--open .select2-dropdown--below {
    
    border-radius: 6px;
    box-shadow: 0 0 10px rgba(0,0,0,0.5);

}
.select2-selection .select2-selection--multiple:after {
    content: 'hhghgh';
}


.select2-results__group:before {
  content: "";
  display: none;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">

    

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />

    

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>


</head>
<body>
    <div class="container">
        <div class="row">
        <h4>checkbox</h4>
            <select class="js-select2" multiple="multiple">
                <optgroup label="Group1" class="GROUP">
                <option value="O1" data-badge="">Option1</option>
                <option value="O2" data-badge="">Option2</option>
                <option value="O3" data-badge="">Option3</option>
            </optgroup>
            <optgroup label="Group2">
                <option value="O4" data-badge="">Option4</option>
                <option value="O5" data-badge="">Option5</option>
                <option value="O6" data-badge="">Option6</option>
                </optgroup>
            </select>

        </div>
    </div>

</body>
</html>