lundi 31 août 2020

How to show ticked checkboxes

I am creating dynamic checkboxes and then saving the ids of those in database which are checked. It being saved in the database however it does not show those checkboxes as ticked.

This is my table:

  <table>
                      <tr>
                              <td style="width: 5%;" >
                              </td>
                              <td class="description" align="centre" id="tdEAlist">
                              </td>
                      </tr>
                 </table>

Then in aspx I get this checkbox using

$('#tdEAlist').html(AJAX.getExtraData('EAlist'));

At class level:

 ArrayList ExtdataExisting = new ArrayList();
 ExtdataExisting.Add("EAlist");
 ExtdataExisting.Add(createCheckBox(getDataTableFromQuery("select id,value,null as checked 
 from ChecklistOptionSetup where type in('1');"), "chkEAlist_", ""));
 retAry.Add(ExtdataExisting);

and then finally in grid I show my checkboxes like this

 Html.Append("<td style=\"padding-left:8%\" id= 'tdEAlist' width='20%' class=\"GreyBorder\" ></td>");

for saving:

 for (int j = 0; j < AllCheckedIDs.Length; j++)
                            {
                                qry += "insert into AMLOptions(AmlAction,value,TransactionCode) 
 values(" + checkNull(AllCheckedIDs[j]) + ",'Y'," + checkNull(TransactionCode) + ");";                                       
                            }

How do I show ticked checkboxes against those who ids are saved in the database? For example I checked Low and high so their ids 1 and 3 are saved in database against column value which is showing 'Y'. I know I ma missing something really small. Kindly help.




Updating boolean value with cloud firestore in Vue

I'm new to both Vue and Firebase. So I'm trying to implement a very simple library app with both. However, the updating function only updates the value of the attribute 'read' once. What am I doing wrong?

This is the template and the function in App.vue :

<template>
  <div id="app">
    <Header />
    <AddBook v-on:add-book="addBook" />
    <Books v-bind:books="books" v-on:del-book="deleteBook" v-on:update-book="updateBook" />
  </div>
</template>
updateBook(id, book) {
  console.log(book);
  db.collection("books")
    .doc(id)
    .update({
      read: !book.read,
    })
    .then(() => {
      console.log("Book successfully updated!");
    })
    .catch((error) => {
      console.error("Error updating book: ", error);
    });
}

And I'm passing the data with $emit from Book.vue :

<template>
  <div class="book" v-bind:class="{ 'is-read': book.read }">
    <p></p>
    <p></p>
    <input
      type="checkbox"
      v-on:change="$emit('update-book',book.id, book)"
      v-bind:checked="book.read"
    />
    <button @click="$emit('del-book', book.id)">x</button>
  </div>
</template>

If anyone could help me I'd really appreciate it.




PHP : no return selected checkboxes

I am new to php code, this is my first one. Here I list the contents of a directory and list it with checkboxes. My final goal is to be able to make one or more selections and delete them. But I am unable to retrieve the value of the select boxes. My return value is empty. (no error message). Please, Can you point me on the right path? Thanks

My index.php

<head>
    <!-- JS -->
        <script type="text/javascript" src="./js.js"></script>
    <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="./css/css.css" />
</head>

<form>

    <fieldset>
    
        <br><legend>select files to delete :</legend> 

        <form method="POST" action="index.php">
                
            <?php
                
                
                
                    $directory = "./tmp";
                                                
                    $list = array_slice(scandir ($directory), 2);
                
            
                    
                    foreach ($list as $file) {
                    
                        $value= "./tmp/$file";
                        
                        if (is_file ($value)){ // files only
                            
                            echo "
                            <input type='checkbox' name='chk[]' value=$value>$file<br>
                            ";

                        }
                    }   

            ?>
            
            
        <br><input type="submit" name="button" value="DELETE FILES" />
                
        </form>

<!--  return selected checkboxes -->

        <h1>$_POST</h1>

        <?php
         if(isset($_POST["button"]))
         {
            if (isset($_POST['chk'])){
                var_dump($_POST);
            }
        }
        ?>
    
    </fieldset>
    

</form>



Setting Javascript to ignore an action on itself while still affecting other boxes (Beginner Javascript Coder)

I am creating a series of checkboxes in an interactive PDF, and I have added Javascript action to clear all other options once one is selected. Checkbox 1, once clicked, clears checkboxes 2 through 4.

I understand this is essentially a Radio button, but for the purpose of the PDF, the user needs to be able to unselect an option and to be able to clear all the options without adding a 'clear all' button.

The Javascript I'm adding is: this.resetForm(["name", "name1", "name2", "name3", "name4"]);

I'm wondering if there is additional code I could add, so the form ignores the reset action on itself?

With this, I could apply the Javascript to all the checkboxes at once instead of going in and adding the Javascript reset form to each individual checkbox.

Apologies if this question is really simple, I have little Javascript experience.

Thanks in advance, Marty




Remove the array value from CheckboxListTile in flutter

I am trying to have list of CheckboxListTile. I am getting the array of the checked value. I am adding the all the checked values arrays and set them to the list of text but the problem is I couldnot remove the value when unchecked. I have tried as follows:

My function to get checkValues from checkBox:

  onChecked(var items) {
    setState(() {
      myItems.addAll(items);
    });

    for (var i = 0; i < myItems.length; i++) {
      bool repeated = false;
      for (var j = 0; j < nonRepated.length; j++) {
        if (myItems[i] == nonRepated[j]) {
          repeated = true;
        }
      }
      if (!repeated) {
        nonRepated.add(myItems[i]);
      }
    }
    print(nonRepated);
  }

And I set the values in text as follows:

  for (int i = 0; i < nonRepated.length; i++) Text(nonRepated[i])

I have passed the function as follows:

 CheckboxWidget(cropsProduce[i].items[i].items[i].data,onChecked)
                                

My list of checkbox

  ListView(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        children: widget.values.keys.map((String key) {
          return new CheckboxListTile(
            title: new Text(key),
            value: widget.values[key],
            activeColor: Theme.of(context).primaryColor,
            checkColor: Colors.white,
            onChanged: (bool value) {
              setState(() {
                widget.values[key] = value;
              });
              setValues(widget.values[key]);
            },
          );
        }).toList(),
      );

     void setValues(bool myValue) {
    widget.values.forEach((key, myValue) {
      if (myValue == true) {
        if (tmpArray.contains(key) != widget.values.containsKey(key))
          tmpArray.add(key);

        widget._onChecked(allValues);
      } else if (myValue == false) {
        print("Else false");
        print(myValue);
        tmpArray.remove(key);

        widget._onChecked(allValues);
      }
    });
  }



How can I create multiple checkbox with total controllable checkbox button react.js with useRedux?

I am making a multiple select checkbox using React.js and useRedux react hook.

enter image description here

For default all is checked as true value. Either one or multiple place names is checked besides of all, all should be unchekced. (true -> false).

On the other hand, when all is checked, other names should be unchecked.

Here is the code :

// Data
const PLACE_TYPE_OPTIONS = [
  { name: "all", value: "all" },
  { name: "guest_house", value: "guest_house" },
  { name: "rental_house", value: "rental_house" },
  { name: "design_pension", value: "design_pension" },
  { name: "hanok_stay", value: "hanok_stay" },
  { name: "boutique_hotel", value: "boutique_hotel" },
  { name: "stone_stay", value: "stone_stay" }
];

// Checkbox Group
           <div className="tit">PLACES</div>
              <ul className="check_list">
                {
                  PLACE_TYPE_OPTIONS.map(option => (
                    <li>
                      <label className="check_skin">
                        <input type="checkbox" onChange={() => dispatch({ type: TYPE_STATE, payload: option.value })} checked={state.typeState[option.value]} />
                        <span>{option.value}</span>
                      </label>
                    </li>
                  ))
                }
              </ul>

// initialState
const initialState: IFindStayState = {
  typeState: {
    all: true,
    guest_house: false,
    rental_house: false,
    design_pension: false,
    hanok_stay: false,
    boutique_hotel: false,
    stone_stay: false
  }
};

// useReducer
const reducer = (state: IFindStayState, action: Action): IFindStayState => {
  switch (action.type) {
    case TYPE_STATE:
      return {
        typeState: {
          ...state.typeState,
          [action.payload]: !state.typeState[action.payload]
        }
      };
    default:
      return state;
  }
};

If I can use conditional inside return statement in reducer so I did it like below

    case TYPE_STATE:
      return {
        typeState: {
          ...(state.typeState["all"] && {
            all: true,
            guest_house: false,
            rental_house: false,
            design_pension: false,
            hanok_stay: false,
            boutique_hotel: false,
            stone_stay: false
          }),
          ...(state.typeState[action.payload] && {
            all: false,
            [action.payload]: !state.typeState[action.payload]
          })
        }
      };

Of course the code above is not going to work because all value stay the same all the time.

How can I interact all and other value? Can I make it work using conditional statement inside of reducer??

(I am trying to make it work not using input library like Formik)




dimanche 30 août 2020

display php array as dropdown checkbox

I've one array, which is output of some function and size of array is dynamic. So, I want to put all array element as drop-down with checkbox. Can anyone is here to help?




Trying to update state in my react app and then send a put request to the rails backend with checkboxes

I have a checklist. I want to check a box on the checklist and then have the react state update and then send a put request to my rails backend to have the checklist object saved in the backend. I am having several problems

  1. I am having trouble getting react to render the checkboxes as checked when the corresponding value is true and unchecked when the corresponding value is false

  2. my checkboxes will update the state (or at least create a pending update) when i check the boxes but do nothing when I uncheck them

  3. my data always gets sent to my backend as false for all checklist values even if some of them are checked

here is my checklist code

import React, { useState } from 'react' 
import checklist from '../reducers/checklist'

export default function Checklist(props) {
    const [completed_app, setCompleted_app] = useState(props.completed_app ? props.completed_app : false)
    const [edcon_call, setEdcon_call] = useState(props.edcon_call ? true : false)
    const [enrollment, setEnrollment] = useState(props.enrollment ? true : false)
    const [inform_team, setInform_team]  = useState(props.inform_team ? true : false)
    const [parent_call, setParent_call] = useState(props.parent_call ? true : false)
    const [parents, setParents] = useState(props.parents ? true : false)
    const [recieve_testing, setRecieve_testing] = useState(props.recieve_testing ? true : false)
    const [review_testing, setReview_testing] = useState(props.review_testing ? true : false)
    const [staffing, setStaffing] = useState(props.staffing ? true : false)
    const [steps_to_enroll, setSteps_to_enroll] = useState(props.steps_to_enroll ? true : false)
    const [submitted_docs, setSubmitted_docs] = useState(props.submitted_docs ? true : false)
    const [team_assigned, setTeam_assigned] = useState(props.team_assigned? true : false)
    const [telos_hq, setTelos_hq] = useState(props.telos_hq ? true : false)
    const [tour_scheduled, setTour_scheduled] = useState(props.tour_scheduled ? true : false)
    const [vetting, setVetting] = useState(props.vetting? true : false)
    const [w_therapist_call, setW_therapist_call] = useState(props.w_therapist_call ? true : false)
    
    const checklistObj = {
        completed_app,
        edcon_call,
        enrollment,
        inform_team,
        parent_call,
        parents,
        recieve_testing,
        review_testing,
        staffing,
        steps_to_enroll,
        submitted_docs,
        team_assigned,
        telos_hq,
        tour_scheduled,
        vetting,
        w_therapist_call,
    }

    const updateCheck = (item) => {
        switch(item){
            case 'recieve_testing':
                setRecieve_testing(!recieve_testing)
                break;
            case 'review_testing':
                setReview_testing(!review_testing)
                break;
            case 'edcon_call':
                setEdcon_call(!edcon_call)
                break;
            case 'w_therapist_call':
                setW_therapist_call(!w_therapist_call)
                break;
            case 'staffing':
                setStaffing(!staffing)
                break;
            case 'parent_call':
                setParent_call(!parent_call)
                break;
            case 'tour_scheduled':
                setTour_scheduled(!tour_scheduled)
                break;
            case 'steps_to_enroll':
                setSteps_to_enroll(!steps_to_enroll)
                break;
            case 'completed_app':
                setCompleted_app(!completed_app)
                break;
            case 'submitted_docs':
                setSubmitted_docs(!submitted_docs)
                break;
            case 'inform_team':
                setInform_team(!inform_team)
                break;
            case 'team_assigned':
                setTeam_assigned(!team_assigned)
                break;
            case 'telos_hq':
                setTelos_hq(!telos_hq)
                break;
            }
    }

    async function  updateChecklistUi(item, referral_id, id){
            await updateCheck(item)
            if (props.color === "orange" || props.color === "yellow"){
                if (
                    recieve_testing === true && 
                    review_testing === true && 
                    edcon_call === true &&
                    w_therapist_call === true &&
                    staffing === true
                    ) {setVetting(true)} 
            } else if (props.color === "green") {
                   if (
                    recieve_testing === true && 
                    review_testing === true && 
                    edcon_call === true &&
                    w_therapist_call === true
                   ) {setVetting(true)}     
            }
            if (
                parent_call === true && 
                tour_scheduled === true && 
                steps_to_enroll === true &&
                completed_app === true &&
                submitted_docs === true
                ){ setParents(true)}
            if (
                inform_team === true &&
                team_assigned === true &&
                telos_hq === true
            ){setEnrollment(true)}
                await props.setChecklist(checklistObj)
                console.log('beforeAxios:',checklistObj)
                await props.updateChecklist(referral_id, id, checklistObj)
    }

    return (
        <section>
            {console.log('props',props)}
            <h3><strong>Checklist</strong></h3>
            <h5>Vetting</h5>
            <input 
            type='checkbox' 
            name='recieve_testing' 
            checked={!!recieve_testing} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='recieve_testing'>Recieve testing</lable>
            <br/>
            <input 
            type='checkbox' 
            name='review_testing'
            checked={!!review_testing} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='review_testing'>Review testing</lable>
            <br/>
            <input 
            type='checkbox' 
            name='edcon_call'
            checked={!!edcon_call} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='ed_con_call'>Call with Education Consultant</lable>
            <br/>
            <input 
            type='checkbox' 
            name='w_therapist_call'
            checked={!!w_therapist_call} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='w_therapist_call'>Call with Wilderness Therapist</lable>
            <br/>
            {props.color == 'yellow' || props.color == 'orange' ?
                        <>
                        <input 
                        type='checkbox' 
                        name='staffing'
                        checked={!!staffing} 
                        onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
                        />
                        <lable for='staffing'>Staffing with team</lable>
                        <br/>
                        </> : 
                        null
            }
            <h5>Parents</h5>
            <input 
            type='checkbox' 
            name='parent_call'
            checked={!!parent_call} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='parent_call'>Call with Parents</lable>
            <br/>
            <input 
            type='checkbox' 
            name='tour_scheduled'
            checked={!!tour_scheduled} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='tour_scheduled'>Schedule Tour</lable>
            <br/>
            <input 
            type='checkbox' 
            name='steps_to_enroll'
            checked={!!steps_to_enroll} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='steps_to_enroll'>Steps to Enrollment Complete</lable>
            <br/>
            <input 
            type='checkbox' 
            name='completed_app'
            checked={!!completed_app} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='completed_app'>Application Completed</lable>
            <br/>
            <input 
            type='checkbox' 
            name='submitted_docs'
            checked={!!submitted_docs} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='submitted_docs'>Documents Submitted</lable>
            <br/>
            <h5>Enrollment Process</h5>
            <input 
            type='checkbox' 
            name='inform_team'
            checked={!!inform_team} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='inform_team'>Team Informed of Enrollment</lable>
            <br/>
            <input 
            type='checkbox' 
            name='team_assigned'
            checked={!!team_assigned} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='team_assigned'>Team Assigned</lable>
            <br/>
            <input 
            type='checkbox' 
            name='telos_hq'
            checked={!!telos_hq} 
            onChange={(e) => updateChecklistUi(e.target.name, props.referal_id, props.id)}
            />
            <lable for='telos_hq'>Loaded onto TelosHQ</lable>
        </section>
    )
}

here is referral where my checklist component is rendered:

import React, { useState, useEffect } from 'react';
import { Button } from '@material-ui/core';
import AddReferal from './AddReferal';
import { useHistory } from 'react-router';
import Checklist from './Checklist';
import Axios from 'axios';

export default function Referral(props) {
    const history = useHistory()
    const [editing, setEditing] = useState(false)
    const [checklist, setChecklist] = useState({})
    const { f_name, 
        l_name, 
        source, 
        ed_con, 
        therapist, 
        w_therapist, 
        created_at, 
        status, 
        color, 
        result,
        id 
    } = props.location.state.referral

    useEffect(()=> {
        Axios.get(`/api/referals/${id}/checklists`)
        .then(res => {
            console.log(res.data)
            setChecklist(res.data)
        })
        .catch(err => {
            console.log(err)
        })
    },[])

    const updateChecklist = (referralId, id, checklistObj) => {
        Axios.put(`/api/referals/${referralId}/checklists/${id}`, checklistObj)
        .then(res => {
            console.log(res.data)
            setChecklist(res.data)
        })
        .catch(err => {
            console.log(err.message)
        })
    }

    return (
        <div style={styles.page}>
            <div style={styles.sideBySide}>
                <div>
                    <h1><strong>{f_name} {l_name}</strong></h1>
                    <p>Source: {source} </p>
                    <p>Educational Consultant: {ed_con}</p>
                    <p>Wilderness Therapist: {w_therapist}</p>
                    <p>TelosU Therapist: {therapist}</p>
                    <p>Created at: {created_at}</p>
                    <Button onClick={() => setEditing(!editing)}>Edit</Button>
                    <Button onClick={() => props.deleteReferral(id, history)}>Delete</Button>
                </div>
                <Checklist 
                {...checklist}
                color={color} 
                setChecklist={setChecklist} 
                updateChecklist={updateChecklist}
                />
            </div>
            {editing && 
            <AddReferal  
            initF_name={f_name} 
            initL_name={l_name}
            initSource={source}
            initEd_con={ed_con}
            initTherapist={therapist}
            initW_therapist={w_therapist}
            initStatus={status}
            initColor={color}
            initResult={result} 
            editId = {id}/>}
        </div>
    )
}

const styles = {
    sideBySide: {
        display: 'flex',
        justifyContent:'space-between',
        alignItems: 'center',
    },
    page: {
        maxWidth:'95vw'
    }
}

Here is my checklist controller

class Api::ChecklistsController < ApplicationController
    before_action :set_checklist, only: [:update, :show]

    def index
        referal = Referal.find(params[:referal_id])
        render json: referal.checklist
    end 

    def show 
    end 

    def update
        @checklist.update(checklist_params)
        if @checklist.save
            render json: @checklist
        else
            render json: {errors: @checklist.errors, status: 422}
        end 
    end 

    private

    def set_checklist
        @checklist = Checklist.find(params[:id])
    end 

    def checklist_params
        params.require(:checklist).permit(
            :completed_app,
            :edcon_call,
            :enrollment,
            :inform_team,
            :parent_call,
            :parents,
            :recieve_testing,
            :review_testing,
            :staffing,
            :steps_to_enroll,
            :submitted_docs,
            :team_assigned,
            :telos_hq,
            :tour_scheduled,
            :vetting,
            :w_therapist_call
        )  
    end 
end

checklist is part of a has_one relationship with referrals so it is created in the referrals controller (i know referral is misspelled on the backend) with all values defaulted to false.

Any help would be much appreciated!




react.js handling multyple checkbox fields

I am working on a quiz application and would like to enable my users to go back and forth over the questions and see what they have already selected in the previous questions.

I am storing all of the data about the questions and the answers that they selected in the state. However, I am not able to render the selected checkboxes as they should be.

if I put a variable in the checked field just like the one below (checkbox) then all checkboxes within the question are affected and I only want to check just the selected ones. here is example code

https://codesandbox.io/s/confident-night-zyy2h?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";

const answersArray = ["answer1", "answer2", "answer3", "answer4"];
const selectedAnswers = ["answer1", "answer3"]


export default function App() {
  const [checkbox, setCheckbox] = useState(false);

  function handleCheckbox() {}

  return (
    <div className="App">
      <h1>question 1 - how to manipulate the checkboxes</h1>

      {answersArray.map((possibleAnswer, index) => (
                        <li key={[index, possibleAnswer]}>
                            <div>
                                <input
                                    name={[index, possibleAnswer]}
                                    type="checkbox"
                                    
                                    onChange={(event) => handleCheckbox(event, index)} 
                                    checked={checkbox}
                                  />
                                
                            </div>
                            <div>
                                <span>{possibleAnswer}</span>
                            </div>
                        </li>
                    )
                    )}
    </div>
  );
}

Any ideas on how to go about this problem? I would like to render answer 1 and 3 for example as selected and make sure my users can also unselect them and change them if they wanted.




Overridden CellPainting in DataGridView displays content only after cell loses focus

I have overridden the CellPainting in a WinForms DataGridView to display a specific image in a cell depending on various factors.

To give you some more details, in the CellPainting I am redrawing the content of a DataGricViewCheckBoxColumn; I want to display a green tick or red cross instead of the default black tick.

To draw the image I use:

e.Graphics.DrawImage(image, new PointF(centreX - offsetX, centreY - offsetY));

It works fine, but my green tick/red cross is only displayed after the cell loses focus. Is there a way to make it show as soon as I have clicked it, just like the standard checkbox does?

Thanks




CSS: Changing background color of parent label when the input checkbox is checked? [duplicate]

I have a html form with the following checkboxes:

<label><input type='checkbox' name='tag' value='1' /> Tag #1</label>
<label><input type='checkbox' name='tag' value='2' /> Tag #2</label>
<label><input type='checkbox' name='tag' value='3' /> Tag #4</label>

Those label's are styled like this:

label {
    display: inline-block;
    padding: 5px;
    background: #CCC;
    color: #fff;
    border-radius: 999em;
    -moz-border-radius: 999em;
    -webkit-border-radius: 999em;
    }

I found out how to change the checkbox-style itself using :checked - but I didn't manage to change the styling of the parenting label (I wand to change the label's background color from #CCC to something else, e.g. #FC0), when the checkbox is checked. If anyhow possible using only CSS and no JS. Is that possible?




React - Cannot toggle the checkbox if multi-select the group(with sandbox)

When I click the + button to expand the group and click the checkbox of group 1, it executes as expected.

But the problem is,
If I click the checkbox of group 1 first and then expand the group by clicking + button,
It shows all user clicked which is correct, if I clicked the checkbox of group 1 again,
the checkbox of group 1 become unchecked, but the checkboxes of users do not get unchecked.

Reproduce step: refresh the page > Click group 1 checkbox > click + to expand > click group 1 checkbox again > then you'll see user checkbox do not become unselected

enter image description here

SandBox Link below:
https://codesandbox.io/s/dazzling-antonelli-gl9rm




samedi 29 août 2020

React - what is the best way to set for checkbox checked field

In below code, I use a function this.isExist(data.id, "") to evaluate the checked value.
But sometimes click the checkbox of the item, it does not change from empty to ticked,
meanwhile the selected array does add the item.
Is it related to the checked prop of input?

state= {
  selected: [],
}
isExist = (id, group) => {
if(!this.props.selected){
  console.log("selected = null")
  return null;
}
// return this.props.selected.find(ele => ele.id == group + id);

return this.props.selected.some(item=> item.id == group + id);
};

return 
<div style=>
                      {this.state.groupMembersList[groupData.id] && this.state.groupMembersList[groupData.id].length > 0 ?
                        this.state.groupMembersList[groupData.id].map(data => (
                        <div key={data.id} className="popup-contact__item">
                          <label>
                            <input
                              id={data.id}
                              key={data.id}
                              className="checkbox"
                              type="checkbox"
                              group= {groupData.id}
                              onChange={async(e) => {await onSelect(e); await this.checkIfAllSelected();}}
            
                              name={(data.firstName&&data.lastName?(data.firstName + " " + data.lastName):data.firstName)+" ("+t("mobile") + ": " + (!data.mobileCountryCode || data.mobileCountryCode === "+852"?"":data.mobileCountryCode) +
                              data.mobileNumber+")"}
                              checked={this.isExist(data.id, "")}
                              disabled={ this.state.groupLoading }
                            />
                            {data.firstName&&data.lastName?(data.firstName + " " + data.lastName):data.firstName } ({t("mobile") + ": " + (!data.mobileCountryCode || data.mobileCountryCode === "+852"?"":data.mobileCountryCode) +
                            data.mobileNumber+")"}
                          </label>
                        </div>



How to make a checkbox with text datagridview column?

I want to make a custom column like the one illustrated in the attached photo in a datagridview control.example image




variable checkbox list in php or html [closed]

I want to make a checkbox list from a list of files whose content would be variable.

<form method='POST' action='fenetre.php'>

    <?php

        $list = array_slice(scandir("./repertoire/tmp"), 2);

        foreach($list as $fichier){
            
        <input type="checkbox" name="chk[]" value="Selection"> <?php echo $fichier;?><br>

                                    }
    ?>

    </br>
    <input type="submit" name="submit" Value="Soumettre">
 
</form>

But I get the error

Parse error: syntax error, unexpected '<', expecting end of file

Thanks for your help




Flutter: getting switch toggle values from dynamic form or why does state change rebuild differs

I have kind of a form where I can add cards, each having 5 textfields and 2 switches. I would like to use a method to build the switch code (and the textfield code, but that is working). However, the switches refuse to show their intended state. I saw couple of similar questions. However, most were solved with a list view listing all switched/checkboxes next to one another (I have multiple cards with multiple textfields and multiple switches, each). This was close, but I don't really understand the answer (within the comments)

Actually some answers come up with the same (I guess more or less same because mine isn't working) code storing the switch state in a bool list. When debugging I can see that the values are correctly stored in the list. However, the changed value is not rendered upon state change.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  var descrTECs = <TextEditingController>[];
  var fixedSCs = [true]; //storing the switch values
  var cards = <Card>[]; // storing the list of cards with forms

  SizedBox createTextField(String placeholderStr, double fieldWidth) {
    var tFieldController = TextEditingController();
    switch (placeholderStr) { //switching placeholder to assign text controller to correct controller list
      case "Description":
        descrTECs.add(tFieldController);
        break;
    }
    return SizedBox(width: fieldWidth, height: 25,
      child: CupertinoTextField(
          placeholder: placeholderStr,
          controller: tFieldController,
      ),
    );
  }

  SizedBox createSwitch(int pos) {
    return SizedBox(width: 50, height: 25,
        child: CupertinoSwitch(
          value: fixedSCs[pos],
          onChanged: (value) {
            setState(() => fixedSCs[pos] = value); // value is stored in fixedSCs but not rendered upon rebuild
          },
        )
    );
  }

  Card createCard() {
    return Card(
      child: Row(children: <Widget>[
        Text('#p${cards.length + 1}:'),
        Column(
          children: <Widget>[
            createSwitch(cards.length),
            createTextField("Description", 70.0),
          ],),
      ],),
    );
  }

  @override
  void initState() {
    super.initState();
    cards.add(createCard()); // first card created upon start
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      child: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder( // List Builder to show all cards
                itemCount: cards.length,
                itemBuilder: (BuildContext context, int index) {
                  return cards[index];
                },
              ),
            ),
            RaisedButton(
                child: Text('add new'),
                onPressed: () => setState(() {
                  fixedSCs.add(true); // bool element created to create next card
                  cards.add(createCard());}  // create next card
                ),
              ),
          ],
        ),
      ),);
  }
}

One thing I do not understand in general: Upon rebuild after a state change cards.length} should be my number of cards, let's say 3. And when it renders the 1st card, it passes the line Text("#p${cards.length + 1}"), so it should show #p3 and not #p1. What do I get wrong here?




How do I use a button to change the colour of a TextField in SwiftUI?

I am currently working on an app to create a shopping list.

The view is composed of a list of HStacks, which again is composed of a checkbox and a textfield. As of now, the button only checks/unchecks the checkbox.

However, i also want the button to change the transparancy of the following textfield.

This is my current code for each element in the list:

struct Vare: View {

@State var vare: String = ""
@State var checked = false

var body: some View {
    HStack {
        ZStack {
            Button(action: {
                self.checked.toggle()
            }) {
                Image("UnCheckbox")
                .resizable()
                .frame(width: 20, height: 20)
                .padding(.leading)
            }
            
            if checked {
                Image("Checkbox")
                .resizable()
                .frame(width: 20, height: 20)
                .padding(.leading)
                
            }
        }
       TextField("Neste vare...", text: $vare)
           .frame(maxWidth: .infinity)
    }
}

}




How to multiple checbox passing data to another activity and saving to Firebase

firstly I am sorry for my bad english...

I am new in Android and I have a register page include multiple checkboxes like reading book, playing an enstrument etc. In another activity, I save user's information in Firebase Realtime Database. But I can't passing the data of checkboxes to another page.

This is the Xml code of Checkboxes.

<CheckBox
                android:id="@+id/bisiklet_surmek_hobi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:background="@drawable/hobi_bisiklet_check_selector"
                android:button="@color/colorTransparent"
                android:fontFamily="@font/inter_bold"
                android:gravity="center_horizontal|center_vertical"
                android:letterSpacing="-0.03"
                android:shadowColor="#000000"
                android:shadowDy="3"
                android:shadowRadius="10"
                android:text="Bisiklet\nSürmek"
                android:textColor="@color/whiteColor" />

            <CheckBox
                android:id="@+id/satranc_hobi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginBottom="10dp"
                android:layout_toRightOf="@id/bisiklet_surmek_hobi"
                android:background="@drawable/hobi_satranc_check_selector"
                android:button="@null"
                android:fontFamily="@font/inter_bold"
                android:gravity="center_horizontal|center_vertical"
                android:letterSpacing="-0.03"
                android:shadowColor="#000000"
                android:shadowDy="3"
                android:shadowRadius="10"
                android:text="Satranç"
                android:textColor="@color/whiteColor" />

            <CheckBox
                android:id="@+id/enstruman_calmak_hobi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/satranc_hobi"
                android:layout_alignLeft="@id/satranc_hobi"
                android:layout_marginBottom="10dp"
                android:background="@drawable/hobi_enstruman_check_selector"
                android:button="@null"
                android:fontFamily="@font/inter_bold"
                android:gravity="center_horizontal|center_vertical"
                android:letterSpacing="-0.03"
                android:shadowColor="#000000"
                android:shadowDy="3"
                android:shadowRadius="10"
                android:text="Enstrüman\nÇalmak"
                android:textColor="@color/whiteColor" />

            <CheckBox
                android:id="@+id/cizim_yapmak_hobi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/bisiklet_surmek_hobi"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:background="@drawable/hobi_cizim_check_selector"
                android:button="@null"
                android:fontFamily="@font/inter_bold"
                android:gravity="center_horizontal|center_vertical"
                android:letterSpacing="-0.03"
                android:shadowColor="#000000"
                android:shadowDy="3"
                android:shadowRadius="10"
                android:text="Çizim Yapmak"
                android:textColor="@color/whiteColor" />

I defined the checkboxes in Hobby_Activity.

    bisiklet_surmek_hobi = findViewById(R.id.bisiklet_surmek_hobi);
    satranc_hobi = findViewById(R.id.satranc_hobi);
    enstruman_calmak_hobi = findViewById(R.id.enstruman_calmak_hobi);
    cizim_yapmak_hobi = findViewById(R.id.cizim_yapmak_hobi);
    kitap_okumak_hobi = findViewById(R.id.kitap_okumak_hobi);
    cosplay_hobi = findViewById(R.id.cosplay_hobi);
    muzik_dinlemek_hobi = findViewById(R.id.muzik_dinlemek_hobi);

And this is the Last_Activity that I saved the datas in database.I used Intent function page by page.

    comp_phoneNumber = getIntent().getStringExtra("userPhone");
    user_FirstName = getIntent().getStringExtra("user_FirstName");
    user_Gender = getIntent().getStringExtra("user_Gender");
    user_Birthdate = getIntent().getStringExtra("user_Birthdate");

    

This is the realtime database function. This function is working very well.

public void storeNewUserData() {
    rootNode = FirebaseDatabase.getInstance();
    reference = rootNode.getReference("Users");

    UserHelperClass addNewUser = new UserHelperClass(comp_phoneNumber, user_FirstName, user_Gender, user_Birthdate);
    reference.child(comp_phoneNumber).setValue(addNewUser);
}

But I can't passing data of the checkboxes in Last_Activity and I don't know how to save checkboxes to under the user phone number.

Thank you in advance for your help.




vendredi 28 août 2020

Kivy: size of layout doesn't update on app start

I am quite new to kivy and python, first question here... So, I want to hide the layout if the checkbox is empty manipulating size and opacity properties. It works as expected if you use checkboxes, but when app run, there is empty space. I tried to use constructor and schedule_once functions to change size to [0,0], and looks like size property changes, but still there an empty space you can see in screenshot.

P.S. I have a hypothesis, that the issue somehow related to kv file includes because I tried to create a minimalistic example for this question, and that... works fine, using just main.kv and main.py.

So, here the code I prepared to replicate the issue:

https://github.com/NobleFox/kivy-toggleLayout

Screenshot

Big thanks in advance!




How to get value Check and Uncheck checkbox use JQuery on array

Now im doing PHP Project combine with JQuery. I want to get value from checkbox both checked and unchecked on array. here is what i try

$(function() {
      $('.dealprice').on('input', function(){

        if($('.dealprice:checkbox:checked').prop('checked')){
            //CHECKED
            console.log("Checked");
            const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
            console.log(getPrice);
        }else{
            //UNCHECKED
            console.log("Uncheck");
            const getPrice = $(this).closest("tr").find('input[name=itemprice]').val();
            console.log(getPrice); 
        }
        
    });
 });

i make a sample on this site. https://repl.it/@ferdinandgush/get-value-checkbox please click "RUN" bottom on the top to able test it.

the problem is, when the checkbox checked more then 1 and when i want to uncheck 1 of it. it still return value "True" not "false".

what i want it. each of checkbox can return value wherever i checked and uncheck it.

checked return consolo.log('true');

unchecked return consolo.log('false');

please help




jeudi 27 août 2020

Check boxes values returned and added to string

I am trying to take a row of checkboxes in a table and for each TD in the table it needs to check if the checkbox is ticked, is so it is a 1 and else its 0. I need a for loop where I will be able to loop over each td, determin if it is checked and if so add a 1 to a binary string or else add a 0 to the binary string.

This should end with each tr having its own unique binary string from the checkboxes that have or have not been ticked. I will also want to set up each tr with its own unique ID.

The below code is what I have so far but am presumming I am going in the wrong direction.

Any help appreciated. Thanks

[ { ID: 000, binary: 0101010101 }  ]
function generate(){


$("#actionTable>tbody").children("tr").each(function(i, rowitem){
    $(rowitem).children("td").each(function(index, item){
        if (index == 0){
            var amid = $(item).data("amid");
        }

        else {
            //Handle checkbox
            var checked = $(item.firstChild).prop('checked')
        }
    });
});

}




How to maintain the old input value in checkbox after validating by an update request using laravel?

when i open the edit page it should have the value from the database and when i change the value and if in case validaton fails, i need the value to persist. This is the code :

<input type="checkbox" id="show_in_website" name="show_in_website"  @if($data->show_in_website=='1') checked @endif>Show in Website
       



How to change the text of an Label tag when a checkbox is unchecked

I can’t change the text of my label when I uncheck my checkbox.

Thanks in advance for your help.

    var checkBox_fruit = document.getElementById("fruit");
    var label_fruit = document.getElementById("label_fruits");

    checkBox_fruit.addEventListener('change', function () {
        if (this.checked) {
            // Checkbox is checked..

           label_fruit.innerHTML = " fruits 1"; ////// its that who works

        } else {
            // Checkbox is not checked..

           label_fruit.innerHTML = " fruits 2"; ////// its that who not works

        }



Datagrid Checkbox in UWP

I am struggling to find a working example of a utilised checkbox for my datagrid in UWP. I would like to use my check box -> press a button -> do X.

I dont suppose any of you could either give me an example of the process or point me to a documented example? Thanks




How to control checkbox checked attribute from different checkbox?

I see an issue that I can't fix it properly. When I click the checkbox any item among 9 items the groupSelect function not getting unchecked or checked properly. I have tried to remove the attribute of the checkbox items but still not execute the groupSelect function checkbox. whenever I try to checked or unchecked the item before "Racial or Ethnic Group " checkbox then I see the "Racial or Ethnic Group " checkbox not execute properly. Please see the snippet,

function groupSelect(val) {
  let checkInput = $(val).parent().next().find('input[type="checkbox"]')
  if (val.checked == true) {
    $(() => {
      checkInput.attr('checked', 'true')
    })
  } else {
    checkInput.removeAttr('checked');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-wrapper pb-3">
  <div class="group_title">
    <strong>Racial or Ethnic Group</strong>
    <input title="Select all items in the group" type="checkbox" onclick="groupSelect(this)" style="cursor: pointer;" name="">
  </div>
  <div class="row no-gutters pt-2 px-3">
    <div class="col-12 col-sm-6 col-md-4">
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input"
                                           name="" id="" value="checkedValue">
                                          American Indian/Alaskan
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          Hispanic/Latino
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          Hispanic/Latino
                                        </label>
      </div>
    </div>
    <div class="col-12 col-sm-6 col-md-4">
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          Asian/Pacific Islander
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          White/Caucasian
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          White/Caucasian
                                        </label>
      </div>
    </div>
    <div class="col-12 col-sm-6 col-md-4">
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                          Black/African American
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                        Other
                                        </label>
      </div>
      <div class="form-check">
        <label class="form-check-label" style="cursor: pointer">
                                          <input type="checkbox" class="form-check-input" name="" id="" value="checkedValue">
                                        Other
                                        </label>
      </div>
    </div>
  </div>
</div>



I want to get result of each checkbox in PHP POST by ajax on real time checkbox selection

I want to get result of each checkbox in PHP POST by ajax on real time checkbox selection

function showValues() {
  var str = $("form").serialize();
  $("#results").text(str);
}
$("input[type='checkbox']").on("click", showValues);
showValues();
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<form>
  <input type="checkbox" name="check" value="check1" id="ch1">
  <label for="ch1">check1</label>
  <input type="checkbox" name="check" value="check2" id="ch2">
  <label for="ch2">check2</label>
  <input type="checkbox" name="check" value="check3" id="ch3">
  <label for="ch2">check3</label>
  <input type="checkbox" name="check" value="check4" id="ch4">
  <label for="ch2">check4</label>
  <input type="checkbox" name="check" value="check5" id="ch5">
  <label for="ch2">check5</label>
</form>

<tt id="results"></tt>



close checkbox hamburger menu, when clicked outside without javascript/jquery possibly

i have hamburger menu which i took from here. https://codepen.io/erikterwan/pen/EVzeRP it is using only css by using a checkbox to expand and collapse the menu.

so what i want is when i click outside the menu (anywhere on the page), the menu should collapse. can someone help me.

this is the html code

<nav role="navigation">
  <div id="menuToggle">

    <input type="checkbox" />
    
    <span></span>
    <span></span>
    <span></span>
    
    <ul id="menu">
      <a href="#"><li>Home</li></a>
      <a href="#"><li>About</li></a>
      <a href="#"><li>Info</li></a>
      <a href="#"><li>Contact</li></a>
      <a href="https://erikterwan.com/" target="_blank"><li>Show me more</li></a>
    </ul>
  </div>
</nav>

this is the css code


body
{
  margin: 0;
  padding: 0;
  
  background: #232323;
  color: #cdcdcd;
  font-family: "Avenir Next", "Avenir", sans-serif;
}

#menuToggle
{
  display: block;
  position: relative;
  top: 50px;
  left: 50px;
  
  z-index: 1;
  
  -webkit-user-select: none;
  user-select: none;
}

#menuToggle a
{
  text-decoration: none;
  color: #232323;
  
  transition: color 0.3s ease;
}

#menuToggle a:hover
{
  color: tomato;
}


#menuToggle input
{
  display: block;
  width: 40px;
  height: 32px;
  position: absolute;
  top: -7px;
  left: -5px;
  
  cursor: pointer;
  
  opacity: 0; 
  z-index: 2; 
  
  -webkit-touch-callout: none;
}

#menuToggle span
{
  display: block;
  width: 33px;
  height: 4px;
  margin-bottom: 5px;
  position: relative;
  
  background: #cdcdcd;
  border-radius: 3px;
  
  z-index: 1;
  
  transform-origin: 4px 0px;
  
  transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
              background 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
              opacity 0.55s ease;
}

#menuToggle span:first-child
{
  transform-origin: 0% 0%;
}

#menuToggle span:nth-last-child(2)
{
  transform-origin: 0% 100%;
}

#menuToggle input:checked ~ span
{
  opacity: 1;
  transform: rotate(45deg) translate(-2px, -1px);
  background: #232323;
}

#menuToggle input:checked ~ span:nth-last-child(3)
{
  opacity: 0;
  transform: rotate(0deg) scale(0.2, 0.2);
}

#menuToggle input:checked ~ span:nth-last-child(2)
{
  transform: rotate(-45deg) translate(0, -1px);
}

#menu
{
  position: absolute;
  width: 300px;
  margin: -100px 0 0 -50px;
  padding: 50px;
  padding-top: 125px;
  
  background: #ededed;
  list-style-type: none;
  -webkit-font-smoothing: antialiased;

  
  transform-origin: 0% 0%;
  transform: translate(-100%, 0);
  
  transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0);
}

#menu li
{
  padding: 10px 0;
  font-size: 22px;
}

#menuToggle input:checked ~ ul
{
  transform: none;
}



mercredi 26 août 2020

How can we get checkboxes which are checked

<?php 
session_start();
require  'conn.php';
global $conn;

if(isset($_POST['test'])){  
  foreach($_POST['test'] as $key => $val){
    mysqli_set_charset($conn,"utf8");    
     $sql = "SELECT * FROM Jautajumi_Prof where TEMA = ? ";
     $stmt = mysqli_stmt_init($conn); 

     if(!mysqli_stmt_prepare($stmt, $sql)){
      header ('location: test.php?error');
      exit();
    
      }else{
        mysqli_stmt_bind_param($stmt, "s", $val);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
      }  
     
      while ($row = mysqli_fetch_assoc($result)){           
          echo "         
          <h4>".$row["JAUTAJUMS"]."</h4>
          <input type='checkbox' name='check_list[]' value='".$row["ATBILDE_A"]."' >            
          <label>".$row["ATBILDE_A"]."</label>
          <input type='checkbox' name='check_list[]' value='".$row["ATBILDE_B"]."'>            
          <label>".$row["ATBILDE_B"]."</label>
          <input type='checkbox' name='check_list[]' value='".$row["ATBILDE_C"]."'>            
          <label>".$row["ATBILDE_C"]."</label>
          <input type='checkbox' name='check_list[]' value='".$row["ATBILDE_D"]."'>           
          <label>".$row["ATBILDE_D"]."</label>              
          ";             
      } 
     
  }
}

?>
 <div class="delete">
        <form method="post" action="answer.inc.php">
            <input name="delete" type="submit" id="delete" value="DELETE">
        </form>
    </div>
<?php 



?>

I am trying to make a web page for students and my self where can i
To choose a topic what they like and they will see a question which needs to ba answered. In my code I get the answers from the SQL but I need them to store somewhere and I made like a second file where I want to trie to save or event get to screen but it won't show it just submits for me.

<?php 
if (empty($_POST['delete'])){
  foreach($_POST['check_list'] as $item){
    echo $item;
  }
}

?>



mardi 25 août 2020

How can I save CheckBox state from RecyclerView?

I am using a RecyclerView and an adapter to display the data of an array of Event objects. In RecyclerView, I use a CheckBox for one of the object's parameters. How can I save it? For the rest I use SharedPreferences, but here I don't know how to apply it in my Activity.

Here's my class Event:

public class Event implements Serializable {
public String Name;
public Long Date; 
public String Comment;
public String Type;
public String Notify;
public Boolean IsComplete;
public Boolean IsImportant;

Event()
{
    Name = "Событие";
    Date = MaterialDatePicker.todayInUtcMilliseconds();
    Comment = "Comment";
    Type = "Material";
    Notify = "Не напоминать";
    IsComplete = false;
    IsImportant = false;
}

Event(String name, Long date, String comment, String type, String notify, Boolean iscomplete, Boolean isimportant)
{
    Name = name;
    Date = date;
    Comment = comment;
    Type = type;
    Notify = notify;
    IsComplete = iscomplete;
    IsImportant = isimportant;
}

public String getName() {
    return Name;
}

public Long getDate() {
    return Date;
}

public String getComment() {
    return Comment;
}

public String getType() {
    return Type;
}

public String getNotify() {
    return Notify;
}

public Boolean getComplete() {
    return IsComplete;
}

public Boolean getImportant() {
    return IsImportant;
}

}

And my Recycler View and Adapter:

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private ArrayList<Event> mEventList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
    void onItemClick(int position);
}



public void setOnItemClickListener(OnItemClickListener listener){
    mListener = listener;
}

public static class EventViewHolder extends RecyclerView.ViewHolder{
   public TextView TVtitle;
   public TextView TVcomment;
   public CheckBox CBimportance;



   public EventViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
       super(itemView);
       TVtitle = itemView.findViewById(R.id.tv1);
       TVcomment = itemView.findViewById(R.id.tv2);
       CBimportance = itemView.findViewById(R.id.iconImportant);

       itemView.setOnClickListener(new View.OnClickListener(){

           @Override
           public void onClick(View view) {
                if (listener != null){
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION){
                        listener.onItemClick(position);
                    }
                }
           }
       });


   }

}
public EventAdapter(ArrayList<Event> listEvent){


    mEventList = listEvent;}

@NonNull
@Override
public EventViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
   View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
   EventViewHolder evh = new EventViewHolder(v, mListener);
   return evh;
}

@Override
public void onBindViewHolder(@NonNull EventViewHolder holder, final int position) {
    final Event item = mEventList.get(position);

    holder.TVtitle.setText(item.getName());
    holder.TVcomment.setText(item.getComment());

    holder.CBimportance.setOnCheckedChangeListener(null);

    holder.CBimportance.setChecked(item.getImportant());

    holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            item.IsImportant = b;
            if (b){
                Log.d(TAG, String.valueOf(position) + " IMPORTANT");
            }
            else{
                Log.d(TAG, String.valueOf(position) + " NON IMPORTANT");
            }
        }
    });

}

@Override
public int getItemCount() {
    return mEventList.size();
}

}

For example, for ItemClick and changes saving in my Activity I use onItemClick:

adapterEvent.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            eventsProcess.remove(position);
            adapterEvent.notifyItemRemoved(position);
            write(getContext(), eventsProcess, PROCESSED_EVENTS);
        }
    });
public static void write(Context context, ArrayList<Event> events, String Key)
{
    Gson gson = new Gson();
    String jsonString = gson.toJson(events);
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(Key, jsonString);
    editor.apply();
}



PDF scripting - Can I check multiple checkboxes based on their value instead based on their name?

I just recently started with JS and PDF scripting, in particular, so please excuse me if this is maybe a rather basic question.

I would like to add something like a bar rating to my PDFs. I have a number of checkboxes (number varies between 5 and 15), and I would like to check all checkboxes left of an mouse up event. When a checkbox is checked already, I would like to uncheck all checkboxes right of this event.

I have managed to achived that already using uniquely named checkboxes that follow a specific naming convention (xx-1, xx-2, xx-3 etc.) Please note, this is for a rating of 1 to 5, hence the d < 6 in the loop. Still working on a way to recognize the number of boxes beforehand.

How it looks

function bar(){
var [dName, dValue] = event.target.name.split("-");

if (event.target.value === "Yes") {
  for (d = 1; d < dValue; d++) {
    this.getField(dName + '-' + d.toString()).value = "Yes";
  }
  
} else if(event.target.value === "Off" && dValue == 1 ){
    for (d = dValue; d < 6; d++){
        this.getField(dName + '-' + d.toString()).value = "Off";
    }
  
} else if(event.target.value === "Off"){
    for (d = dValue; d < 6; d++){
        this.getField(dName + '-' + d.toString()).value = "Off";
    }   
    this.getField(dName + '-' + dValue).value = "Yes";
}
}

My question is now: Can achive this using checkboxes (or similar) that share the same name but have different values? When I set it up, selecting a checkbox automatically deselects all other checkboxes like a radio button? Thinking ahead, if that is not possible, how would I use the bar information (dValue) outside the function in other fields?

Thanks for your help.




How to return multiple values from checkbox from a form to populate a table?

.html

<tr *ngFor="let item of itemList; let i=index">
    <td><input type="checkbox" name="item"              
        [(ngModel)]="item.checked" ></td>
    <td ></td>
    <td ></td>
    <td>    
        <a class="btn text-danger"><i class="fa fa-trash fa-lg"></i></a>
    </td>
</tr>

.ts

 ngOnInit(): void {
    this.itemService.getItemList().then(res => this.itemList = res as Item[]);
    this.formData = {
      OrderItemID: null,
      OrderID: this.data.OrderID,
      ItemID: 0,
      ItemName: '',
      Quantity: 0
      }
  }

onSubmit(form: NgForm){
    console.log(form.value);
}

So this component is part of a pop up dialog which is used to select one/multiple items from a checkbox in a table in a form. How do I return the multiple checked items into the main table (not in this component)? Currently it is returning a array of itemnames and whether they are checked or not. i.e. {Apple: undefined, Banana: undefined, Orange: true, Pear: true, …} How do I return the form data information (collection of items) such that it can populate the table in the main component?




lundi 24 août 2020

How to wrap checkbox widget with ValueListenableBuilder widget?

Checkbox( value: datas[i]["check"], onChanged: (bool newValue) => setState((){ Array data in looping datas[i]["check"] = !datas[i]["check"]; }), ),




Gravity Forms Alphabetic Order Dropdown and Checkboxes field after WPML translation

I am using Gravity Forms with WPML. I have some Dropdown and Checkboxes Fields. In English Dropdown and Checkboxes are in alphabetic order. All ok. But in my translation form, the system keeps the English order not the translation order. I would like to have a snippet that force Dropdown and Checkboxes fields to be in alphabetic order, no matter the language. I try to use the code below in my function.php without success. If someone could help it will make my day.

    add_filter("gform_pre_render_39", "sort_categories");
    function sort_categories($form){
    foreach($form["fields"] as &$field){
    if($field->id == 1)
        usort($field["choices"], "sort_numerically");
    }
    return $form;
    }
    function sort_numerically($a, $b){
    return floatval($a["text"]) > floatval($b["text"]);
    }

My ID form is 39 My ID Dropdown field is 1

Thank you for your help




read from multiple checkbox appearing in different divs with same value

i have written bootstrap code for checkboxes with label appear side by side based on screen size they are divided into different divs. when i try to upload the values of checked box into database using php and mysql im getting error that foreach isnt passed an array and when i checked the array has only the last checked item and not the items checked before them

<div class="form-row">
                <div class="col-6 col-sm-3">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="features[]" value="wifi"><label class="form-check-label" for="wifi">wifi</label></div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="features[]" value="hotwater"><label class="form-check-label" for="hotwater">Hot Water</label></div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="features[]" value="ac"><label class="form-check-label" for="ac">A.C</label></div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="form-check"><input class="form-check-input" type="checkbox" name="features[]" value="food" style="background-color: #ffffff;"><label class="form-check-label" for="food">Food</label></div>
                </div>
            </div>

and php code is $features = $_POST['features'];

$feat="";
foreach($features as $feat1){
    //write if condition for inserting icons into database if $feat1==wifi{$feat=<i>fas fa wifi wifi</i>}
    $feat.=$feat1.",";
}

when i try to read $features it only has the last feature. how can i get all the checked values? thanks in advance




Two values in one checkbox with react

Can I have two values in checkbox. Normally if I assign single value to checkbox, whenever I check or uncheck this checkbox it return me value, but I want this behavior only if I check the value(eventually alternative behavior). I tried this way, but it didn't work

<input type="checkbox" name="path" id="path" defaultChecked={true} 
       value={ this.checked ?userData.image : ''} onChange={onChangeText}/>

Ofcourse I can do it in onChange function, but I want to find more simple and 'aesthetic' way, without

getElementById or e.target.name== ? something() : somethingElse()

And I want to do it in React.




How do I make a string from javascript appear in the html when certain checkboxes are clicked?

So i want too start off by saying I am very new at web development, specifically javascript. I'm trying to build a simple program where you check certain items from a list of certain ingredients from a video game, and you are then told which recipes you can make. I am struggling with getting the text to appear in the html when a box is checked.

This is my html for one of the ingredients that make a recipe from just the one item:

<div>
    <input type="checkbox" id="egg" name="egg">
  <label for="egg">Egg</label>
    </div>

This is the javascript I have trying to make the recipe appear under the checkboxes in a paragraph with the id being "make":

if (document.getElementById("egg").checked === true) {
    document.getElementById("make").innerHTML = "You can make a fried egg with egg!";
}



Checkbox: checkbox select all and unselect not effect on all

I'm trying to do a button to check and uncheck all boxes using react.But for some reason, 'Select All' is only selecting three of them, while 'Unselect All' is only unselecting those three and selecting the rest two.

My code is as below:

<button type='button' className='btnSelectAll' onClick={this.selectAllOrNone}>Select All</button>

this.selectAllOrNone = () => {
            let events = document.getElementsByClassName('toDoList_checkbox')
            let btnSelectAll = document.getElementsByClassName('btnSelectAll')[0]
            console.log(events)

            for (let i = 0; i < events.length; i++) {
                if (btnSelectAll.innerHTML === 'Select All') {
                    events[i].checked = true
                    btnSelectAll.innerHTML = 'Unselect All'
                }
                else if (btnSelectAll.innerHTML === 'Unselect All') {
                    events[i].checked = false
                    btnSelectAll.innerHTML = 'Select All'
                }

                console.log('btnSelectAll')
            }
        }

Anyone can suggest what the problem is?enter image description here

enter image description here enter image description here




Add checkboxes to Semantic UI's dropdown

I'm using Semantic UI's dropdown for a table.

The component is this:

import React from 'react';
import { Dropdown } from 'semantic-ui-react';

import './Dropdown.styles.scss';

export default ({ placeholder, options, onChange, name, className }) => (
  <Dropdown
    className={className}
    name={name}
    placeholder={placeholder}
    search
    selection
    options={options}
    onChange={onChange}
    clearable
    selectOnBlur={false}
  />
);

and it's used in another component:

const cityOptions = [ // the existing options
      { text: 'Paris', value: 'Paris' },
      { text: 'London', value: 'London' },
     ...
    ];

  searchHandlerCity = (event, data) => { // the method that filter the cities
    const { getCompanies } = this.props; 
    getCompanies({
      name: this.props.query.name,
      city: data.value,
    });
  }; 

    <Dropdown // the dropdown with the data
      className="hello-dropdown"
      placeholder="City"
      onChange={this.searchHandlerCity}
      options={cityOptions}
    />

enter image description here

I was wondering if it's possible to modify it, instead of selecting only one from the dropdown to have a chechbox near each line and being able to click on them which will also provide multiselect option.

The Checkbox from Semantic UI doesn't tell too much if this is possible.




Android Kotlin Can we put combination of text and image icon to the checkbox?

Made toppings checkboxes with only text, wonder can I add a small image to it.

<CheckBox
        android:id="@+id/checkWhippedCream"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:paddingStart="24dp"
        android:paddingEnd="24dp"
        android:text="@string/whipped_cream"
        android:textSize="16sp" />



Javascript (extjs) : check only one checkbox from two

The application I am working on is based on ExtJS, and what I would like to do is to allow the use to check only one checkbox.

The thing is that my application is very complex, and I don't really know a lot on ExtJS. The checkbox is initialized in a class viewport.js like this :

Ext.define('Viewport', {
    extend : 'Ext.container.Viewport',
    require : ['A','B'],
    frame : true,
    layout : 'fit',
    items : [{
                xtype : 'container',
                layout : 'hbox',
                margins : "a b c d",
                items : [{
                    margins : "0 0 5 35",
                    name : 'box1',
                    inputValue : true,
                    xtype : 'checkbox',
                    id : 'box1-box-id',
                    boxLabel : "BOX 1"
                }
                ,{
                    margins : "0 0 5 35",
                    name : 'box2',
                    inputValue : true,
                    xtype : 'checkbox',
                    id : 'box2-box-id',
                    boxLabel : "BOX 2"
                }]
            }
})

I don't know how to modify this code to have the user checking only one of these checkboxes. Do I have to add a function in this class?




Checkbox Two Way Data Binding, Angular version 9.1.12

my job is to do the following functionality. I have 3 checkboxes and after selecting one I want the other two to also be selected.

I use a ready-made component to create the checkbox.

<form [formGroup]="data" name="name" >
  <div class="form-group">
    <div class="form__element">
      <nb-checkbox name="groupname" value="Check All" label="Check All" formControlName="isAgree" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}"></nb-checkbox>
    </div>
  </div>

  <div class="features__box">
    <section class="agreements">
          <ul class="features__list">
        <li class="features__item" *ngFor="let agreement of data.agreements.value">
          <div class="form__element">
            <nb-checkbox name="groupname" value= label= [checked]="myVar2" (change)="myVar2 = !myVar2"></nb-checkbox>
          </div>
        </li>
      </ul>
    </section>
    <section class="statements">
          <ul class="features__list">
        <li class="features__item" *ngFor="let statement of data.statements.value">
          <div class="form__element">
            <nb-checkbox name="groupname" value= label= [checked]="myVar2" (change)="myVar2 = !myVar2"></nb-checkbox>
          </div>
        </li>
      </ul>
    </section>
  </div>
</form>

I added [(ngModel)] =" myVar2 "[ngModelOptions] =" {standalone: true} " to my main checkbox, and I added [checked] =" myVar2 "(change) =" myVar2 =! myVar2 to my next checkbox. In the file.component.ts file I addedmyVar2: boolean = false;

However, the above solution does not work. I get the following errors in the console

    
    ERROR in src/app/file.component.html:64:66 - error NG8002: Can't bind to 'ngModelOptions' since
it isn't a known property of 'nb-checkbox'.
    1. If 'nb-checkbox' is an Angular component and it has 'ngModelOptions' input, then verify that it is part of this module.
    2. If 'nb-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
    3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
    
    64                   formControlName="isAgree" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}"></nb-checkbox>
                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
      src/app/file.component.ts:14:16
        14   templateUrl: './file.component.html',
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Error occurs in the template of component CeidgPositiveComponent.
    src/app/file.component.html:94:121 - error NG8002: Can't bind to 'checked' since it isn't a known property of 'nb-checkbox'.
    1. If 'nb-checkbox' is an Angular component and it has 'checked' input, then verify that it is part of this module.
    2. If 'nb-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
    3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
    
    94                     <nb-checkbox name="groupname" value= label= [checked]="myVar2" (change)="myVar2 = !myVar2"></nb-checkbox>
                                                                                                                               ~~~~~~~~~~~~~~~~~~
    
      src/app/file.component.ts:14:16
        14   templateUrl: './file.component.html',
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Error occurs in the template of component File.

I have imported modules import {FormsModule, ReactiveFormsModule} from '@ angular / forms'; import {NgxsModule} from '@ ngxs / store';

Does anyone know how to solve this problem?




dimanche 23 août 2020

toggle input field editable

I would like to make form fields editable only after clicking a button, without Javascript. In the first state (readonly) I wanted to make the frame invisible and set the pointer events to "none". The button is supposed to be a checkbox, but there is no effect on the input fields, unlike the test frame below.

label.toggle {color:white; background: darkred;padding: 0.1rem .3rem;border-radius: 0.5rem;}
.visually-hidden {position: absolute;left: -100vw;}

.toggle_edit {color:black;   border:1px solid #FFFFFF;}
#toggle:checked ~ .toggle_edit {color:darkred; border:1px solid #000000;}
                  input.toggle_edit {color:black; border:1px solid #FFFFFF;}
#toggle:checked ~ input.toggle_edit {color:darkred;  border:1px solid #000000; pointer-events: none;}
<div> <!-- toggle -->
  <label class="toggle" for="toggle">bearbeiten</label><input type="checkbox" id="toggle" class="visually-hidden">
  <table>
    <form action="functions/edit.php" method="post" target="editframe"> 
      <tr>
        <th>Name</th>
        <td><input type="text" class="toggle_edit" name="justus" value="Justus" size="30" maxlength="50" ></td>
      </tr> 
      <input type="Submit" name="absenden" value="absenden"></form>
  </table>
  <div class="toggle_edit">Testframe</div> 
</div> <!-- toggle -->



What is the actual difference in between Radio button and Checkbox in HTML form

As,we know the difference between Radio button and Checkbox is that it is used to select the option. As Radio button is used to select only option, where as checkbox is used to select the multiple option. but Here what is the actual Difference in between this?




Javafx checkbox styleclass changes box disappear

Checkbox will disappear if change style class only. I was changing my style class when I clicked checkbox. But only the letters of checkbox changed and the box disappeared. The Scene builder I'm using doesn't look like that, but it's like this when you import it into java project.

here my settingsUiController code.

@FXML
private Pane settings_bg;

@FXML
private CheckBox settings_darkThemeCheckBox;

public void changeDarkTheme(boolean darkTheme) {
    if(darkTheme == true) {
        //settings ui
        settings_bg.getStyleClass().clear();
        settings_bg.getStyleClass().add("dark_bg");

        settings_darkThemeCheckBox.getStyleClass().clear();
        settings_darkThemeCheckBox.getStyleClass().add("dark_checkBox");
    }
}

and here my css code.

.light_bg {
    -fx-background-color: #FFFFFF;
}

.light_checkBox {
    -fx-text-fill: #000000;
}

.light_checkBox .box {
    -fx-background-radius: 0;
    -fx-background-color: #C8C8C8;
}

.light_checkBox .box:hover {
    -fx-background-color: #B4B4B4;
}

.light_checkBox .box:pressed {
    -fx-background-color: #A0A0A0;
}

.dark_bg {
    -fx-background-color: #353535;
}

.dark_checkBox {
    -fx-text-fill: #FFFFFF;
}

.dark_checkBox .box {
    -fx-background-radius: 0;
    -fx-background-color: #252525;
}

.dark_checkBox .box:hover {
    -fx-background-color: #202020;
}

.dark_checkBox .box:pressed {
    -fx-background-color: #151515;
}

my fxml code

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.layout.Pane?>

<Pane fx:id="settings_bg" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" 
minWidth="-Infinity" prefHeight="400.0" prefWidth="427.0" styleClass="light_bg" 
stylesheets="@mainStyle.css" xmlns="http://javafx.com/javafx/8.0.171" 
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.kerenic.javafxtest.settingsUiController">
   <children>
      <CheckBox fx:id="settings_darkThemeCheckBox" layoutX="168.0" layoutY="192.0" 
      mnemonicParsing="false" onAction="#checkBoxes" styleClass="light_checkBox" 
      stylesheets="@mainStyle.css" text="Dark Theme" />
   </children>
</Pane>

before image

after image




samedi 22 août 2020

Google Apps Script onEdit clear/change cells in another sheet based on a lookup [closed]

I have a Spreadsheet that is tracking updates to knowledge base articles.

I wish to create an onEdit function where a checkbox being ticked in Sheet 2 (P15) looks up the article title from that row (C15) in column A of Sheet 1 and clears column H (Notes on update) and changes column G (Article status) to 'up to date'.

enter image description here

enter image description here

I have no experience writing Apps Script and have spent hours without much luck making any progress on the script! I would be very appreciative of any assistance you can offer.

Spreadsheet here: https://docs.google.com/spreadsheets/d/1MC0yZr_RgPmwunaiWF9eHZldY-8_ZdWnkIblNsPeFXc/edit?usp=sharing




Send true or false to database wether checkbox is checked or not

i got an issue regarding checkboxes with nedb. I want to send true or false if the checkbox is checked or not to the database i cannot solve this issue. i am working with node.js and nedb. please help!

client js eventlistener:

var taskDone = document.querySelectorAll('.taskDone');


taskDone.forEach(btn => {
     btn.addEventListener('click', (e) => {
        var done = e.target.attributes[1].value;

        let id = e.target.getAttribute('data-id');
        let isDone = document.querySelector(`input[data-id=${id}]`).value;

        console.log(isDone + "isdone")
        if ($(taskDone).is(':checked')) {
            $('.text').addClass('line-through')
            console.log("trues")
            $.ajax({
                url: 'http://localhost:3000/done/' + id,
                type: 'PUT',
                data: { isDone }
            }).done(function (data) {
                //location.reload()
                console.log(data)
            })

        } else {
            console.log('falses')
            $('.text').removeClass('line-through')
        }
    })
})

update function to nedb:

    function taskIsDone (id, done) {
    return new Promise((resolve, reject) => {
        db.update({ _id: id }, { $set: done }, { returnUpdatedDocs: true }, (err, num, updateDocs) => {
            if (err) {
                reject(err)
            } else {
                resolve(updateDocs)
            }
        })
    })
}

server:

app.put('/done/:_id', async(req, res) => {
  try {
    var id = req.params._id;
    let done = {
      title: req.body.isDone,
    }
      const updateToDo = await taskIsDone(id, done)
      console.log(updateToDo + " Todo done");
      res.json(updateToDo);
  } catch (error) {
    res.json({error: error.message});
  }
})

html/ejs:

<% for ( var i = 0; i < row.length; i++) { %>
        <div class="edit-container" >
        
                <input type="text" name="editTask" value="<%=row[i].title %>" data-id="<%=row[i]._id %>">

                <button name="<%= row[i]._id %>" class="edit" data-id="<%=row[i]._id %>">save edit</button>
        </div>
        
        <div>
                <input type="checkbox" name="isDone" class="taskDone" data-id="<%=row[i]._id %>">
                <span class="text"><%= row[i].title %></span>
                <button class="delete" name="<%= row[i]._id %>">delete</button>
        </div>
        <br>
    <% } %>

i could really need some help with this! thanks




How to detect an image with checkbox if its checked or not using OpenCV?

If the checkbox is marked with cross, tick, star, or any such symbols then it is checked. The non-checked checkbox image could be blank or have some irregular lines or have a perfect rectangle outline with nothing inside it.




VBA CheckBox_Change gets triggered by initializing the userform. How can I avoid this?

I wrote a code which adds +1 to a variable whenever a checkbox is "true" and -1 when it is "false". However, when I start the userform, all chkboxes are true as they should be but they all add +1 what they shouldn't do. So it starts with a counter too high as all checkboxes add 1. I want them to stay neutral UNTIL someone unclicks them. The number of checkboxes is unknown as there is more code so I can't set the counter at -4 for 4 checkboxes eg.

So basically I want them to ignore their initial value and get activated when they are manually clicked on. Any ideas?




onChange event with javascript modifications of checkbox [duplicate]

I tried to check a checkbox with js and detect the change, but the event onchange not detect the change, while that is visually changing. (sorry for by bad english, i'm french) Here is an example:

document.querySelector("#checkbox").onchange = (e) => {
  let checked = e.target.checked;
  if (checked) {
    console.log("checked !");
  } else {
    console.log("unchecked...");
  }
}

document.querySelector("#buttonOn").onclick = (e) => {
  document.querySelector("#checkbox").checked = true;
}
document.querySelector("#buttonOff").onclick = (e) => {
  document.querySelector("#checkbox").checked = false;
}
<button id="buttonOn">On</button>
<button id="buttonOff">Off</button>
<input type="checkbox" name="" id="checkbox">



vendredi 21 août 2020

Checkbox accessibility showing no relation

I have a group of checkbox with one heading. while checking the accessibility i am getting error "All elements with the name "recognitionOption" do not reference the same element with aria-labelledby" and "Fieldset contains unrelated inputs".

<fieldset>
   <legend id="item-box">Item Box</legend>
   <div>Choose your favourite item</div>
   <div aria-labelledby="item-box">
      <div class="ant-row ant-form-item">
         <div class="ant-col ant-form-item-control-wrapper">
            <div class="ant-form-item-control">
               <span class="ant-form-item-children">
                  <div>
                     <label><span class="ant-radio ant-radio-checked"><input name="itemOption" id="itemOption1" type="radio" class="ant-radio-input" aria-label="item1" value="10" checked=""><span class="ant-radio-inner"></span></span></label><span class="small-box">Jackfruit</span>
                  </div>
                  <div><label class="ant-radio-wrapper"><span class="ant-radio"><input name="itemOption" id="itemOption2" type="radio" class="ant-radio-input" aria-label="item2" value="20"><span class="ant-radio-inner"></span></span></label><span>Mango</span></div>
               </span>
            </div>
         </div>
      </div>
   </div>
</fieldset>

It would be helpful if someone can give some suggestion on this.

Thanks in advance




Pass a group of IDs to function (onchange function)

I have 10 html table lines. In each line I have 1 checkbox and 2 input boxes, each element with an unique ID (AA, Price_1, RTprice_1, AB, Price_2, RTprice_2....AJ, Price_10, RTprice_10)

Trying to disable the corresponding input fields once a checkbox is checked. I'm repeating the function for each line. How can I pass each group of variable into the below function instead of having 10 functions? Script:

document.getElementById("AA").onchange = function() {
document.getElementById('price_1').disabled = !this.checked;
document.getElementById('RTprice_1').disabled = !this.checked;
document.getElementById('price_1').value = "0";
document.getElementById('RTprice_1').value = "0";
document.getElementById('AA').value = "0";
};  

                                       
document.getElementById("AB").onchange = function() {
document.getElementById('price_2').disabled = !this.checked;
document.getElementById('RTprice_2').disabled = !this.checked;
document.getElementById('price_2').value = "0";
document.getElementById('RTprice_2').value = "0";
document.getElementById('AB').value = "0";};



Checkbox not aligning with Text

In my code, I am drawing all the Checkbox dynamically and I have to align checkbox with its text in same row but so far I am unable to do so.

Tried padding but that did not workenter image description here




console.log an array of checked checkbox values in React

I want to console.log an array of the checkboxes that are checked. Like if checkbox 1, 2, and 5 are checked, I want it to show in the console as an array of each checkbox's value. I can get the last value selected to show up in the console, but I can't get an array of all the checkboxes checked to show up. They just show up separate.

import { CheckboxData } from "../../../Data/SurveyData";

class CheckboxForm extends Component {
  constructor(props) {
    super(props);
    this.state = { value: [] };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
    console.log("Checkbox: ", event.target.value);
  }

  handleSubmit(event) {
    event.preventDefault();
  }

  render() {
    return (
      <div
        id="checkboxContainer"
        className="container"
        onSubmit={this.handleSubmit}
      >
        {CheckboxData.map((data, key) => {
          return (
            <div key={key}>
              <h5>{data.question}</h5>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[0].value}
                  id={`${data.options[0].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[0].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[1].value}
                  id={`${data.options[1].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[1].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[2].value}
                  id={`${data.options[2].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[2].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[3].value}
                  id={`${data.options[3].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[3].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[4].value}
                  id={`${data.options[4].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[4].label}
                </label>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}

export default CheckboxForm;

The data is in the SurveyData.js file as follows:

  {
    page: 2,
    name: "checkbox",
    question: "Check all that apply. I understand:",
    type: "checkbox",
    options: [
      {
        name: "checkbox1",
        value: "I am entering into a new contract.",
        label: "I am entering into a new contract.",
      },
      {
        name: "checkbox2",
        value:
          "I will be responsible for $49.95 each month until my contract is over.",
        label:
          "I will be responsible for $49.95 each month until my contract is over.",
      },
      {
        name: "checkbox3",
        value: "I have three days to cancel.",
        label: "I have three days to cancel.",
      },
      {
        name: "checkbox4",
        value:
          "If I cancel after three days, I will be responsible for the remainder of the contract.",
        label:
          "If I cancel after three days, I will be responsible for the remainder of the contract.",
      },
      {
        name: "checkbox5",
        value:
          "My system is monitored and if it is set off, the cops will come to my home.",
        label:
          "My system is monitored and if it is set off, the cops will come to my home.",
      },
    ],
  },
];```