mercredi 30 juin 2021

Filter fetched data with checkbox in react

I have fetched data from the json file.

I made the elements in which they are fetched, now I have to make checkboxes to filter these elements.

< Header /> - here I plan to do checkboxes for filtering.
< Main /> - here I have made elements that I would like to filter.

I have no idea how to go about it, in addition, I cannot map the data with tags to the checkboxes because they are repeated.

Json looks something like this :

[
{
    "id": "101",
    "title": "xyz",
    "tags": ["tag3", "tag1"]
  },
{
    "id": "102",
    "title": "xyz",
    "tags": ["tag1", "tag2"]
  },
{
    "id": "103",
    "title": "xyz",
    "tags": ["tag2", "tag4"]
  },
]
import { useState, useEffect } from 'react'
import Main from '../components/Main'
import Header from '../components/Header'
import Margins from '../components/Margins'

const Page = () => {
  const [data, setData] = useState([])

  const getData = () => {
    fetch('data.json', {
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
    })
      .then(function (response) {
        console.log(response)
        return response.json()
      })
      .then(function (myJson) {
        console.log(myJson)
        setData(myJson)
      })
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <Margins>
      <Header data={data} />
      <Main data={data} />
    </Margins>
  )
}

export default Page




Grouped dropdown. in angular material js

I am trying to make UI similar to one given in screenshot. Is this possible with angular js material.(v1.1.8)This ui




How to remove a string from an array based on string matching id

I'm currently rendering a Checkbox where if checked, the data (id in a string) is saved in state. However I'm trying to put together the functionality for if the checkbox is unchecked, the data needs to be removed from the state (which is an array of strings).

I have come up with this solution however I don't think I am using .splice correctly or if that's the best option for me to use as it doesn't work.

<Checkbox
        onChange={(e) => {
          e.target.checked
            ? setSelectedStyles([...selectedStyles, s.id])
            : e.target.checked === false &&
              selectedStyles.map((id) => id === s.id)
            ? selectedStyles.splice(s.id)
            : console.log(`didn't work`)
        }}
      ></Checkbox>

To clarify, selectedStyles is an array of strings stored in state. s.id is the id (string) I'm checking against.

Does anyone have any thoughts on how to approach this?

Thanks in advance




I am hiding the digital signature until every field and checkbox is completed. However, my code isn't recognizing the checkbox as not being checked

var bEmpty = false;

var oFld = this.getField("Date") bEmpty |= /^\s*$/.test(oFld.value);

var oFld = this.getField("Vessel Name") bEmpty |= /^\s*$/.test(oFld.value);

var oFld = this.getField("Group0") bEmpty |= /^\s*$/.test(oFld.value);

var oFld = this.getField("Check Box 2") bEmpty |= /^\s*$/.test(oFld.value);

var oFld = this.getField("Check Box 3") bEmpty |= /^\s*$/.test(oFld.value);

this.getField("Employee Name").display = bEmpty ? display.hidden : display.visible;




generated with on runtime

I have been creating a form with lots of <input type="checkbox"> for search and filter functionality. Please find the code below;

    <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" name="type" value="1" id="type1">
        <label class="custom-control-label" for="type1">Filter Sub Item</label>
   </div>

But when the page renders in the browser the DOM is appended with a new hidden field for each <input type="checkbox">

<input type="hidden" name="_type" value="on">

I am using Boostrap CSS library for the form design. How can I stop this from auto generating the hidden fields in the form.

When I submit the form with method="get" these hidden values are appearing in the browser address bar.




Count selected checkboxes in collectionview xamarin

I have a collection view with a checkbox. I want to count the amount of checkboxes which have been selected and show that value in a label (string Sel). I think I have mostly done it however the label doesn't update. I think this is due to not calling OnProperty changed in the correct place which would update the label. I'm still rapping my head round MVVM. Thanks

ModelView:

public class MeetAWalkerViewModel : INotifyPropertyChanged
 {
       
       
     public ObservableCollection<PetProfile> source;
     public ObservableCollection<PetProfile> PetInfo { get; private set; }
     public ObservableCollection<PetProfile> EmptyPetInfo
     {
         get => source;
         private set
         {
             if (value != source)
             {
                 source = value;
                 OnPropertyChanged(nameof(EmptyPetInfo));
             }
         }
     }
     
        
     public string Sel { get; private set; }

     public MeetAWalkerViewModel()
     {
            
         var count = EmptyPetInfo.Count(t => t.Selected);
         Sel = "Amount of selected pets" + Convert.ToString(count);
     }

       
        
     #region INotifyPropertyChanged
     public event PropertyChangedEventHandler PropertyChanged;
     void OnPropertyChanged([CallerMemberName] string propertyName = null)
     {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
     #endregion
 }

Xaml:

<CollectionView  x:Name="petCollectionView"  ItemsSource="{Binding EmptyPetInfo}">
                 <CollectionView.ItemTemplate>
                     <DataTemplate>
                         <Grid Padding="10" RowDefinitions="80" ColumnDefinitions="120,60,60">
                             <Image Grid.Column="0"
                                Grid.Row="0"
                                x:Name="PetImage"
                                Source="{Binding imageUrl}"/>
                             <Label Grid.Column="1"
                                Grid.Row="0"
                                Text="{Binding PetName}"
                                FontAttributes="Bold"
                                x:Name="labelpetname" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
                             <CheckBox  Grid.Row="0" Grid.Column="2" HorizontalOptions="End" IsChecked="{Binding Selected, Mode=TwoWay}" CheckedChanged="CheckBox_CheckedChanged" BindingContext="{Binding .}"/>
                         </Grid>
                     </DataTemplate>
                 </CollectionView.ItemTemplate>
             </CollectionView>



mardi 29 juin 2021

How to bold customized checkbox text label scss

I want to make customized checkbox in react with using scss.

My react component is:

<div className="checkbox">
        <ul>
          {data.map((item) => (
            <li key={item.id}>
              <label htmlFor={item.text} >
                <span >
                  <input
                    type="checkbox"
                    id={item.text}
                    name="checkbox-list"
                    value={item.text}
                    checked={isSelected.includes(item.id)}
                    onChange={() => onSelectedFilter(item)} //when onClick, I get the error 
                  />
                    <span class="checkbox-icon-wrapper"><span class="checkbox-icon icon-tick"></span></span>
                </span>
                <span className="labeltext" >{item.text}</span>
              </label>
            </li>
          ))}
        </ul>
    </div>

and my style.scss is :

.checkbox {
  display: inline-block;
  ul {
    li {
      label {
        display: inline-flex;
        align-items: center;
        font-family: Montserrat;
        font-size: 12px;
        font-weight: normal;
        font-stretch: normal;
        font-style: normal;
        line-height: 1.5;
        letter-spacing: 0.3px;
        color: #1b1b1b;
        padding: 5px;
        
        &:hover {
          cursor: pointer;
        }

      .checkbox-icon-wrapper {
        position: relative;
        display: inline-block;
        box-sizing: border-box;
        display: grid;
        place-items: center;
        width: 14px;
        height: 14px;
        border: 1px solid gray;
        transform: translateY(-0.5px);
        margin-right: 10px;

        .checkbox-icon {
          position: absolute;
          font-size: 8px;
          line-height: 0;    
          color: rgb(255, 255, 255);
        }
      }

      input[type="checkbox"] {
        display: none;
    
        & + .checkbox-icon-wrapper > .checkbox-icon {
            opacity: 0;
            transform: scale(1);
        }
        &:checked + .checkbox-icon-wrapper > .checkbox-icon {
          transform: scale(1);
          opacity: 1;
          
        }
    
      }

      
    }
}}}

.checkbox label input[type="checkbox"] + .checkbox-icon-wrapper > .checkbox-icon {
    opacity: 0;
    transform: scale(1);
}

.checkbox label input[type="checkbox"]:checked + .checkbox-icon-wrapper > .checkbox-icon {
  transform: scale(1);
  opacity: 1;
}

.checkbox label input[type="checkbox"]:checked + .checkbox-icon-wrapper {
  background-color:#e56d59;
  opacity: 1;
  border: 2px solid #e56d59;
  transition: 140ms transform ease-in-out;
  
}



I want to make last child of .checkbox bold when checked state ( span for className=labeltext).

But I can't do this. I'm just learning css and please help me about this issue , what is + or > between classNames ?




Codeigniter Checked Loop Data into DB

I want to do a weekly royalty points giveaway table for my member. However, the rewards points are not fixed amount (count by percentage) and has its minimum total weekly sales requirement.

i.e. $1000 x 10% = 10 Points.. and below $100 will not get any points

if i have a table loop results of all the members of have purchase something on my website within the selected week...i wanted to add a checkbox in front of those "ACTIVE" member, and i can directly giveaway the bonus to those members with "checked". I need to insert Member id and Point Amount into the mysql.

My View looks like

[Button Add Reward]
    Member  |   Total Sales  |   Points
[✓] Alex    |     $1000      |    10
[ ] Beck    |      $100      |    0
[✓] Cath    |     $2000      |    20

My View

   <form action="http://localhost/lkmaster/vip/add_rebate" method="post">
     <button type="submit" name="submit" class="btn btn-danger">Add Selected</button>
        <table class="table table-striped table-bordered" style="width:100%">
          <thead>
             <tr class="btn-primary">
                <th></th>
                       <th></th>
                       <th>Member</th>
                       <th>Point Amount</th>
                     </tr>
                 </thead>
                 <tbody>
                    <tr>
                       <td>
                         <input type="checkbox" name="member_id[]" value="281" checked>
                       </td>
                       <td>1</td>
                       <td class='text-left'><strong>Alex</strong></a></td>                    
                       <td>10                                      
                         <input type="hidden" name ="point_amount[]" value="10" >
                       </td>
                    </tr>
                    <tr>
                       <td>
                         <input type="checkbox" name="member_id[]" value="101" disabled>
                       </td>
                       <td>1</td>
                       <td class='text-left'><strong>Alex</strong></a></td>                    
                       <td>0                                   
                         <input type="hidden" name ="point_amount[]" value="0" >
                       </td>
                    </tr>
                    <tr>
                       <td>
                         <input type="checkbox" name="member_id[]" value="1" checked>
                       </td>
                       <td>1</td>
                       <td class='text-left'><strong>Alex</strong></a></td>                    
                       <td>20                                  
                         <input type="hidden" name ="point_amount[]" value="20" >
                       </td>
                    </tr>
                  
                 </tbody>
               </table>
         </form>
   

My Controller

    <?php
    public function add_rebate() {
        $member_id = $this->input->post('member_id'); //here i am getting member id from the checkbox
        $point_amount = $this->input->post('point_amount'); 
        
           for ($i=0; $i < sizeof($member_id); $i++) {
             $data = array('member_id' => $member_id[$i],
                           'point_amount' => $point_amount[$i]);
            $this->db->insert('tbl_bonus_giveaway',$data);
            
            }
    
                      
             return redirect(base_url('vip/rebate'),'refresh');
    }
    ?>

Something wrong with this code, as If I unchecked the previous rows.

For previous example, Alex get points with no issue if first row, but Cath will get "0" from Beck, if I uncheck ALEX from the list, it will add Cath's member ID but Alex's Points into database (previous rows points amount).

What do i miss there to make correct data go into DB correctly followed by its checked row.




Toggle class on trigger and on div inside trigger

I'm trying to create an own multiselect dropdown with checkboxes. Works so fine, so far, the only problem that i have is, that the class .checkbox-selected wich triggers the design of the checkbox rectangle, is only triggert when i click on the checkbox, but not on the text wich is right to it, or the link in generell. How can i achieved it, that the trigger is also set by clicking the link or text?

$(document).ready(function(e) {
  $(".dropdown-items .checkbox").click(function() {
    $(this).toggleClass("checkbox-selected");
  });
});
.dropdown-items {
  font-size: .875rem;
  line-height: 1.375em;
  margin-bottom: 0.625rem;
  display: flex;
  align-items: center;
}

.checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid #E2E2E2;
  border-radius: 5px;
  margin-right: 0.625rem;
}

.checkbox-selected {
  background-color: #BC9590;
  width: 18px;
  height: 18px;
  border-color: #bc9590;
  background-image: url(../img/checked.svg);
  background-repeat: no-repeat;
  background-position: center center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="dropdown-items">
  <div class="checkbox"></div>
  <p>demo</p>
</a>
<a href="#" class="dropdown-items">
  <div class="checkbox"></div>
  <p>demo</p>
</a>



C# Checked Change the other checkbox (color change, flat appearance checkbox mousedown color)

Only if there is one mousedown color in the flat appearance in the check box. Also, when I put the mouse on the check box, I want to change the mousedown color of the other flat appearance check box.

ex) check box 1, check box 2

Point to checkbox 1 to change the color of checkbox 2.

How do I change the mouse-over color of a check box along with other check box colors?

i use C#

thanks my friends.




lundi 28 juin 2021

Selenium Chrome Python checkbox associated with a label name

I have a webpage with a list of checkboxes associated with dates (labels).

I want to be able to parse through the webpage :

  1. Find the date I want in the webpage which is always tomorrow (today +1)
  2. Find the Checkbox associated with the found date
  3. Check that checkbox (ex.: Baignade du 29 juin 2021)

For the moment, I use the ID to find the CheckBox which I want and click on it.

Thank you so much for your help in advance. Cheers.

LINK: https://ludik.maville.net/Brossard-LudikIC2Prod_Enligne/Pages/Anonyme/Recherche/Page.fr.aspx?m=1

# piscine Reservation Alpha v1
# https://sites.google.com/a/chrominium.org/chromedriver/downloads
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

import time
import datetime


PATH = "/Users/josephhuynhngoctri/Desktop/Python/chromedriver"
driver = webdriver.Chrome(PATH)
action = ActionChains(driver)  # init. action for double-click

# get Web page Brossard for aquatic activities
driver.get("https://ludik.maville.net/Brossard-LudikIC2Prod_Enligne/Pages/Anonyme/Recherche/Page.fr.aspx?m=1")


# click on "Aquatique" button at the top left menu
link = driver.find_element_by_id("ctlHautPage_ctlMenu_ctlLienActivites")
link.click()

time.sleep(2)

# CHOOSE DATE
# select checkbox 29 Juin by ID - choice #10
checkbox = driver.find_element_by_id("ctlBlocRecherche_ctlRestrictions_ctlSelSession_ctlListeSessions_ctl10_ctlSession_ctlSelection")
checkbox.click()

# Find TOMORROW Date
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1) 
tomorrow = tomorrow.strftime("%B %d, %Y")
print("Today's date String =", tomorrow)

# select checkbox 29 June by xpath via label 
checkbox = driver.find_element_by_xpath("//label/input[contains(..'tomorrow')]")
checkbox = click()


  [1]: https://i.stack.imgur.com/FKJcM.png



vendredi 25 juin 2021

How to reset Material UI Checkbox on Dialog close

I've created a Dialog component via Material UI, dynamically imported from another file.

It works fine, except the checkboxes (also created with Material UI) inside this Dialog do not reset after each time Dialog closes. They only reset on page refresh. Other types of input, such as text or password do reset themselves automatically.

Here is the code for the original Dialog modal component:

import React, {useState, useEffect} from "react";
import Button from "@material/react-button";

import Divider from "@material-ui/core/Divider";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import TextField from "@material-ui/core/TextField";
import FormGroup from "@material-ui/core/FormGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";

const SearchModal = (props) => {

    const [checkState, setCheckState] = useState({
        checkedQuestions: true,
        checkedAnswers: true,
        checkedVerified: true,
        checkedPending: true,
        checkedDisputed: false
    });

    useEffect(() => {
        if(
            checkState.checkedQuestions === false &&
            checkState.checkedAnswers === false
        ){
            setCheckState({
                ...checkState,
                checkedQuestions: true,
                checkedAnswers: true
            });
        }
        if(
            checkState.checkedVerified === false &&
            checkState.checkedPending === false &&
            checkState.checkedDisputed === false
        ){
            setCheckState({
                ...checkState,
                checkedVerified: true,
                checkedPending: true,
                checkedDisputed: false
            });
        }
    });

    const checkSet = (event) => {
        setCheckState({
            ...checkState,
            [event.target.name]: event.target.checked
        });
    }

    return(
        <Dialog
            open={props.searchOpen}
            onClose={props.handleClose}
            aria-labelledby="searchModalTitle"
            aria-describedby="searchModalDescription"
            id="searchModal"
        >
            <DialogTitle id="dialog">{"Search tolodire."}</DialogTitle>
            <DialogContent>
                <DialogContentText className="marginBottom-17" id="searchModalDescription">
                    Search for questions or answers.
                </DialogContentText>
                <TextField
                    required
                    type="search"
                    id="searchQuery"
                    label="Enter keywords or sentences"
                    placeholder="Required"
                    variant="outlined"
                    data-owner="searchModal"
                    autoFocus
                />
                <DialogContentText className="marginTop-20 marginBottom-10">
                    Use filters to search in detail.
                </DialogContentText>
                <FormGroup row className="marginTop-5">
                    <FormControlLabel
                        control={
                            <Checkbox
                                color="default"
                                checked={checkState.checkedQuestions}
                                onChange={(e) => checkSet(e)}
                                name="checkedQuestions"
                            />
                        }
                        label="Questions"
                    />
                    <FormControlLabel
                        control={
                            <Checkbox
                                color="default"
                                checked={checkState.checkedAnswers}
                                onChange={(e) => checkSet(e)}
                                name="checkedAnswers"
                            />
                        }
                        label="Answers"
                    />
                </FormGroup>
                <Divider/>
                <FormGroup row>
                    <FormControlLabel
                        control={
                            <Checkbox
                                color="default"
                                checked={checkState.checkedVerified}
                                onChange={(e) => checkSet(e)}
                                name="checkedVerified"
                            />
                        }
                        label="Verified"
                    />
                    <FormControlLabel
                        control={
                            <Checkbox
                                color="default"
                                checked={checkState.checkedPending}
                                onChange={(e) => checkSet(e)}
                                name="checkedPending"
                            />
                        }
                        label="Pending Verification"
                    />
                    <FormControlLabel
                        control={
                            <Checkbox
                                color="default"
                                checked={checkState.checkedDisputed}
                                onChange={(e) => checkSet(e)}
                                name="checkedDisputed"
                            />
                        }
                        label="Disputed"
                    />
                </FormGroup>
            </DialogContent>
            <DialogActions>
                <Button raised className="button regularButton font-body" onClick={props.handleClose}>
                    Search
                </Button>
            </DialogActions>
        </Dialog>
    );
}

export default SearchModal

I've already tried searching this issue on Google and StackOverflow, yet, I haven't found any solution. Any contribution is appreciated.

P.S: The handleClose const is on another file;

const [searchOpen, setSearchOpen] = useState(false);

const handleSearchOpen = () => {
    setSearchOpen(true);
};

const handleClose = () => {
    setSearchOpen(false);
};



Como lidar com inputs do tipo checkbox e number

tenho um script que faz um cadastramento

funciona assim: numa tabela dinamica, cada linha tem um input que é do tipo checkbox e ele carrega uma id e outro input é tipo number e carrega um valor qualquer

dai ocorre que $_POST fica com arrays com numeros distintos de indices. por ex, se nessa tabela eu marcar somente a ultima checkbox e colocar um valor no ultimo input number, o array do checkbox terá um valor true para seu indice 0, ao mesmo tempo que o valor que eu coloquei no input number estará em outro indice, o que significa que o loop nao vai pegar o valor number correto..

foreach($fator as $k => $v){
        try{
            $sql = "INSERT INTO " . EMP_MODALIDADES . " (eid,mid,fator) VALUES (:eid,:mid,:fator)";
            $insert = $link->prepare($sql);
            $insert->bindValue(':eid',$eid);
            $insert->bindValue(':mid',$v);
            $insert->bindValue(':fator',$fator[$k]);
            $insert->execute();
        }
        catch(PDOException $erro){
            die('INSERT error: '.$erro->getMessage());
        }



knockout - header checkbox stays unchecked in table header when clicked

I am new to knockout and I am stuck at a problem for last couple of days - I am sure it is something silly but cant figure out. Any help will be appreciate. I am trying to select and deselect all rows in a table based on the header check box column. The SelectAll function works and selects/unselects all rows in table but the header remains unckecked?

    <tr>    
        <th><input type="checkbox" data-bind="click: selectAll, checked: AllChecked"></th>
        <th>@Html.Vocab("Document")</th>
        <th>@Html.Vocab("Notes")</th>
        <th>@Html.Vocab("Created")</th>
    </tr> 

    <tbody data-bind="foreach: DocumentRows">
        <tr >
            <td><input type="checkbox" data-bind="checked: IsSelected"></td>   
            <td><data-bind="text: Notes"></td>               
        </tr>
    </tbody>

And here is the script:

 //Document
    class Document {
        Id: KnockoutObservable<number>;
        Notes: KnockoutObservable<string>;       
        IsSelected: KnockoutObservable<boolean>;
        constructor(data?) {
            this.Id = ko.observable(0);
            this.Notes = ko.observable("").extend({ defaultValue: "" });            
            this.IsSelected = ko.observable(false);
            if (data != null) {
                ko.mapping.fromJS(data, {}, this);
            }            
        }      
        
    };


//DocumentS VIEW MODEL
  class DocumentsViewModel {
    DocumentRows: KnockoutObservableArray<Document>;        
    IsAnySelected: KnockoutObservable<boolean>;//used for delete button
    constructor(params) {
       this.DocumentRows = ko.observableArray([]);
       this.selectedIds = ko.observableArray([]);
    }
    
    InitComputed = () => {
       this.IsAnySelected = ko.pureComputed(() => {
                    var isChecked = false;
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        if (item.IsSelected()) {
                             isChecked = true;
                         }
                     });
                    return isChecked;
                });
    }
    selectAll = (): void => {
                
                if (this.selectedIds().length > 0) {
                    this.selectedIds.removeAll();
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        item.IsSelected(false);
                    });
                 
                } else {
                    ko.utils.arrayPushAll(this.selectedIds(), this.DocumentRows())
                    ko.utils.arrayForEach(this.DocumentRows(), function (item) {
                        item.IsSelected(true);
                    });
                  
                }
              
            }
    }



C# reset wpf toolkit CheckComboBox

I have a CheckComboBox from the wpfToolkit and i want to reset it. That means that all items in the CheckComboBox are unchecked. Already tried to set the SelectedValue to an empty string. This works for the function itself, but in the UI the items are still checked.

I also work with Bindings and the MVVM pattern:

 <wpfTool:CheckComboBox IsSelectAllActive="True"  ItemsSource="{Binding Filter, UpdateSourceTrigger=PropertyChanged}" SelectedValue="{Binding SelectedFilterItem, UpdateSourceTrigger=PropertyChanged}" Width="140"/>
                   



jeudi 24 juin 2021

AngularJS Bootstrap checkbox not checking on click

I have a checkbox I am using in my AngularJS/Bootstrap application and the issue i'm facing is that when I click on it when it's unchecked, it's not showing the checkmark. The toggleVal() method is being called though and it's executing the steps but it's not showing the check mark. Also, my scope variable myvar is either a 0 or a 1 and I want to display it accordingly.

<input ng-click="toggleVal()" class="form-check-input ml-2" type="checkbox"  
  ng-model="myvar"
  ng-checked="myvar"
  ng-true-value="1" ng-false-value="0">



How I can create a Popup when I press a Checkbox in kivy?

I want a pop-up to be created when both a and c are selected in the checkbox.
The popup should show the written: "Both A and C are selected, not well".
I don't want use RadioButton because I want you to be able to select both A and B or B and C

Python file

import kivy
from kivymd.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.core.window import Window

Builder.load_file('try.kv')

class MyLayout(Widget):
    checks = []
    def checkbox_click(self, instance, value, topping):
        if value == True:
            MyLayout.checks.append(topping)
            print(MyLayout.checks)
            if "a" in MyLayout.checks and "c" in MyLayout.checks:
                print("not well")
        
        else:
            MyLayout.checks.remove(topping)
            print(MyLayout.checks)
            if "a" in MyLayout.checks and "c" in MyLayout.checks:
                print("not well")


class MyApp(App):
    def build(self):
        return MyLayout()


if __name__ == '__main__':
    MyApp().run()

kv file

<MyLayout>

    GridLayout:
        cols:2

        Label:
            text:"a"
        CheckBox:
            on_active: root.checkbox_click(self, self.active, "a")

        Label:
            text:"b"
        CheckBox:
            on_active: root.checkbox_click(self, self.active, "b")

        Label:
            text:"c"
        CheckBox:
            on_active: root.checkbox_click(self, self.active, "c")



mercredi 23 juin 2021

remove the selected item from the Table. React

I need to click on the button to delete the line with the selected checkbox. I don't know how to use the filter method. I read the documentation, but there is little information there. help me correct the code

 class Table extends Component {
        constructor(props) {
          super(props);
          this.state = {
            droplets: [],
            allSelected: false,
            isChecked: false
          }
          this.toggleSelectAll = this.toggleSelectAll.bind(this);
          this.toggleSelect = this.toggleSelect.bind(this);
          this.handleChecked = this.handleChecked.bind(this);
          **this.handleDelete = this.handleDelete.bind(this);**
        }
        async componentDidMount() {
          const res = await fetch('http://api.npoint.io/324f4ca2cdd639760638');
          const droplets = await res.json();
          this.setState({ 'droplets': droplets })
        }
        
        toggleSelect(dropletToToggle) {
          this.setState({isChecked: !this.state.isChecked});
          this.setState((prevState) => {
            const newDroplets = prevState.droplets.map((dplt) => {
              if (dplt === dropletToToggle) {
                return { ...dplt, checked: !dplt.checked };
              }
              return dplt;
            });
      
            return {
              ...prevState,
              droplets: newDroplets,
              allSelected: newDroplets.every((d) => !!d.checked)
            };
          });
        }
      
        
        toggleSelectAll() {
          this.setState({isChecked: !this.state.isChecked});
          this.setState((prevState) => {
            const toggle = !prevState.allSelected;
            const newDroplets = prevState.droplets.map((x) => ({
              ...x,
              checked: toggle
            }));
            
            return {
              ...prevState,
              droplets: newDroplets,
              allSelected: toggle
            };
          });
        }
        handleChecked () {
          this.setState({isChecked: !this.state.isChecked});
        }
       
    
        **handleDelete = isChecked => {
          this.setState(state => {
            const { droplets } = state;
            const filteredDroplets = droplets.filter(item => item.id !== isChecked);
            return {
              droplets: filteredDroplets
            };
          });
        };**
    
        render() {
          
          return (
            <div className="body">
              <div className="title">Таблица пользователей</div>
              <table className="panel">
                <Tablehead
                  toggleSelectAll={this.toggleSelectAll}
                  allSelected={this.state.allSelected}
                />
                <tbody className="row">
                  <TableBody
                    droplets={this.state.droplets}
                    toggleSelect={this.toggleSelect}
                  />
                </tbody>
              </table>
              **<button className="button" onClick = {this.handleDelete} >Удалить выбранные</button>**
            </div>
          );
        }
      }

the second file in which the item to delete

const TableBody = ({ droplets, toggleSelect}) => {

  return (
    <>
      {droplets.map((droplet, item) => (
        <tr className={s.area} key={item.id} > 
          <td>
            <Checkbox
              handleClick={() => toggleSelect(droplet)}
              isChecked={!!droplet.checked}
            />
          </td>
          <td>{droplet.num}</td>
          <td>{droplet.first_name + " " + droplet.last_name}</td>
          <td>{date_form(droplet.date_of_birth)}</td>
          <td>{height_form(droplet.height)}</td>
          <td>{weight_form(droplet.weight)}</td>
          <td>{salary_form(droplet.salary)}</td>
          <td>
            <button type="submit" className={s.button}>
              <Edit />
            </button>
          </td>
          <td>
            <button type="submit" className={s.button}>
              <Trash />
            </button>
          </td>
        </tr>
      ))}
    </>
  );
};

https://codesandbox.io/s/sweet-butterfly-0s4ff?file=/src/Table.jsx




Checkboxes in Form return only 1 (last selected) value

I have 3 checkboxes. If i select more than 1, it mails me only the last selected. (example: Red, Blue, Green, all selected. In my email i receive only Green. Rest of the fields work fine.

Here's my checkbox :

<label>
    Which color do you like?<br />
    <label>
    <input class="filled-in" type="checkbox" name="checkbox1" value="Red" /><span>Red</span><br />
    </label>
    <label>
    <input class="filled-in" type="checkbox" name="checkbox1" value="Blue" /><span>Blue</span><br />
    </label>
    <label>
    <input class="filled-in" type="checkbox" name="checkbox1" value="Green" /><span>Green</span><br />
    </label>
</p>

In my form-mailer.php i have:

$email_address = $_REQUEST['email_address'] ;
$comments = $_REQUEST['comments'] ;
$first_name = $_REQUEST['first_name'] ;
$checkbox = $_POST['checkbox1'];
$msg = 
"First Name: " . $first_name . "\r\n" . 
"Email: " . $email_address . "\r\n" . 
"Checkbox" . $checkbox . "\r\n" . 
"Comments: " . $comments ;

I'm missing something but because i'm a bad programmer i don't see what. Any Suggestions?




How to read value associated with Checkbox using docx module in Python

I am attempting to read the table cell from word document and extracting the value associated with marked checkbox.

Please refer the attached screenshot of the cell. Doc cell

sho = table.cell(0,1)
for checkbox in sho:
 print('checkbox value is %s' %checkbox.get(qn('w:val))) 

Above code is not working.




R Shiny: Displays all tests at once after checking the checkboxes

I am trying to make a R Shiny App, which will print 3 statistical tests simultaneous, after the checkboxes were selected. The problem is the app is printing just one output, and the other ones "are not founded".Like can be seen here

I tried with

if(input$Stattest=='PP' | input$Stattest==1)

but..it doesn't work.

My code is:

 output$Stattest = renderUI({
     checkboxGroupInput("Stattest", "Choose test for stationarity", choices = c("ADF","PP","KPSS-TREND"))
  })
adf <- reactive({
    if(is.na(input$Stattest)){
      return(NULL)}

     if(input$Stattest=='ADF'){
       d=list()
       c=list(df_sel()[[print(input$y)]],df_sel()[[print(input$x1)]],df_sel()[[print(input$x2)]])
       for (i in 1:3){
         d[[i]]=adf.test(c[[i]])
       }
           }
    d
    })

  output$ADF=renderPrint({
    adf()
  })

 pp <- reactive({

    if(is.na(input$Stattest)){
      return(NULL)}

    if(input$Stattest=='PP' | input$Stattest==1){
      ptest=list()
      d=list(df_sel()[[print(input$y)]],df_sel()[[print(input$x1)]],df_sel()[[print(input$x2)]])
      for (i in 1:3){
        ptest[[i]]=pp.test(d[[i]])
      }

    }
    ptest
  })


  output$PP=renderPrint({
    pp()
  })

The main "problem" is that I need to create this reactive functions, because all of these tests will be printed in a pdf-report. Any idea how could I make it work?

Thanks in advance.




mardi 22 juin 2021

Matching a checkbox to a custom checkbox

Ok so I made a show hide toggle checkbox for a password input. However, I cannot figure out how to get the "when checked" background of the checkbox to be a different color.

In our existing code base there is a custom checkbox that uses custom styling, however I cannot use this checkbox for this feature as it does not use ng-model. See Example Here

<input ng-show="showpassword" type="text" name="Password" id="password" ng-model="TokenLogin.Password" Class="form-control input-lg" ng-class="Loginform.Password.$invalid?'ng-dirty':''" required autofocus style="width:250px;">
<input ng-hide="showpassword" type="password" name="Password" id="password" ng-model="TokenLogin.Password" Class="form-control input-lg" ng-class="Loginform.Password.$invalid?'ng-dirty':''" required autofocus style="width:250px;">
                                
<input style="opacity: 1; color: #009688;" type="checkbox" ng-model="showpassword" ng-checked="false"> <label style="color: #a9a9a9; font-weight: 700;">Show</label>



lundi 21 juin 2021

Angular Reactive form set Multiselect Checkbox values

The form is having 1 textbox , 1 radio button and 1 multi select Checkbox The HTML template is like below

        <form  *ngIf="notificationSettings | async; else loading"
              [formGroup]="notificationForm" (ngSubmit)="onSubmit()">
              
          <div class="form-group">        
            <div *ngFor="let option of notifyBackAlertOptions; let i=index">
              <input type="checkbox" class="form-check-input" [value]="option.value" formControlName="notifyBackOptions"  />
              <label>  </label>
            </div>
          </div>
          <div class="form-group">
            <label for="notifyBackEmail">Where shall we send the alerts?</label>
            <input type="email" class="form-control" formControlName="notifyBackEmail">
          </div>
          
          <div class="form-check" *ngFor="let option of discontinuedAlertOptions;">
            <label>
              <input formControlName="discontinuedOption" class="form-check-input"
                     type="radio"
                     name="discontinuedOption"
                     [value]="option.value" />
              
            </label>
          </div>

          <div class="float-left">
            <button class="btn btn-primary mr-1">Update</button>        
          </div>

        </form>

        <ng-template #loading>
          Loading ---...
        </ng-template>
        

The component is like below

    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';


    export class NotifcationsComponent implements OnInit {
      
      notificationSettings: Observable<NotificationSetting>;
      notificationForm: FormGroup;
      submitted = false; 
      
      notifyBackAlertOptions = [
        { name: 'Option 1', value: '1' },
        { name: 'Option 2', value: '2' },
        { name: 'Option 3', value: '3' }, 
        { name: 'Option 4', value: '4' }    
      ];
      discontinuedAlertOptions = [
        { name: 'Yes for any', value: '1' },   
        {name: 'Yes for all', value: '2' },
        { name: 'No', value: '3' }
      ];   

      constructor(private formBuilder: FormBuilder,private userService: UserService)  { }

      ngOnInit() {

        this.getCurrentSettings(); 
        this.notificationForm = this.formBuilder.group({
          notifyBackEmail: [''], 
          discontinuedOption: [''],   
          notifyBackOptions: new FormArray([]),
        });
        
        
      }

      getCurrentSettings(): void {



        this.notificationSettings =   this.userService
          .getUserNotificationSettings()
          .pipe(tap(data => {
            console.log("GET")
         
            this.notificationForm = this.formBuilder.group({
              notifyBackEmail: new FormControl(data.notifyBackEmail),                 
              discontinuedOption: new FormControl(data.discontinuedOption),
              notifyBackOptions: new FormControl(data.notifyBackOptions)
            });

            console.log(this.notificationForm) //I can see the values are mapping correctly against notificationForm. Checkbox  property ie notifyBackOptions value is coming as ["1", "2"] at this stage 

            }        
           ));
          
          //This code maps / sets the values of textbox and radio buttons correctly at page loading based on response from API. But not setting values for multiselect checkbox correctly. 
            //I can see all checkbox values are coming as selected.          IN this case 4 checkbox values are selected      
         //How to set only  the notifyBackOptions checkbox selected values marked as checked 
      }

      // convenience getter for easy access to form fields in HTML page 
      get f() { return this.notificationForm.controls; }
     

 

      onSubmit() {
        this.submitted = true; 
        // stop here if form is invalid
        if (this.notificationForm.invalid) {
          return;
        }
        console.log(this.notificationForm.value);        
      }

       

    }
    

The HTML is rendering correctly and capturing the values at form submission . At load time of the component i have to read the values from API endpoint and prefill form based on current settings

The JSON response from API endpoint is like below

    {
    notifyBackEmail: "email@email-domain.in"
    notifyBackOptions: ["1","2"]
    discontinuedOption: "1"
    }

The existing implementation of getCurrentSettings() is setting values of radio and textbox correctly but not checkbox. At present this is setting all values of checkbox as selected. How can i set the Checkbox values as selected based on response form API with help of model binding




Add text to checkboxlist item being added to another checkboxlist (while preserving original checkboxlist item)

I'm using Visual Studio, vb.net, and asp.net with webforms.

I have two checkboxlists, one called Available and one called Modifications. I don't want (Add) to show where I have the blue arrow in this picture. Please view this image for clarity on what I am about to explain.

When a user checks some items in Available and clicks the "Add" button, I have code to add the item to the Modifications checkboxlist. The item does not leave the Available checkboxlist until it hits the account max.

For example, Available Checkboxlist item Membership is allowed to be added twice. The user checks Membership and clicks Add. It adds to the Modifications checkboxlist. Membership remains in the Available checkboxlist. The user checks Membership again and clicks Add, and Membership is added a second time to Modifications. This time, Membership is removed from the Available checkboxlist because they hit the max of 2. (This number can be any number I set it to, by the way).

My issue is, when I add the item to Modifications, I want to concatenate the word (Add) to the item. However it also adds the word (Add) to my Available checkboxlist. I want to say (Add) in modifications but not in available. How can I do this? This is where I do it CBLAvailable.Items(i).Text = CBLAvailable.Items(i).Text + serviceAdd where serviceAdd is Private serviceAdd As String = "<span style='color:red;'><em> (Add)</em></span>"

  Protected Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click

        'Create the local DataTable and set it to the ViewState
        Dim dtEditedAvailable As DataTable
        dtEditedAvailable = DirectCast(ViewState("vsEditedAvailable"), DataTable)

        'Create a list to hold services that need removed
        Dim removeAvailableService As New List(Of ListItem)()

        'ADD ITEM FROM AVAILABLE TO MODIFICATION

        'Loop through each service in CBLAvailable
        For i As Integer = 0 To CBLAvailable.Items.Count - 1

            'If a service in CBLAvailable is selected
            If CBLAvailable.Items(i).Selected = True Then

                'Uncheck the item
                CBLAvailable.Items(i).Selected = False

                'Add this CBLAvailable service item to CBLModifications
                CBLAvailable.Items(i).Text = CBLAvailable.Items(i).Text + serviceAdd
                CBLModifications.Items.Add(CBLAvailable.Items(i))
                'Dim serviceValue = CBLAvailable.Items(i).Value
                'Dim serviceMod = CBLModifications.Items.FindByValue(serviceValue)
                'serviceMod.Text += serviceAdd

                'Get the service ID from CBLAvailable and select the matching service row in dtAvailable
                Dim serviceId = CBLAvailable.Items(i).Value
                Dim serviceRows() As DataRow = dtEditedAvailable.Select("ID = " + serviceId)

                If serviceRows.Count > 0 Then
                    'Get the AccountTotal (Number of accounts user added)
                    Dim serviceAccountTotal = serviceRows(0).Item("AccountTotal").ToString()

                    'Add one to the AccountTotal
                    Dim newTotal = Integer.Parse(serviceAccountTotal) + 1

                    serviceRows(0).Item("AccountTotal") = newTotal
                    dtEditedAvailable.AcceptChanges()

                    'Compare to the AccountMax and add the item from CBLAvailable to removeAvailableService if max is reached
                    Dim serviceAccountMax = Integer.Parse(serviceRows(0).Item("MaxAccount").ToString())
                    If newTotal >= serviceAccountMax Then
                        removeAvailableService.Add(CBLAvailable.Items(i))
                    End If
                End If
            End If
        Next

        'REMOVE SERVICE ITEM FROM AVAILABLE
        'Loop through each service in the removeAvailableService list that needs to be removed
        For i As Integer = 0 To removeAvailableService.Count - 1

            'Remove the service from CBLAvailable
            CBLAvailable.Items.Remove(removeAvailableService(i))

        Next

        'Set the current state of the DataTable to the ViewState
        ViewState("vsEditedAvailable") = dtEditedAvailable
End Sub



Header (select all) checkbox does not stay checked

we are using Vaadin 8 and we have a multi select grid. In the header there is a checkbox present which acts as a select / deselect all checkbox. The problem is that the header checkbox does not stay checked after the window is closed. E.g. if the window is opened, the header checkbox is checked -> all other checkboxes are checked, the window is then closed and opened again he header checkbox is unchecked again. Is there a method to manually set the header checkbox value, or any other workaround? We work with a data provider object and upon the button click the selected items are saved, but we have no way of accessing (or we do not know of a way of accessing) the header checkbox.




dimanche 20 juin 2021

Updating the value of a Checkbox column in datagridview in c# by code

I am trying to update the value of a checkbox column in datagridview in c# by code but it is not working. Here it is the code:

foreach (DataGridViewRow r in dgvAlumnos.Rows)
{
    if (attendance[r.Index] == true)
    {
        r.Cells[2].Value = true;
    }
    else
    {
        r.Cells[2].Value = false;
    }
}

Attendance is the array of booleans where I have the values.

The column number 2 of the datagridview is the checkbox column.

However, the changes are not visible in the datagriview. I am using this code inside the form construct.

Thanks in advance.




Adding variable automatically when checkbox is checked Android Studio

Is it possible to make arithmetic calculation automatically when checkbox is pressed? I want to add the total harga (total price) change based the choice of checkbox topping prices and add them with the basic prices (product price).

ex: checked CB Extra Ayam and CB Kepala will add 3000 + 4000 then add it with basic product price 10000 so the total price would be 17000 and the total price will back to 10000 when im unchecked CB Extra Ayam and CB Kepala and so on

screenshoot

Here is my code

if (Code.toUpperCase().matches((inMieAyam.toUpperCase()))){
            
    //set text topping
    CBTopping1.setText("Extra Ayam");
    CBTopping2.setText("Extra Tetelan Sapi");
    CBTopping3.setText("Cakar (2 pcs)");
    CBTopping4.setText("Kepala");
    CBTopping5.setText("Bakso Sapi");
    CBTopping6.setText("Telur Mata Sapi");
    CBTopping7.setText("Balungan Rica Ayam");
    CBTopping8.setText("Extra Sawi");
    CBTopping9.setText("Extra Acar");

    //hide remaining topping CB
    CBTopping10.setVisibility(View.GONE);

    //set price to variable
    Price1 = 3000;
    Price2 = 7000;
    Price3 = 4000;
    Price4 = 4000;
    Price5 = 3000;
    Price6 = 4000;
    Price7 = 4000;
    Price8 = 1000;
    Price9 = 1000;
    Price10 = 0;

    //set price topping
    TxtvToppingPrice1.setText("Rp."+Price1);
    TxtvToppingPrice2.setText("Rp."+Price2);
    TxtvToppingPrice3.setText("Rp."+Price3);
    TxtvToppingPrice4.setText("Rp."+Price4);
    TxtvToppingPrice5.setText("Rp."+Price5);
    TxtvToppingPrice6.setText("Rp."+Price6);
    TxtvToppingPrice7.setText("Rp."+Price7);
    TxtvToppingPrice8.setText("Rp."+Price8);
    TxtvToppingPrice9.setText("Rp."+Price9);


    //hide remaining topping price Txtv
    TxtvToppingPrice10.setVisibility(View.GONE);
    

    FinalPrice1 = 0;
    FinalPrice2 = 0;
    FinalPrice3 = 0;
    FinalPrice4 = 0;
    FinalPrice5 = 0;
    FinalPrice6 = 0;
    FinalPrice7 = 0;
    FinalPrice8 = 0;
    FinalPrice9 = 0;
    FinalPrice10 = 0;

    CBTopping1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice1 = Price1;
            }
            else {
                FinalPrice1 = 0;
            }
        }
    });

    CBTopping2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice2 = Price2;
            }
            else {
                FinalPrice2 = 0;
            }
        }
    });

    CBTopping3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice3 = Price3;
            }
            else {
                FinalPrice3 = 0;
            }
        }
    });

    CBTopping4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice4 = Price4;
            }
            else {
                FinalPrice4 = 0;
            }
        }
    });

    CBTopping5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice5 = Price5;
            }
            else {
                FinalPrice5 = 0;
            }
        }
    });

    CBTopping6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice6 = Price6;
            }
            else {
                FinalPrice6 = 0;
            }
        }
    });

    CBTopping7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice7 = Price7;
            }
            else {
                FinalPrice7 = 0;
            }
        }
    });

    CBTopping8.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice8 = Price8;
            }
            else {
                FinalPrice8 = 0;
            }
        }
    });

    CBTopping9.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                FinalPrice9 = Price9;
            }
            else {
                FinalPrice9 = 0;
            }
        }
    });


    FoodPrice1 = Integer.parseInt(Price);
    TotalFinalPrice = FoodPrice1 + FinalPrice1 + FinalPrice2 + FinalPrice3 +
            FinalPrice4 + FinalPrice5 + FinalPrice6 +
            FinalPrice7 + FinalPrice8 + FinalPrice9 ;

    TxtvTotalHarga.setText(Integer.toString(TotalFinalPrice));

}

the variable of the TotalFinalPrice just not changed or maybe not calculated




How to get value of Checkbox and save in Array?

I have a checkbox like this:

LinearLayout layout = findViewById(R.id.lyLayout);
CheckBox checkBox;

for (int i = 0; i < items.size(); i++) {
    checkBox = new CheckBox(getBaseContext());
    checkBox.setId(View.generateViewId());
    checkBox.setText(items.get(i).getDesk());
    layout.addView(checkBox); 
}

and I want to get checked data, I do this :

ArrayList<String> checkedBox = new ArrayList<>();
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> 
    {
        for (int a = 0; a < layout.getChildCount(); a++) {
        checkBox = (CheckBox) layout.getChildAt(a);
        if (checkBox.isChecked()) {
        checkedBox.add(checkBox.getText().toString());
        Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();

        } else {
            checkedBox.remove(checkBox.getText().toString());
            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();
            }
        }
    });

but the captured data is only at index 0. Other than that, the data is not stored. And sometimes the data is not stored at all.




handling multiple checkboxs and push or filter values based on selection

how to handle checkbox is selected or not and push the object if selected and remove if unselected ?

this is the initial arr set to state

let arr=[{lable:lable1,value:value1}
{lable:lable2,value:value2}
{lable:lable3,value:value3}
]

handle function triggered on selecting checkbox

  function handleChange(item) {
        let temp = [...arr];
     if (temp.includes(item.value)) {
       temp = temp.filter((value) => value != item.value);
     } else {
       temp.push(item.value);
     }
     setState(temp);
  }

multiple checkbox iterated based on array

      {arr.map((item, i) => {
        return (
             
                <label className="check-wrap">
                  <input
                    className="check-field"
                    checked={ ? } // how to handle checkbox is selected or not
                    name={item.lable}
                    onChange={() => handleChange(item)}
                    type="checkbox"
                  />
                  <span className="check-label">{item.value}</span>
                </label>
            </div>
))}



Checkbox check/uncheck not working properly with angularjs

I am working on a project where i am using a partial view in Asp.net MVC and in that partial view there is a html table and in the table header there is a checkbox on click of that checkbox all the checkboxes besides the table body data should be checked and if from table body data any checkbox is unchecked then top header checkbox should be also unchecked. This functionality is working with my current code but it is working only once second time if i uncheck top header checkbox and check it again and try to uncheck any table body data checkbox top header checkbox is not getting unchecked i am not able to figure out why this is not working

Here is my code

<table class="table table-condensed table-bordered table-hover left" style="width:100%;margin:0px;">
                        <thead>
                            <tr>
                                <th>
 <input type="checkbox" style="margin: 3px 0;" ng-model="IsAllChecked" ng-change="CheckUncheckAll(IsAllChecked)" ng-checked="isChecked"/>
                                </th>
                                <th><label>Name</label></th>
                                <th><label>City</label></th>
                                <th><label>Country</label></th>
                            </tr>
                        </thead>

                        <tr ng-repeat="clientData in $Clients.Clients| orderBy:'Name'|limitTo: totalDisplayed | filter: searchClient"
                            ng-mouseover="MouseOverOnUnassigned(clientData );" ng-mouseleave="MouseLeaveOnUnassigned(clientData)">

                            <td>
 
                                <input type="checkbox" ng-model="clientData.IsSelectedClients" ng-change="CheckUncheckHeader(clientData.IsSelectedClients)" />
                            </td>
                            <td></td>
                            <td></td>
                            <td></td>
                           
                        </tr>
                    </table>

And my angular js code

$scope.CheckUncheckHeader = function (checked) {
    $scope.isChecked = true;
    for (var i = 0; i < $scope.$Client.Clients.length; i++) {
        if (!$scope.$Client.Clients[i].IsSelectedClients) {
            $scope.isChecked = false;
            break;
        }
    };
};

$scope.CheckUncheckAll = function (IsAllChecked) {
    for (var i = 0; i < $scope.$Client.Clients.length; i++) {
        $scope.$Client.Clients[i].IsSelectedClients= IsAllChecked;
    }
};

Can anybody tell what is the best way to achieve this without failing. Thanks in advance




samedi 19 juin 2021

Unchecked input onClick on body

I have created a drop down menu with an input that I hide and a label, I would like to be able to set the input to unchecked even if I click outside. I tried to implement a logic with just console.log and I notice that my logic is not good as soon as I click on the input it is checked and unchecked as fast which makes that on the user side it does not open at all.

  mounted: function () {
let input = this.$refs.checkboxInput;
let body = document.querySelector("body");

input.addEventListener("click", (e) => {
  e.stopPropagation;
  console.log("listener on input with the onClick");
  if (this.$refs.checkboxInput.checked) {
    console.log("the menu is open");
  }
  body.addEventListener("click", (e) => {
    e.stopPropagation;
    console.log("close");
  });
}); 

},




vendredi 18 juin 2021

Cannot change visibility settings with onChange event in React app

In my React app component, I have a table with checkboxes. Below the table is a card that I want to display information based on the selected/clicked row. On load, its visibility is set to hidden.

<div className="card text-center" id="profileCard" style=>
...
</div>

I have added a function for the onChange event to display the card information based on the row that is checked.

const IndeterminateCheckbox = React.forwardRef(
    //This is the function for the checkboxes in page select
    ({ indeterminate, ...rest }, ref) => {
        const defaultRef = React.useRef()
        const resolvedRef = ref || defaultRef

        React.useEffect(() => {
            resolvedRef.current.indeterminate = indeterminate
        }, [resolvedRef, indeterminate])
        return (
            <>
                <input type="checkbox" ref={resolvedRef} {...rest} />
            </>
        )
    }
 )
  ....
 <div>
     <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} onChange={(e) => {
                            e.preventDefault();
                            showCard(e);}}
     />
 </div>

 ...
 
 const showCard = (e) => {
    if (e.target.checked) {
        document.getElementById("profileCard").visibility = "visible";
        e.preventDefault();
    } else {
        document.getElementById("profileCard").visibility = "hidden";
        e.preventDefault();
    }
};

What currently happens is that the box is checked, it goes into the showCard function and then sets the visibility of the element to "visible" (if I console.log() it in the debugger, it shows the changed visibility). But as soon as it comes out of the function, the checked box disappears and the card never displays as if the page has been completely reset. I have tried to add e.preventDefault() to fix this, but that doesn't seem to work. Any idea as to what I am doing incorrectly here or how to resolve this issue?

NOTE: I only included the relevant parts of the code to keep the focus on this one problem.




ASP.Net Core MVC checkbox alignment

Can someone please help with a problem I have with two checkboxes side by side. For some reason they don't line up with the rest of the controls and I have to specify a height or else the div has a height of zero. All the other controls align perfectly. I have attached a screen shot and my code. enter image description here

                    <div class="row align-items-start">
                        <div class="col-2">
                            <label asp-for="customer.MeasureLoft" class="col-form-label">M (Loft)</label>
                        </div>
                        <div class="col-2">
                            <label asp-for="customer.MeasureIWI" class="col-form-label">M (IWI)</label>
                        </div>
                        <div class="col-2">
                            <label asp-for="customer.MeasureUFI" class="col-form-label">M (UFI)</label>
                        </div>
                        <div class="col-2">
                            <label asp-for="customer.MeasureRIR" class=" col-form-label">M (RIR)</label>
                        </div>
                        <div class="col-4">
                            <label asp-for="customer.MeasureESH_FTCH" class="col-form-label">M (ESH/FTCH)</label>
                        </div>
                    </div>
                    <div class="row align-items-start">
                        <div class="col-2">
                            <input asp-for="customer.MeasureLoft" class="form-control" style="width:100px;" />
                        </div>
                        <div class="col-2">
                            <input asp-for="customer.MeasureIWI" class="form-control" style="width:100px;" />
                        </div>
                        <div class="col-2">
                            <input asp-for="customer.MeasureUFI" class="form-control" style="width:100px;" />
                        </div>
                        <div class="col-2">
                            <input asp-for="customer.MeasureRIR" class="form-control" style="width:100px;" />
                        </div>
                        <div class="col-4">
                            <input asp-for="customer.MeasureESH_FTCH" class="form-control" style="width:100px;" />
                        </div>
                    </div>
                    <div class="row align-items-start">
                        <div class="col-6">
                            <label asp-for="customer.Flex" class="col-form-label">Flex</label>
                        </div>
                        <div class="col-6">
                            <label asp-for="customer.HCRO" class="col-form-label">HCRO</label>
                        </div>
                    </div>
                    <div class="row align-items-start" style="height: 38px;">
                        <div class="col-6">
                            <input asp-for="customer.Flex" class="form-check-input" type="checkbox" />
                        </div>
                        <div class="col-6">
                            <input asp-for="customer.HCRO" class="form-check-input" type="checkbox" />
                        </div>
                    </div>



Checkbox Angular

I'm using angular and I'm not sure if problem is with it. So I have a checkbox, and when I click on it, it works, but when I need to choose another object and I need to click on it. It appears it (checkbox) has previous state. I need that if I choose another element to click on. It has default state (which is untick (false)).

.ts

show = false

toggleContract() {
   this.show = !this.show
}

.html

<p-checkbox  (click)='toggleContract()' [ngModel]="show"></p-checkbox>
<ng-container *ngIf="show"><ng-container />



jeudi 17 juin 2021

R/Shiny - Transfer checkbox labels to function field

I need the selected checkbox labels to fill in the "[,c("checkbox1","checkbox2")]" field (where both "checkbox1" and "checkbox2" are written). Thank you.

This is my code.

library(shiny) library(shinydashboard) library(shinyWidgets) library(readxl) library(tidyverse) library(readxl) library(stringr)

ui <- fluidPage(

br(),

fileInput("archive", "Upload file", accept = c(
    ".xlsx")),

    # Itens Selection
checkboxGroupInput("additem", "Select Items", choices = NULL)
    )
box(
    width = 2000,
    verbatimTextOutput("calfa")

)

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

    # Upload Data Sheet

csv <- reactive({
    req(input$archive)
    inFile <- input$archive
    df <- read_xlsx(inFile$datapath)
    return(df)
})

    #reactive value that will hold the name of the file
reactive_my_path <- reactive({
    # Test if file is selected
    req(input$archive)
    return(sub(".xlsx$", "", basename(input$archive$name)))
})

observe({
    input$archive
    # update the choices in input$additem
    updateCheckboxGroupButtons(session,
                               "additem",
                               paste('Column names in:', reactive_my_path()),
                               choices = names(csv()))
})

    # Alpha
output$calfa <-
    renderPrint({
        int<-csv()[,c("checkbox1","checkbox2")]
        int <- na.omit(int) 
        psych::alpha(int, check.keys = TRUE) 
    })

}

App

shinyApp(ui, server)




How to make a tkinter checkbox mandatory to check?

I want make a checkbox widget mandatory, so the user must enter data in it, otherwise don't proceed to next step.

How to do it with tkinter?




mercredi 16 juin 2021

¿Cómo habilitar o deshabilitar un confirmbutton a travez de un checkbox?

Estoy empezando a trabajar con los sweetAlert2 y estoy tratando de habilitar y deshabilitar un ConfirmButton a travez de un checkbox que esta antes, esto es lo que he intentado:

swal.fire({
            title: "¿Enviar formulario?",
            input: 'checkbox',
            inputPlaceholder: "Acepto que la toda información sea enviada.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'Si, confirmar',
            cancelButtonText: 'No, cancelar!',
            reverseButtons: true,
            onOpen: function (){
                swal2.disableConfirmButton();
                     },
        /* }, function(){ 
            $('.swal2-confirm').on('change', function (e) {
                e.preventDefault();
                val = this.checked;
                if (val) {
                    $(".swal2-confirm").attr('disabled', 'disabled'); 
                }else{
                    $(".swal2-confirm").attr('disabled', false); 
                }
            }) */
        }).then((result) => {
            if (result.isConfirmed) {
                if (resultAjax == true) {
                    Swal.fire(
                        dataPreregistro.data.message,
                        '',
                        'success'
                    )
                } else {
                    Swal.fire(
                        'Error:',
                        dataPreregistro.data.responseJSON.errors_msgs,
                        'error'
                    )
                }
            }
        })
    });

Cómo tal estoy tratando de que la alerta lance deshabilitado el confirmButtton y yo acepte el uso de la información a travez de un checkbox y una vez que yo marque el checkbox se habilite el boton de confirmar.

Gracias por leerme.




How can I set checkbox checked outside modalbox via jQuery

I have a form on that form I have some textbox, buttons, radio button and one checkbox.

On one button's click the modal box will appear on screen and model will contain 2 button and 3 input.

When model open the overlay will grey out the background.

When we click one of the button on model I need to set checkbox checked on form behind modal overlay but unable to set it via jQuery.




I am having trouble with argument type 'void Function(bool)' can't be assigned to the parameter type 'void Function(bool?)?'

Below is my attempt to make a checkBox widget and used Bool, but when trying to run this function which I created with parameter bool. but this is the error I get

  • The argument type 'void Function(bool)' can't be assigned to the parameter type 'void Function(bool?)?'.

I tried looking for a solution dint find any. thanks in advance

import "package:flutter/material.dart" ;

void main() {
   runApp(new MaterialApp(
     home: new Baseapp(),
   ));
}

class Baseapp extends StatefulWidget{
  @override
  _State createState() => new _State();
}
class _State extends State<Baseapp> {
  bool _value1  = false;
  bool _value2 = false;
  void _value1Changed(bool value) =>   setState(() => _value1 = value);
  void _value2Changed(bool value) =>   setState(() => _value2 = value);


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar:  new AppBar(
        title :  new  Text("NAME HERE", style :TextStyle(color:Colors.black)),
        backgroundColor: Colors.yellow ,
      ),
      body: new Container(
      padding :   new EdgeInsets.all(20),
        child: new Center(
          child: new Column(
            children:<Widget>[
             new  Checkbox(value: _value1, onChanged:_value1Changed),
             new CheckboxListTile(value: _value2, onChanged:_value2Changed )
            ],
          ),
        ),
      ),
    );
  }
}



Check/Uncheck all checkbox on different page

I'm trying to get, by checking or unchecking one checkbox, in order to check/uncheck all checkboxes called by data-ajax-source.

actually i can check/uncheck all checkboxes on the current page but my list is based on several pages.

I do have make a lot research but nothing work for me.

My th :

<table id="someid" class="data display datatable" data-sort="[[1, 'asc']]" data-ajax-source="">
<thead>
    <tr>
        <th class="no_sort"><input type="checkbox" name="check_all" value="check_all" checked /></th>
        <th width="15%">firstname</th>
        <th width="15%">lastname</th>
        <th width="55%">Email(s)</th>
        <th class="no_sort" width="10%">Blacklist ?</th>
    </tr>
</thead>

data :

<input type="checkbox" name="element-ids[]" value="" checked />

<div></div>

<div></div>

<div>
    
</div>

JQuery code :

$('form table input[name="check_all"]').on('change', function() {
    $(this).closest('table').find('input[type="checkbox"]:not(:disabled)').prop('checked', $(this).prop('checked'));
});

In the html, i think each page is equal to a different table element, that is why i can not select/deselect one checkbox to check/uncheck all checkboxes on all pages. Because when i change page, the "main" checkbox is always checked by default as i have set.

so what can i change to reach my goal ?

Thanks a lot in advance.




Is it possible to call the checkbox function in a view to another view? So if one is checked, the statement shows

I would like to call a statement from another view, which if i click the print report, the statement show if I clicked like this the print button call function of these

And this is my view page which give options

the first view code

<label class="radio-inline">
<input type="checkbox" value="up" name="stats" >Naik kelas
</label>
<label class="radio-inline">
<input type="checkbox" value="stay" name="stats" >Tidak Naik kelas
</label>

And this is the printreport view enter image description here This code is used to call from first view to this view. So if we click which value is up, as i mentioned in first image, it shows statement in the button.

<?php if (isset($_POST['stats']) == 'up') { ?>
<br>Naik Ke Kelas ............... (.....) atau Tinggal di Kelas ............... (.....)</td>
<?php } ?>

However, the output did not called even I clicked or not as in this picture. I try using in my view using isset did not worked. enter image description here

and this is my controller controller to access print report

Anyone know how to solve it so the statement is appeared if selected one?




How to use checkbox in a form to select one or multiple choices from database?

I have this problem, where I would like to select one or more choices based on what is in the database, but I don't know how to do it. Below I will attach a code similar to the one from the search inputs only that I modified the first 3 lines under "isset" in the hope that maybe it will work, and I would like to know if I could make the code in such a way as to modify it and to work at checkboxes as well.

job-list.php (the form)

        <form action="../pages/jobs-list.php" method="POST">
            <div class="job-listing sidebar-container pr-3 pl-3 pt-2 pb-2" style="box-shadow: none; transform: none">

                <!-- Exceperience level -->
                <div class="sidebar-widget pt-2 ">
                    <h3 class="text-center" style="color: #2a41e8;"><b>Experiența de muncă</b></h3>
                    
                    <div class="switches-list">
                        <div class="switch-container" name>
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="Stagiar"><span class="switch-button"></span> Stagiar</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="Internship"><span class="switch-button"></span> Internship</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="Junior"><span class="switch-button"></span> Junior ( < 2 ani)</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="Middle"><span class="switch-button"></span> Middle (2 < 5 ani)</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="Senior"><span class="switch-button"></span> Senior ( > 6 ani)</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-experience[]" value="ManagerLeader"><span class="switch-button"></span> Manager/ Leader</label>
                        </div>
                    </div>
                </div>
                
                <!-- Job Types -->
                <div class="sidebar-widget">
                    <h3 class="text-center" style="color: #2a41e8;"><b>Tipul jobului</b></h3>

                    <div class="switches-list">
                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-jobType[]"><span class="switch-button"></span> Full Time</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-jobType[]"><span class="switch-button"></span> Part Time</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-jobType[]"><span class="switch-button"></span> Freelance</label>
                        </div>

                        <div class="switch-container">
                            <label class="switch"><input type="checkbox" name="search-jobType[]"><span class="switch-button"></span> Temporary</label>
                        </div>
                    </div>
                </div>

                <div class="text-center">
                    <button type="submit" name="submit-search-left" class="button ripple-effect pb-1 pt-1" onclick="window.location.href='../pages/jobs-list.php'">Caută</button>
                </div>
            </div>              
        </form>

job-list.php (the php)

                else if(isset($_POST['submit-search-left'])) {
                    $searchexperience = mysqli_real_escape_string($conn_search, $_POST['search-experience']);
                    $searchjobType = mysqli_real_escape_string($conn_search, $_POST['search-jobType']);
                    $sql = "SELECT * FROM article WHERE (a_experience LIKE '%$searchexperience%') AND(a_jobType LIKE '%$searchjobType%'";
                    $result = mysqli_query($conn_search, $sql);
                    $queryResult = mysqli_num_rows($result);

                    echo "<p class='alert alert-info mb-4 text-center col-12' style='color: blue;'><b>S-au găsit ".$queryResult." rezultate!</b></p>";

                    if($queryResult > 0) {
                        while($row = mysqli_fetch_assoc($result)) {
                            
                            echo"<a href='../pages/jobs-list/php?title=".$row['a_title']."&date=".$row['a_author']."'><div class='freelancer'>

                                <div class='freelancer-overview pr-0 pb-0 pt-0'>
                                    <div class='freelancer-overview-inner'>
                                        <!-- Bookmark Icon -->
                                        <span class='bookmark-icon'></span>
                                        
                                        <!-- Avatar -->
                                        <div class='freelancer-avatar'>
                                            <a href='single-freelancer-profile.html'><img src='' alt=''></a>
                                        </div>

                                        <!-- Name -->
                                        <div class='freelancer-name height_200'>
                                            <h4 class='pt-3'><a href='../pages/person-profile.php' class='noHoverBlueLine'>".$row['a_author']."</a></h4>
                                            <span>".$row['a_title']."</span>
                                            <p class='font-14 line-height-1_6 pr-3'>".$row['a_text']."... <a href='../pages/person-profile.php' class='readMore2'>Read more</a></p>
                                        </div>
                                    </div>
                                </div>

                                <!-- Details -->
                                <div class='freelancer-details noHoverBlue-a pr-3'>
                                    <div class='freelancer-details-list'>
                                        <ul>
                                            <li>Tip Job <strong class='pt-1';><i class='fas fa-clock'></i> ".$row['a_jobType']."</strong></li>
                                            <li><span style='padding-left: 5px;'>Locația</span><strong><i class='icon-material-outline-location-on'></i> ".$row['a_city']."</strong></li>
                                            <li>Nivel Pregătire <strong class='pt-1 pl-2';><i class='fas fa-user-graduate'></i> ".$row['a_experience']."</strong></li>
                                        </ul>
                                    </div>
                                    <div class='col-lg-9 col-md-6 pr-4' id='view-profile'>
                                        <a href='../pages/person-profile.php' class='noHoverBlueLine button button-sliding-icon ripple-effect'>View Profile <i class='far fa-long-arrow-alt-right'></i></a>
                                    </div>
                                </div>
                            </div></a>";
                        }
                    } else {
                        echo "Nu s-au găsit rezultate bazat pe ceea ce ai căutat!";
                    }
                }

Below I will attach the code from the search inputs to see from where I got the code I tried to modify it to make the checkbox version work(the code above).

if(isset($_POST['submit-search'])) {
                    $searchjob = mysqli_real_escape_string($conn_search, $_POST['search-job']);
                    $searchcity = mysqli_real_escape_string($conn_search, $_POST['search-city']);
                    $sql = "SELECT * FROM article WHERE (a_title LIKE '%$searchjob%' OR a_author LIKE '%$searchjob%' OR a_experience LIKE '%$searchjob%' OR a_jobType LIKE '%$searchjob%') AND a_city LIKE '%$searchcity%'";
                    $result = mysqli_query($conn_search, $sql);
                    $queryResult = mysqli_num_rows($result);

                    echo "<p class='alert alert-info mb-4 text-center col-12' style='color: blue;'><b>S-au găsit ".$queryResult." rezultate!</b></p>";

                    if($queryResult > 0) {
                        while($row = mysqli_fetch_assoc($result)) {
                            
                            echo"<a href='../pages/jobs-list/php?title=".$row['a_title']."&date=".$row['a_author']."'><div class='freelancer'>

                                <div class='freelancer-overview pr-0 pb-0 pt-0'>
                                    <div class='freelancer-overview-inner'>
                                        <!-- Bookmark Icon -->
                                        <span class='bookmark-icon'></span>
                                        
                                        <!-- Avatar -->
                                        <div class='freelancer-avatar'>
                                            <a href='single-freelancer-profile.html'><img src='' alt=''></a>
                                        </div>

                                        <!-- Name -->
                                        <div class='freelancer-name height_200'>
                                            <h4 class='pt-3'><a href='../pages/person-profile.php' class='noHoverBlueLine'>".$row['a_author']."</a></h4>
                                            <span>".$row['a_title']."</span>
                                            <p class='font-14 line-height-1_6 pr-3'>".$row['a_text']."... <a href='../pages/person-profile.php' class='readMore2'>Read more</a></p>
                                        </div>
                                    </div>
                                </div>

                                <!-- Details -->
                                <div class='freelancer-details noHoverBlue-a pr-3'>
                                    <div class='freelancer-details-list'>
                                        <ul>
                                            <li>Tip Job <strong class='pt-1';><i class='fas fa-clock'></i> ".$row['a_jobType']."</strong></li>
                                            <li><span style='padding-left: 5px;'>Locația</span><strong><i class='icon-material-outline-location-on'></i> ".$row['a_city']."</strong></li>
                                            <li>Nivel Pregătire <strong class='pt-1 pl-2';><i class='fas fa-user-graduate'></i> ".$row['a_experience']."</strong></li>
                                        </ul>
                                    </div>
                                    <div class='col-lg-9 col-md-6 pr-4' id='view-profile'>
                                        <a href='../pages/person-profile.php' class='noHoverBlueLine button button-sliding-icon ripple-effect'>View Profile <i class='far fa-long-arrow-alt-right'></i></a>
                                    </div>
                                </div>
                            </div></a>";
                        }
                    } else {
                        echo "Nu s-au găsit rezultate bazat pe ceea ce ai căutat!";
                    }
                }



Angular Reactive Form Select multiple selected values to Checkbox

The form is having 1 textbox , 1 radio button and 1 multi select Checkbox The HTML template is like below

        <form  *ngIf="notificationSettings | async; else loading"
              [formGroup]="notificationForm" (ngSubmit)="onSubmit()">
              
          <div class="form-group">        
            <div *ngFor="let option of notifyBackAlertOptions; let i=index">
              <input type="checkbox" class="form-check-input" [value]="option.value" (change)="onNotifyBackCheckboxChange($event)"  />
              <label>  </label>
            </div>
          </div>
          <div class="form-group">
            <label for="notifyBackEmail">Where shall we send the alerts?</label>
            <input type="email" class="form-control" formControlName="notifyBackEmail">
          </div>
          
          <div class="form-check" *ngFor="let option of discontinuedAlertOptions;">
            <label>
              <input formControlName="discontinuedOption" class="form-check-input"
                     type="radio"
                     name="discontinuedOption"
                     [value]="option.value" />
              
            </label>
          </div>

          <div class="float-left">
            <button class="btn btn-primary mr-1">Update</button>        
          </div>

        </form>

        <ng-template #loading>
          Loading ---...
        </ng-template>
        

The component is like below

    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';


    export class NotifcationsComponent implements OnInit {
      
      notificationSettings: Observable<NotificationSetting>;
      notificationForm: FormGroup;
      submitted = false; 
      
      notifyBackAlertOptions = [
        { name: 'Option 1', value: '1' },
        { name: 'Option 2', value: '2' },
        { name: 'Option 3', value: '3' }, 
        { name: 'Option 4', value: '4' }    
      ];
      discontinuedAlertOptions = [
        { name: 'Yes for any', value: '1' },   
        {name: 'Yes for all', value: '2' },
        { name: 'No', value: '3' }
      ];   

      constructor(private formBuilder: FormBuilder,private userService: UserService)  { }

      ngOnInit() {

        this.getCurrentSettings(); 
        this.notificationForm = this.formBuilder.group({
          notifyBackEmail: [''], 
          discontinuedOption: [''],   
          notifyBackOptions: new FormArray([]),
        });
        
        
      }

      getCurrentSettings(): void {

         //https://coryrylan.com/blog/using-angular-forms-with-async-data
         this.notificationSettings = this.userService
          .getUserNotificationSettings()
          .pipe(tap(data => this.notificationForm.patchValue(data)));
          
          //This code maps / sets the values of textbox and radio buttons correctly at page loading based on response from API. But not setting values for multiselect checkbox       
         //How to set the notifyBackOptions checkbox selected values marked as checked 
      }

      // convenience getter for easy access to form fields in HTML page 
      get f() { return this.notificationForm.controls; }
     

      onNotifyBackCheckboxChange(e) {
        const notifyBackOptions: FormArray = this.notificationForm.get('notifyBackOptions') as FormArray;

        if (e.target.checked) {
          notifyBackOptions.push(new FormControl(e.target.value));
        } else {
          let i: number = 0;
          notifyBackOptions.controls.forEach((item: FormControl) => {
            if (item.value == e.target.value) {
              notifyBackOptions.removeAt(i);
              return;
            }
            i++;
          });
        }
      }


      onSubmit() {
        this.submitted = true; 
        // stop here if form is invalid
        if (this.notificationForm.invalid) {
          return;
        }
        console.log(this.notificationForm.value);        
      }

       

    }
    

The HTML is rendering correctly and capturing the values at form submission . At load time of the component i have to read the values from API endpoint and prefill form based on current settings

The JSON response from API endpoint is like below

    {
    notifyBackEmail: "email@email-domain.in"
    notifyBackOptions: ["1","2"]
    discontinuedOption: "1"
    }

The existing implementation of getCurrentSettings() is setting values of radio and textbox but not checkbox. How can i set the Checkbox values as selected




Vue.js - checkbox on and off won't trigger change event using jquery

I have two components: Modal and Checkbox. I want turn off the checkbox when the button in the modal (dialogue box) is clicked. The jquery code used in modal to control checkbox is given below. The checkbox is turned off successfully but change event of checkbox is not triggered.

$(`#${btn.changeToggleValue.toggleId}`).prop("checked", false);



mardi 15 juin 2021

Jquery - Find closest previous

I need to find the previous and closest element (".table-primary") to the td that contain the input ("checkbox").

If i check the checkbox inside the "David" row it should find the "Patricia" row element.

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <title>Hello, world!</title>
</head>

<body>
  <div class="container">
    <table class="table table-sm">
      <thead>
        <tr>
          <th scope="col" style="max-width: 36px;"></th>
          <th scope="col">Name</th>
          <th scope="col">Surname</th>
          <th scope="col">Work</th>
          <th scope="col">Country</th>
          <th scope="col">Birthday</th>
          <th scope="col">Hobbyes</th>
        </tr>
      </thead>
      <tbody>
        <tr class="table-primary">
          <td class="docRow"><input class="form-check-input" type="checkbox"></td>
          <td class="name">Mark</td>
          <td class="surname">White</td>
          <td class="work">Lawyer</td>
          <td class="country">USA</td>
          <td class="birthday">26/05/1993</td>
          <td class="hobbyes">Tennis, Music</td>
        </tr>
        <tr>
          <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
          <td class="childname">Laura</td>
          <td class="childage">5</td>
          <td colspan="4"></td>
        </tr>
        <tr>
          <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
          <td class="childname">Maurice</td>
          <td class="childage">10</td>
          <td colspan="4"></td>
        </tr>
        <tr>
          <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
          <td class="childname">Bryan</td>
          <td class="childage">2</td>
          <td colspan="4"></td>
        </tr>
        <tr class="table-primary">
          <td class="docRow"><input class="form-check-input" type="checkbox"></td>
          <td class="name">Patricia</td>
          <td class="surname">Mallon</td>
          <td class="work">Manager</td>
          <td class="country">Germany</td>
          <td class="birthday">05/07/1976</td>
          <td class="hobbyes">Mode, Cooking, Reading</td>
        </tr>
        <tr>
          <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
          <td class="childname">David</td>
          <td class="childage">8</td>
          <td colspan="4"></td>
        </tr>        
        <tr class="table-primary">
          <td class="docRow"><input class="form-check-input" type="checkbox"></td>
          <td class="name">Wuei</td>
          <td class="surname">Zong</td>
          <td class="work">Marketing</td>
          <td class="country">China</td>
          <td class="birthday">01/01/1945</td>
          <td class="hobbyes">Bricolage, Manual Work, Sleep</td>
        </tr>
        <tr>
          <tr>
            <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
            <td class="childname">Philips</td>
            <td class="childage">12</td>
            <td colspan="4"></td>
          </tr>
          <tr>
            <td class="fileRow"><input class="form-check-input" type="checkbox"></td>
            <td class="childname">Alice</td>
            <td class="childage">22</td>
            <td colspan="4"></td>
          </tr> 
        </tr>
      </tbody>
    </table>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
    crossorigin="anonymous"></script>

</body>

</html>

I have already tried using closest() e prev(). But it doesn't seem to work, I don't understand why.