mardi 31 mars 2020

Disable dropdown if checkbox is checked in reactjs using typescript

I have disabled the dropdown by default. The dropdown should be enabled only when the checkbox is checked. Please let me know, what is the best approach for this. I using reactjs app and coding done in typescript.




Get data back from object into form

In a Chrome extension i save user input (checked checkboxes) - it works and looks like:

function save_checkboxes() {
    const form = document.forms['cbx'];
    const data = Object.fromEntries(new FormData(form).entries());
/*     console.log(data); */
    chrome.storage.sync.set({
        savedCheckboxes: data
    }, function () {
/*         console.log(data); */
    });
}
document.getElementById("save_checkboxes").addEventListener("click", save_checkboxes);

Than i want to restore saved data, so the user get his checked checkboxes back until doing new choice. I try it on this way:

function restore_checkboxes() {
    chrome.storage.sync.get(['savedCheckboxes'], function (entries) {
console.log(Object.entries(entries.savedCheckboxes));

/*stumble, stumble, stumble*/

    )}
    }

This console.log displays already an array with saved values, which are IDs of checked checkboxes, like on screenshot:

enter image description here

My question: how can i put values back into previously checked checkboxes?




Passing and printing checkboxes values JSON

I'm trying to create a CV-like generator with radiobuttons, input texts and checkboxes. I created 2 views/states. The 1st view is when the user inputs the values, and the 2nd view only prints the selected values. Until now, I managed to print the text input from the user and the selected value from the radio button, but I can't seem to find a way to pass the checkbox (checked: true) and print it.

Here's my code until now:

1st view (home state):

<ion-view view-title="Hello App">
  <ion-pane>
    <ion-header-bar class="bar-stable">
      <h1 class="title">CV test</h1>
    </ion-header-bar>
    <ion-content>

      <li class="item">Input your name</li>
      <div class="list list-inset">
        <label class="item item-input">
          <input type="text" placeholder="Insert your name and last name" ng-model="username.name">
      </div>

      <li class="item">Higher degree of education obtained</li>
      <div class="list">
        <div class="item item-divider">
                     Selected Value: 
     </div>
     <ion-radio ng-repeat="item in mobileappsList"
                              ng-value="item.value"
                              ng-model="data.mobileapp">
                     
      </ion-radio>

      </div>

      <li class="item">Skills</li>
      <div class="list">

<ion-checkbox ng-repeat="item in skills" ng-model="item.checked" ng-value="item.checked">
           
        </ion-checkbox>

      </div>

      <button class="button button-block button-positive" ng-click="click()"> <!--button to let the user click and take some action -->
    Submit
    </button>

    </ion-content>
  </ion-pane>
</ion-view>

2nd view (submit state):

<ion-view view-title="Submit CV">
  <ion-content>
    <h1 class="title">Data submitted</h1>

    <h3 class="title">Name:</h3>
      <div class="item item-text-wrap">
      
    </div>

    <h3 class="title">Education:</h3>
      <div class="item item-text-wrap">
      
    </div>

    <h3 class="title">Skills:</h3>
      <div class="item item-text-wrap">
      
    </div>

</ion-content>
</ion-view>

3rd view (app.js):

var myapp = angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {

    if (window.cordova && window.Keyboard) {
      window.Keyboard.hideKeyboardAccessoryBar(true);
    }

    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})


myapp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider

  .state('home', {
    url: '/home',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl',
    params: {
      name: '',
      mobileapp: '',
      skills: ''
    }
  })

  .state('submit', {
    url: '/submit/:name'+':data'+':',
    templateUrl: 'templates/submit.html',
    controller: 'SubmitCtrl',
  })



$urlRouterProvider.otherwise('/home');



});

myapp.controller('HomeCtrl', function($scope, $state) {

  $scope.username={name: ""};

  $scope.supers={skills: ""};


    $scope.skills= [
       { text: "Programming", checked: true },
       { text: "Problem-solving skills", checked: false },
       { text: "Leadership", checked: false },
       { text: "IS management", checked: false },
       { text: "Communicator", checked: false }
     ];

    $scope.data = {mobileapp: ""};

    $scope.mobileappsList = [
      { text: "High school", value: "HS" },
      { text: "Bachelor", value: "BA" },
      { text: "Master", value: "MA" }
    ];
$scope.click = function(){
  $state.go('submit', {name:$scope.username.name, data:$scope.data.mobileapp, supers:$scope.supers.skills});
}

});


myapp.controller('SubmitCtrl', function($scope, $stateParams) {
console.log($stateParams);
$scope.name = $stateParams.name;
$scope.data = $stateParams.data;
$scope.supers = $stateParams.supers;


});

As you can see, I want to pass the pass and print the "Programming" text/value.

Thanks




Formatting checkboxes with Bootstrap in Rails form erb?

I'm using multiple check boxes in my Rails views form. I'm using Bootstrap 4 for styling. If there is a Bootstrap style for checkboxes like:

<div class="input-group mb-3">
  <div class="input-group-prepend">
    <div class="input-group-text">
      <input type="checkbox" aria-label="Checkbox for following text input">
    </div>
  </div>
  <input type="text" class="form-control" aria-label="Text input with checkbox">
</div>

<div class="input-group">
  <div class="input-group-prepend">
    <div class="input-group-text">
      <input type="radio" aria-label="Radio button for following text input">
    </div>
  </div>
  <input type="text" class="form-control" aria-label="Text input with radio button">
</div>

how do I implement multiple class stylings into an erb object? Here is the code I'm trying to implement:

            <%= f.collection_check_boxes(:authorization_ids, Authorization.all, :id, :auth_name, { checked: @account.try { |a| a.authorization_ids.map(&:to_param) } }, multiple: true, # WOULD LIKE TO IMPLEMENT BOOTSTRAP CLASSES HERE ) %>
        <%= f.label :authorization_ids, 'Authorizations' %>




R Shiny Leaflet - how to make a CheckboxGroup for binary data

I posted a similar question here: How do I create a Leaflet Proxy in observeEvent() for checkboxGroup in R Shiny . But I'm a little desperate for answers, so I thought I'd rephrase my question and post it again. I've scoured the internet for answers and can't seem to find what I'm looking for. Apologies for the double posting.

Here's my issue. I have a dataset here: https://github.com/mallen011/Leaflet_and_Shiny/blob/master/Shiny%20Leaflet%20Map/csv/RE.csv

It's recycling centers in Kentucky. It's set up so each recyclable material is a column, and each row i.e. recycling center is listed as yes/no as to whether each center actually recycles said material. Here's an example of what the data looks like, in case you can't access the csv. Top row is the header column. Sorry for the formatting:

  • Name___________________GL______AL_____PL
  • Bath Community Recycling___Yes_____No____Yes
  • Ted & Sons Scrap Yard______No______No____Yes

Now I have the csv visualized on a R shiny dashboard app like here using Leaflet: https://github.com/mallen011/Leaflet_and_Shiny/blob/master/Shiny%20Leaflet%20Map/re_map.png But I want to add a control in which users can filter through where they can recycle their goods, namely, I want to use checkboxGroupInput() in R shiny so users can check materials and have recycling centers populate the map. For example, if a person wants to know where to recycle their glass, they can check "glass" in the checkbox group, and all recycling centers that allow glass recycling pop up.

So in R Shiny, I've read my recycling data csv (RE.csv):

RE <- read.csv("C:/Users/username/Desktop/GIS/Shiny Leaflet Map/csv/RE.csv")

RE$y <- as.numeric(RE$y)
RE$x <- as.numeric(RE$x)

RE.SP <- SpatialPointsDataFrame(RE[,c(7,8)], RE[,-c(7,8)])

Here's my UI that puts the checkboxGroupInput() in the sidebar():

ui <- dashboardPage(
  skin = "blue",
  dashboardHeader(titleWidth = 400, title = "Controls"),
  dashboardSidebar(width = 400
                  #here's the checkboxgroup, it calls the columns for glass, aluminum and plastic from the RE.csv, all of which have binary values of yes/no
                  checkboxGroupInput(inputId = "RE_check", 
                                     label = h3("Recycleables"), 
                                      choices = list("Glass" = RE$GL, "Aluminum" = RE$AL, "Plastic" = RE$PL),
                                      selected = 0)
                   ),
  dashboardBody(
    fluidRow(box(width = 12, leafletOutput(outputId = "map"))),
    tags$style(type = "text/css", "#map {height: calc(100vh - 80px) !important;}"),
    leafletOutput("map")
  )
)

And now for the trouble I'm having: What do I put into my server so it observes each of these events? This is what I have for the event in which a user checks "glass", and I have no idea how wrong or how right it is. I just know it's not working. I'm trying to use "if" statements, so only values that equal "yes" populate the map. But currently, the map in the dashboard is blank no matter what I do, although the checkbox group input seems to work.

server <- function(session, input, output) {
 observeEvent({
    RE_click <- input$map_marker_click
    if (is.null(RE_click))
      return()

    if(input$RE$GL == "Yes"){
      leafletProxy("map") %>% 
        clearMarkers() %>% 
        addMarkers(data = RE_click,
                   lat = RE$y,
                   lng = RE$x)
      return("map")
    }
  })

Here's my output leaflet map too, in case that matters:

 output$map <- renderLeaflet({
    leaflet() %>% 
      setView(lng = -83.5, lat = 37.6, zoom = 8.5)  %>% 
      addProviderTiles("Esri.WorldImagery") %>% 
      addProviderTiles(providers$Stamen.Toner, group = "Toner") %>% 
      addPolygons(data = counties,
                  color = "green",
                  weight = 1,
                  fillOpacity = .1,
                  highlight = highlightOptions(
                    weight = 3,
                    color = "green",
                    fillOpacity = .3)) %>% 
      addMarkers(data = RE,
                 lng = ~x, lat = ~y, 
                 label = lapply(RE$popup, HTML),
                 group = "recycle",
                 clusterOptions = markerClusterOptions(showCoverageOnHover = FALSE)) %>% 
    addLayersControl(baseGroups = c("Esri.WorldImagery", "Toner"),
                     overlayGroups = c("recycle"),
                     options = layersControlOptions(collapsed = FALSE))
  })
}

I'm new to R Shiny if that's not obvious. I'd really appreciate any and all help. All my code is publicly available on my GitHub for download: https://github.com/mallen011/Leaflet_and_Shiny

Thanks and stay safe!




Checkbox content color can't be set in UWP

I'm trying to change the color of a checkbox content. I want the color t change, if the box is checked, but I cannot even change it in the XAML.

<CheckBox x:Name="Checkbox" Foreground="White" Content="I agree" HorizontalAlignment="Left" Margin="50,480,0,0" VerticalAlignment="Top" Height="46" Width="938" FontFamily="Arial" Checked="Checkbox_Checked" Background="#FF009FE3" />

But the content color keeps showing in black. Where is my mistake? Sounds like a simple thing, but I couldn't find any solution out there. I'm new to UWP, what doesn't make it easier as well.




How to make checkbox select, de-select and sellect all in List?

How to select all checkbox ? and if i unselect any checkbox in list then how to remain all selected checkboxes rather than unselect checkbox ?

class SelectAllCheckbox extends StatefulWidget {
  @override
  _SelectAllCheckboxState createState() => _SelectAllCheckboxState();
}

class _SelectAllCheckboxState extends State<SelectAllCheckbox> {
  List _selecteCategorysID = List();
  bool rememberMe = false;
  List<String>userList=['Sam','John','Rohan','Peter'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body:  Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(left: 20, right: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("Select All"),
                Checkbox(
                    value: rememberMe,
                    onChanged: _onRememberMeChanged
                )
              ],
            ),
          ),
          SizedBox(
            height: 450,
            child: ListView.builder(
                itemCount: userList.length,
                itemBuilder: (context, item) {
                  return Card(
                      child: CheckboxListTile(
                        selected: false,
                        value: _selecteCategorysID.contains(userList[item]),
                        onChanged: (bool selected) {
                          _onCategorySelected(selected, userList[item]);
                        },

                        title: Text(userList[item]),
                      ));
                }),
          ),
        ],
      ));
  }

Logic code

  1. this is code for selecting and deselecting single checkbox
  2. it is possible to select all check boxes in this logic

List item

 void _onCategorySelected(bool selected, category_id) {
    if (selected == true) {
      setState(() {
        _selecteCategorysID.add(category_id);

      });
    } else {
      setState(() {
        _selecteCategorysID.remove(category_id);

      });
    }
  }

Logic code

this is for Select All check box

  void _onRememberMeChanged(bool newValue) => setState(() {
    rememberMe = newValue;

    if (rememberMe) {

      // TODO: Here goes your functionality to select all checkbox
    } else {

    }
  });
}



Gravity forms: checkboxes loaded by AJAX get unchecked on bad validation

Using Gravity Forms, the checkboxes are loaded by AJAX based on the value of a dropdown. All works fine. However, when the form is submitted and is invalid (eg. 1 required field left empty), all check boxes get unchecked.

I use $(document).on('gform_post_render', function( ) {} to re-load the checkboxes again after bad validation.

So the question is, how can I keep the checkboxes that where checked, checked?

I haven't found any example or solution concerning this issues. No errors in the console. Checkboxes loaded by Gravity forms stay checked on bad validation.

Any ideas?




lundi 30 mars 2020

Angular 9: Disable label checkbox (not the box)

I need to make clickable a piece of the checkbox label (Privacy Policy). This is the snippet:

    <div>
      <mat-checkbox required formControlName="privacyCheck" [checked]="false">
        <b style="color: crimson">*</b>Accetto la
        <i style="color: #770E0E" (click)="printDebug()">privacy policy</i>
        e i termini di condizione dell'utilizzo del servizio.
      </mat-checkbox>
    </div>

At the moment, if i click on the italic text ("privacy policy"), i got the printDebug but of course the checkbox will be setted to "checked".

I tried several solutions using CSS property pointer-events: none !important; on .mat-checkbox-layout .mat-checkbox-label span, .mat-checkbox-layout .mat-checkbox-label, and so on.


enter image description here

enter image description here




How to create a nested Form of separate model with many_to_many relationship in Rails?

Need to create one form with entries for 2 different models and establish a join table relationship.

Models:

class Account < ApplicationRecord
    has_many :account_authorizations
    has_many :authorizations, through: :account_authorizations
    accept_nested_attributes_for :authorizations

end
class Authorization < ApplicationRecord
    has_many :account_authorizations
    has_many :accounts, through: :account_authorizations
end
class AccountAuthorization < ApplicationRecord
    belongs_to :account 
    belongs_to :authorization 
end

Model authorization already has several instances in my DB. There are only 2 attributes for authorization: auth_name and id.

My form initializes with Account. Within this form, I need to have several checkboxes for Authorization entries. I understand fields_for when using a related model but unclear how to implement the check_box method here and capture the values.

Here's what my views page looks like so far:

<% states = [ 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PA' 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT' 'VA', 'WA', 'WV', 'WI', 'WY'] %>
<% ppu = ['Employment', 'Insurance', 'Law Enforement'] %>

<div class="row justify-content-center">
    <div class="col-lg-16">
        <h3>Create New Account</h3>
    </div>
</div>
<div class="row justify-content-center">
    <div class="col-lg-16">

            <%= form_with(url: accounts_path, model: @paraaccount, local: true) do |f| %>

            <%= f.text_field :account_name, class: "form-control", placeholder: "Account Name" %>
            <%= f.text_field :account_address_line1, class: "form-control", placeholder: "address line 1" %>
            <%= f.text_field :account_address_line2, class: "form-control", placeholder: "address line 2" %>
            <%= f.text_field :account_address_city, class: "form-control", placeholder: "account city" %>
            <%= f.select :account_address_state, options_for_select(states), { :prompt => true }, class: "form-control", include_blank: true, placeholder: "state" %>
            <%= f.text_field :account_address_zipcode, class: "form-control", placeholder: "account zipcode" %>
            <%= f.text_field :contact_first_name, class: "form-control", placeholder: "contact first name" %>
            <%= f.text_field :contact_last_name, class: "form-control", placeholder: "contact last name" %>
            <%= f.text_field :contact_phone, class: "form-control", placeholder: "conact phone" %>
            <%= f.text_field :contact_email, class: "form-control", placeholder: "contact email" %>
            <%= f.select :account_ppu, options_for_select(ppu), { :prompt => true }, class: "form-control", include_blank: true, placeholder: "ppu" %>
            <%= f.text_area :account_notes, class: "form-control", placeholder: "Notes..." %>

            <div class="d-flex justify-content-between flex-wrap">
             <%= f.fields_for :authorization do |auth| %> 
            <div class="order-3 p-2 bd-highlight">
                    # THIS IS WHERE I'M CONFUSED
                <%= auth.label #need to get attribute `auth_name` for the label here %>
                <%= auth.check_box #need to implement checkboxes here for each entry in `Authorizations` %>
            </div>
            <% end %>
             </div>
            <%= f.submit "Create", class: 'btn btn-success' %>
            <% end %>



    </div>
</div>

I need to capture the values of the checked boxes and use id of Authorization in params to create a join table relationship to Account on creation of the new Account instance.

Hope this makes sense.




inserting checkbox information into a sqlite3 database table

I'm trying to create a forum application using Python.

when a new username signs up for the forum I ask him to select the subjects that interest him, and he would like to receive information about, here's an example of one subject checkbox:

nut = IntVar()
nutrition_photo = PhotoImage(file="nutrition.gif")
nutrition_photo = nutrition_photo.subsample(4,4)
nutrition_RB = Checkbutton(scrollable_frame,text="Nutrition" ,image = nutrition_photo, 
compound="top", bg="light goldenrod", variable = nut)
nutrition_RB.grid(row=0, column=0)

I tried to create a database table using sqlite3 that contains all of the subjects's preferences of each user (if he chose the subject the cell will contain the value 1, and if he didn't it will contain the value 0):

connection = sqlite3.connect('subjects_info.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS subjects(
            nutrition INTEGER,
            cooking INTEGER,
            sport INTEGER,
            music INTEGER,
            health INTEGER,
            traveling INTEGER,
            tv INTEGER,
            art INTEGER,
            economics INTEGER,
            fashion INTEGER,
            history INTEGER,
            literature INTEGER,
            philosophy INTEGER,
            technology INTEGER,
            diy INTEGER)
            """)

each time a user tries to sign up for the app his selected subjets will add to the database:

def update_subjects():

connection = sqlite3.connect('subjects_info.db')
cursor = connection.cursor()
cursor.execute("""INSERT INTO subjects (nutrition, cooking, sport, music, health, traveling, tv, art, economics, fashion, history, literature, philosophy, technology, diy)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (nut, cook, spo, mus, hea, tra, tv, art, eco, fas, his, lit, phil, tec, diy)
              )
connection.commit()
connection.close()

when i try to choose subjects and click on the button:

b = Button(new_account_frame, text="That's all", command = update_subjects)
b.pack()

I get this error:

InterfaceError: Error binding parameter 0 - probably unsupported type.

Do you any idea what seems to be the problem? and how can I fix it?

Thanks in advance, I'd really appreciate it if you could help me :)




How to add label to the right side of checkbox in odoo-12

Hi im trying to design my checkbox in odoo i want it to have a label to the right side of the checkbox just like this enter image description here

Any Idea how can I Achieve this?

I've tried adding <span>Percentage</span> After my field but its always breaking the line




How to fill checkbox with data in a config file using JavaScript?

I would like to be able to fill a list of checkbox with datas from a config file.

In fact, if my checkbox is made to choose a Sport, in my config file I have something like this in JSON :

sports: ["Tennis", "Rugby", "Soccer"]

I would like my checkbox to be adaptative, means that the number of inputs is mapped on the length of the table in the JSON file.

Thank you very much for your help !

Edit :

Here is my HTML code

<div class="form-check">
    <label for="editSports">Pick your sport(s)</label>
    <input type="checkbox" class="form-control" id="editSports" name ="editSports">
    </input>
</div>

And I am wondering how to fill it with Javascript, I guess I'll have to do something like this :

ddn = $("#editSharedFolders");
config.sports.forEach(sport=> {
        ddn.append($('<checkbox>', {value: sport, text: sport})); //This line is the problem I guess
});



dimanche 29 mars 2020

I'm trying to figure out how to read the state/value of a slider switch that will react when moved

I've created a sliding switch that will hide or display parts of a large form. The HTML has the following code:

<fieldset class="group">
            <legend>
                <h1>Form Type</h1>
            </legend>
            <label class="switch switch-left-right">
                <input class="switch-input" type="checkbox" id="formSwitch">
                <span  class="switch-label" data-on="Progress" data-off="Diagnostic"></span>
                <span class="switch-handle"></span>
            </label>
        </fieldset>

The CSS behind it is the following:

.switch {
    position: relative;
    display: block;
    vertical-align: top;
    width: 100px;
    height: 30px;
    padding: 3px;
    margin: 0 10px 10px 0;
    background: linear-gradient(to bottom, #eeeeee, #FFFFFF 25px);
    background-image: -webkit-linear-gradient(top, #eeeeee, #FFFFFF 25px);
    border-radius: 18px;
    box-shadow: inset 0 -1px white, inset 0 1px 1px rgba(0, 0, 0, 0.05);
    cursor: pointer;
    box-sizing:content-box;
}
.switch-input {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    box-sizing:content-box;
}
.switch-label {
    position: relative;
    display: block;
    height: inherit;
    font-size: 10px;
    text-transform: uppercase;
    background: #eceeef;
    border-radius: inherit;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.15);
    box-sizing:content-box;
}
.switch-label:before, .switch-label:after {
    position: absolute;
    top: 50%;
    margin-top: -.5em;
    line-height: 1;
    -webkit-transition: inherit;
    -moz-transition: inherit;
    -o-transition: inherit;
    transition: inherit;
    box-sizing:content-box;
}
.switch-label:before {
    content: attr(data-off);
    right: 11px;
    color: #FFFFFF;
    text-shadow: 0 1px rgba(255, 255, 255, 0.5);
}
.switch-label:after {
    content: attr(data-on);
    left: 11px;
    color: #FFFFFF;
    text-shadow: 0 1px rgba(0, 0, 0, 0.2);
    opacity: 0;
}
.switch-input:checked ~ .switch-label {
    background: #E1B42B;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15), inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.switch-input:checked ~ .switch-label:before {
    opacity: 0;
}
.switch-input:checked ~ .switch-label:after {
    opacity: 1;
}
.switch-handle {
    position: absolute;
    top: 4px;
    left: 4px;
    width: 28px;
    height: 28px;
    background: linear-gradient(to bottom, #FFFFFF 40%, #f0f0f0);
    background-image: -webkit-linear-gradient(top, #FFFFFF 40%, #f0f0f0);
    border-radius: 100%;
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
}
.switch-handle:before {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -6px 0 0 -6px;
    width: 12px;
    height: 12px;
    background: linear-gradient(to bottom, #eeeeee, #FFFFFF);
    background-image: -webkit-linear-gradient(top, #eeeeee, #FFFFFF);
    border-radius: 6px;
    box-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
}
.switch-input:checked ~ .switch-handle {
    left: 74px;
    box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
}

/* Transition
========================== */
.switch-label, .switch-handle {
    transition: All 0.3s ease;
    -webkit-transition: All 0.3s ease;
    -moz-transition: All 0.3s ease;
    -o-transition: All 0.3s ease;
}
.switch-left-right .switch-label {
    overflow: hidden;
}
.switch-left-right .switch-label:before, .switch-left-right .switch-label:after {
    width: 20px;
    height: 20px;
    top: 4px;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 11px 0 0 0;
    text-indent: -45px;
    border-radius: 20px;
    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.2), inset 0 0 3px rgba(0, 0, 0, 0.1);
}
.switch-left-right .switch-label:before {
    background: #FF7F50;
    text-align: left;
    padding-left: 80px;
}
.switch-left-right .switch-label:after {
    text-align: left;
    text-indent: 9px;
    background: #FF7F50;
    left: -100px;
    opacity: 1;
    width: 100%;
}
.switch-left-right .switch-input:checked ~ .switch-label:before {
    opacity: 1;
    left: 90px;
}
.switch-left-right .switch-input:checked ~ .switch-label:after {
    left: 0;
}
.switch-left-right .switch-input:checked ~ .switch-label {
    background: inherit;
}

I'm trying to set it up so that when the switch is on Diagnostic, it will unhide a group of form fields and if it's on progress it will hide the same form fields. I've tried event listeners and onclick listeners and couldn't seem to get anything working. I just need to get it as far as "if it's in one position, do this" and "if it's in the other position, do that" This doesn't seem like it would be a challenge, but its proving to be one!




Save and restore check status of multiple checkboxes in a Chrome extension

I can save and restore a user input in a text field, based on the ID of the field - the code works as i expect, like:

function save_options() {
  var api = document.getElementById('text_field').value;
    chrome.storage.sync.set({
    savedApi: api,
    });
}    
document.getElementById("save").addEventListener("click", save_options);

function restore_options() {  
    chrome.storage.sync.get({"savedApi": ''}, function(items) {
      document.getElementById('text_field').value = items.savedApi;
    });
    }
document.addEventListener('DOMContentLoaded', restore_options);

Now i want to save the check status of multiple checkboxes. Should i really repeat this construction for every checkbox? Could somebody point me to a smarter way to save status of multiple checkboxes?




Laravel - old() value of checkbox, in combination with the one loaded from the database

I have this checkbox code:

<div>
     <input type="checkbox" id="allowfullscreen" name="allowfullscreen"
                                 >
</div>

This checks the checkbox based on the value taken from the database. Now, i would like to implement also the old data, in case of a failed submission.

For textboxes i do it like this:

<input id="galname"
                        type="text"
                        class="form-control @error('galname') is-invalid @enderror"
                        name="galname"
                        value=""
                        required autocomplete="galname" autofocus>

But it does not work this way for checkboxes since they need checked to be printed. The samples I found around here on SO only adress one of the two situations, but didnt find any that address both things for checkboxes.

How can this be done?




mat-checkbox unexpected behaviour

I use mat-checkbox within angular application. Globally my issue is the following: I have a formGroup including a mat-checkbox and a text input field. When I click on the mat-checkbox, I instanciate a new FormGroup with the same fields as previous, plus another text field. The value of the mat-checkbox is true and it is checked. Then, I click again on the checkbox to uncheck it and instanciate again the first FormGroup, but it stays checked while it should be unchecked

Here is the demo: (https://stackblitz.com/edit/angular-dy7s9u?file=src%2Fapp%2Fapp.component.html)

Apply following steps: 1) enter "Dupont" as name -> OK

2) check the box. The state of the box is checked. The value of the formControlName is true. The adresse field appear. -> OK

3) enter an adress (for example "19 Christchurch Road") -> OK

4) uncheck again the mat-checkbox. -> NOT OK the state of the mat-checkbox should become unchecked with a value false for the FormControlName and it is the contrary




React input type checkbox error with css styling

I've got a table, which creates itself with .map(). Each object in state array gets displayed in the table row with checkbox, which changes state value, and three buttons. I've had too much trouble with checkbox styling, but I've got it, however, now only the first checkbox works. Other checkboxes below can be clicked, but only the first one gets colored. Also, only in the first checkbox the onChange function works, not on others. So, I need that the function and color change would work on all checkboxes, not just the first one.

List code

class ProductList extends React.Component {
    render() { 
        const products = this.props.products;
        return (
            <div className="productList">
                <table className="productTable">
                    <tr>
                        <th className="text-left">Name</th>
                        <th className="text-right">EAN Code</th>
                        <th className="text-right">Type</th>
                        <th className="text-right">Weight</th>
                        <th className="text-right">Color</th>
                        <th className="text-center">Active</th>
                    </tr>
                    {products.map((product, index) => {
                        return (
                            <tr key={index}>
                                <td className="text-left">{product.name}</td>
                                <td className="text-right">{product.ean}</td>
                                <td className="text-right">{product.type}</td>
                                <td className="text-right">{product.weight}</td>
                                <td className="text-right">{product.color}</td>
                                <td className="text-center">
                                <input type="checkbox" id="check" checked={product.active} onChange={(e) => this.props.setProductActive(product, e.target.checked)} />
                                <label for="check" /></td>
                                <td className="text-center"><Link to=} ><button>View</button></Link></td>
                                <td className="text-center"><Link to=} ><button>Edit</button></Link></td>
                                <td className="text-center"><button onClick={() => this.props.deleteProduct(index)}>Delete</button></td>
                            </tr>
                        )
                    })}
                </table>
            </div>
        )
    }
}

Styling

}
input[type=checkbox] + label{
    display: block;
    margin: 2%;
    cursor: pointer;
}
input[type=checkbox]{
    display: none;
}
input[type=checkbox] + label:before {
    content:"";
    border: 2px solid cornflowerblue;
    border-radius: 10%;
    display: inline-block;
    width: 2rem;
    height: 2rem;
}
input[type=checkbox] + label:active:before{
    transform:scale(0);
}
input[type=checkbox]:checked + label:before{
    background-color: cornflowerblue;
    color: white;
    border-color: cornflowerblue;
}



samedi 28 mars 2020

Send message with ID of checked checkbox from popup.js to background.js

I want to send an ID of the checked checkbox from popup.js to background.js. I tried it on the following way, but failed:

popup.html

<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<input type="submit" value="Submit">

popup.js

document.getElementById('cbx').addEventListener(

    'submit', function checkForm(event) {

    event.preventDefault();

    //Define the form element
    var form = document.getElementById("cbx");

    if (form.cb1.checked) {

chrome.runtime.sendMessage({greeting: "cb1"});

    }

    return true;

});

background.js

chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
if( request.greeting === "cb1" ){
    console.log("cb1"); 
}
})

After checking of the checkbox console remains empty. How can i handle this correctly?




vendredi 27 mars 2020

Open two new tabs from popup.html and popup.js

I have some code, which lets user check checkboxes and on submit opens urls associted with checkboxes in new tabs. In case both checkboxes are checked two tabs become opened. It works like expected and looks like:

document.getElementById('cbx').addEventListener(

    'submit', function checkForm(event) {
        
    //Prevents default action that would normally happen onsubmit
        event.preventDefault();
    
    //Define the form element
    var form = document.getElementById("cbx");

    if (form.cb1.checked) {
        window.open('http://google.com/', '_blank');
    }
    if (form.cb2.checked) {
        window.open('http://yahoo.com/', '_blank');
    }

    return true;

});
<form id="cbx">
        
        <label for="cb1">G</label>
        <input name="cb1" type="checkbox">
        
        <label for="cb2">Y</label>
        <input name="cb2" type="checkbox">
        
        <input type="submit" value="Submit">
        
</form>

Now i want to include this functionality in my Chrome extension:

  • the HTML part is in popup.html,
  • Javascript part is in the popup.js.

The problem is: if both checkboxes are checked only one te first cb1 tab with url is opened.

Why is it so? How can i achieve that if all checkboxes are checked, tabs with all according urls become opened?




using checkbox with fragment result close app

I'm using Android Studio 3.5 and this issue appear when use it in fragment .. I'm try to use checkbox on fragment but when checked when run on mobile (the application close and give error ) i don't know from where the problem is .

Anyone can help me to solve this issue .. thanks note : I built bottom navigation and this fragment that show on fragment not in activity . thanks :

othersFragment:

public class othersActivity extends Fragment {

ArrayList<Integer> selection = new ArrayList<Integer>();

CheckBox send_it ;
Button btn_totalPrice , btn_submit;
TextView total_price;


public othersActivity (){

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_others, container, false);

//ini checkBox
send_it = v.findViewById(R.id.ch_sendITE);

//ini btn (submit & total price) and Textview
btn_totalPrice = v.findViewById(R.id.btn_submit);
btn_submit = v.findViewById(R.id.btn_totalPrice);

total_price = v.findViewById(R.id.t_totalPrice);

return v;
}


public void selectedItem(View view){
boolean checked = ((CheckBox) view).isChecked();

switch (view.getId()){
        case R.id.ch_sendITE:
            if(checked){
                selection.add(5);
            }else{
                selection.remove(Integer.valueOf("5"));
            }
            break;

    }

}

public void final_price(View v){

    String final_price  = "";
    double sum = 0;
    for(int i=0;i<selection.size(); i++){
        sum = sum + selection.get(i);
    }
    String res = String.valueOf(sum);
    final_price = res;
    total_price.setText(final_price);

}

}

Activity_others.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.othersActivity">

<RelativeLayout
    android:id="@+id/banner"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/banner3">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:fontFamily="casual"
        android:text="e - Request"
        android:textColor="@color/colorDarkBlue"
        android:textSize="50dp"
        android:textStyle="bold" />

</RelativeLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/banner"
    android:orientation="vertical"
    android:paddingLeft="20dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="20dp"
        android:text="Please select your item:"
        android:textColor="@color/colorBlack"
        android:textSize="30dp"
        android:textStyle="bold" />

    <CheckBox
        android:onClick="selectedItem"
        android:id="@+id/ch_sendITE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/send_ITE"
        android:textSize="20dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/show_totalPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Total price : "
            android:textSize="20dp" />

        <TextView
            android:id="@+id/t_totalPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" 0.0 "
            android:textSize="20dp" />

        <TextView
            android:id="@+id/K.d_totalPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" K.D "
            android:textSize="20dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="25dp"
        android:orientation="horizontal">

        <Button
            android:onClick="final_price"
            android:id="@+id/btn_totalPrice"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:background="@drawable/btn_log_regist"
            android:text="Total price"
            android:textColor="@color/colorWhite" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@drawable/btn_log_regist"
            android:text="Submit"
            android:textColor="@color/colorWhite" />

    </LinearLayout>


</LinearLayout>

</RelativeLayout>



How to Center Menu on Responsive Checkbox Hamburger Menu

I've successfully made an hamburger menu that only appears after a certain width, but the problem is that I would like the nav links to be centered, to occupy the whole page (here it stops once the links in the menu are done) and to have a different background color. Here's an example how the layout I'd like: layout example I've used CSSS and HTML only and would like to stick to these if possible.

Here's the code:

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="stylenav.css">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link href="css/font-awesome.min.css" rel="stylesheet"/>
        <link rel='icon' href='FAVICON.jpg' type='image/x-icon'/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <title>AURORA CATERA 2020</title>
    </head>

    <body>

        <header class="header">
            <a href="index.html"><img src="img/AURORA-YLOW-FIN copy.png" class="logo"></a>
            <input class="menu-btn" type="checkbox" id="menu-btn" />
            <label class="menu-icon" for="menu-btn"><span class="nav-icon"></span></label>
            <ul class="menu">
                <li><a href="#dont">ALL</a></li>
                <li><a href="#forget">STUFF</a></li>
                <li><a href="#subscribe">ABOUT</a></li>
                <li><a href="#comment">CONTACT</a></li>
                <li><a href="https://www.instagram.com/auroracatera" target="_blank"><i class="fa fa-instagram"></li></i></a>
            </ul>


        </header>


        </body>
        </html>
@import url('https://fonts.googleapis.com/css?family=Poppins:900&display=swap');
@import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond:300&display=swap');
@import url('https://fonts.googleapis.com/css?family=Raleway:500&display=swap');
@import url('https://fonts.googleapis.com/css?family=Work+Sans:100,200,300,400,600&display=swap');
@import url('https://fonts.googleapis.com/css?family=Rajdhani:400&display=swap');


body{
    margin:0;
    background-color:#000;
}

a{
    color:#F8E315;
    font-family: Rajdhani, sans-serif;
}

.header{
    background-color:rgb(153, 57, 57);
    position:fixed;
    width:100%;
    z-index:3;
}

.header ul{
    margin:0;
    padding: 20px 30px 0 0;
    list-style:none;
    overflow:hidden;
    background-color:rgb(0, 0, 0);
}

.header ul a{
    display:block;
    padding:20px;
    text-decoration:none;
}

.header ul a:hover{
   color:#c7c7c7; 
}

.header .logo{
    float:left;
    display:block;
    height: 62px;
    padding: 30px 0 0 40px;

}

.header .menu{
    clear:both;
    max-height:0;
    transition:max-height .2s ease-out;
}

.header .menu-icon{
    padding: 58px 20px;
    position:relative;
    float:right;
    cursor: pointer;
}

.header .menu-icon .nav-icon{
    background:#F8E315;
    display:block;
    height:2px;
    width:30px;
    border-radius: 2px;
    position:relative;
    transition:background;
}

.header .menu-icon .nav-icon:before{
    background: #F8E315;
    content:"";
    display:block;
    height:100%;
    width:100%;
    border-radius: 2px;
    position:absolute;
    top:10px;  

}

.header .menu-icon .nav-icon:after{
    background:#F8E315;
    content:"";
    display:block;
    height:100%;
    width:100%;
    border-radius: 2px;
    position:absolute;
    top:-10px;  

}

.header .menu-btn{
    display:none;
}

.header .menu-btn:checked ~ .menu{
    max-height:240px;

}

.header .menu-btn:checked ~ .menu-icon .nav-icon{
    background:transparent;
}
.header .menu-btn:checked ~ .menu-icon .nav-icon:before{
    transform: rotate(-45deg);
    top:0;
}
.header .menu-btn:checked ~ .menu-icon .nav-icon:after{
    transform: rotate(45deg);
    top:0;
}

@media (min-width:48em){

    .header li{
        float:left;
    }

    .header .menu{
        clear:none;
        float:right;
        max-height:none;
    }

    .header .menu-icon{
        display:none;
    }

}





How to correctly handle checkbox with React?

we are a totally lost in the checkboxes with React.

Our checkbox for the fields : RGPD ans ChaterAcceptance, doesn't take the boolean change when we post it in the database.

Could anyone could give us an explanation to solve our problem, we already made some tests and search but if your knowledge could help us, it would be great.

Here's our code of RegisterPagePro.jsx :

import React, { useState } from "react";
import Field from "../components/forms/Field";
import { Link } from "react-router-dom";
import UsersProAPI from "../services/userProAPI";
import { toast } from "react-toastify";

const ProRegisterPage = ({ history }) => {
  const [userPro, setUserPro] = useState({
    firstName: "",
    lastName: "",
    email: "",
    RGPD: false,
    address: "",
    siret: "",
    therapy: "",
    chaterAcceptance: false,
    rate: "",
    paymentMethod: "",
    expertise: "",
    presentation: "",
    openingTime: "",
    languages: "",
    password: "",
    passwordConfirm: ""
  });

  const [errors, setErrors] = useState({
    firstName: "",
    lastName: "",
    email: "",
    RGPD: false,
    address: "",
    siret: "",
    therapy: "",
    chaterAcceptance: false,
    rate: "",
    paymentMethod: "",
    expertise: "",
    presentation: "",
    openingTime: "",
    languages: "",
    password: "",
    passwordConfirm: ""
  });

  // Gestion des changements des inputs dans le formulaire
  const handleChange = ({ currentTarget }) => {
    const { name, value } = currentTarget;
    setUserPro({ ...userPro, [name]: value });
  };

  const handleSubmit = async event => {
    event.preventDefault();

    const apiErrors = {};

    if (userPro.password !== userPro.passwordConfirm) {
      apiErrors.passwordConfirm =
        "Votre confirmation de mot de passe n'est pas conforme avec le mot de passe original";
      setErrors(apiErrors);
      toast.error("Des erreurs dans votre formulaire !");
      return;
    }

    try {
      await UsersProAPI.registerPro(userPro);
      setErrors({});

      // TODO : Flash success
      toast.success(
        "Vous êtes désormais inscrit, vous pouvez vous connecter !"
      );
      history.replace("/login");
    } catch (error) {
      const { violations } = error.response.data;

      if (violations) {
        violations.forEach(violation => {
          apiErrors[violation.propertyPath] = violation.message;
        });
        setErrors(apiErrors);
      }

      // TODO : Flash erreur
      toast.error("Des erreurs dans votre formulaire !");
    }
  };
  return (
    <>
      <h1>Inscription pour les professionnels</h1>
      <form onSubmit={handleSubmit}>
        <Field
          name="firstName"
          label="Prénom"
          placeholder="Votre joli prénom"
          error={errors.firstName}
          value={userPro.firstName}
          onChange={handleChange}
        />
        <Field
          name="lastName"
          label="Nom de famille"
          placeholder="Votre nom de famille"
          error={errors.lastName}
          value={userPro.lastName}
          onChange={handleChange}
        />
        <Field
          name="email"
          label="Adresse email"
          placeholder="Votre adresse email"
          type="email"
          error={errors.email}
          value={userPro.email}
          onChange={handleChange}
        />
        <Field
          name="RGPD"
          label="Conditions utilisateur"
          placeholder="Veuillez cocher la case"
          type="checkbox"
          error={errors.RGPD}
          value={userPro.RGPD}
          onClick={handleClick}
        />
        <Field
          name="address"
          label="Adresse postale"
          placeholder="Votre adresse postale"
          error={errors.address}
          value={userPro.address}
          onChange={handleChange}
        />
        <Field
          name="siret"
          label="Siret"
          placeholder="Siret"
          error={errors.siret}
          value={userPro.siret}
          onChange={handleChange}
        />
        <Field
          name="therapy"
          label="Thérapie pratiquée"
          placeholder="Thérapie"
          error={errors.therapy}
          value={userPro.therapy}
          onChange={handleChange}
        />
        <Field
          name="chaterAcceptance"
          label="Acceptation de la charte"
          placeholder="Charte"
          type="checkbox"
          error={errors.chaterAcceptance}
          value={userPro.chaterAcceptance}
          onClick={handleClick}
        />
        <Field
          name="rate"
          label="Honoraires"
          placeholder="Honoraires"
          error={errors.rate}
          value={userPro.rate}
          onChange={handleChange}
        />
        <Field
          name="paymentMethod"
          label="Méthode de paiement"
          placeholder="Votre méthode de paiement"
          error={errors.paymentMethod}
          value={userPro.paymentMethod}
          onChange={handleChange}
        />
        <Field
          name="expertise"
          label="Compétence"
          placeholder="Vos compétences"
          error={errors.expertise}
          value={userPro.expertise}
          onChange={handleChange}
        />
        <Field
          name="presentation"
          label="Présentation"
          placeholder="Présentation"
          error={errors.presentation}
          value={userPro.presentation}
          onChange={handleChange}
        />
        <Field
          name="openingTime"
          label="Horaires d'ouverture"
          placeholder="Horaires"
          error={errors.openingTime}
          value={userPro.openingTime}
          onChange={handleChange}
        />
        <Field
          name="languages"
          label="Langues"
          placeholder="Langues parlées"
          error={errors.languages}
          value={userPro.languages}
          onChange={handleChange}
        />
        <Field
          name="password"
          label="Mot de passe"
          type="password"
          placeholder="Votre mot de passe ultra sécurisé"
          error={errors.password}
          value={userPro.password}
          onChange={handleChange}
        />
        <Field
          name="passwordConfirm"
          label="Confirmation de mot de passe"
          type="password"
          placeholder="Confirmez votre super mot de passe"
          error={errors.passwordConfirm}
          value={userPro.passwordConfirm}
          onChange={handleChange}
        />
        <div className="form-group">
          <button type="submit" className="btn btn-success">
            Confirmation
          </button>
          <Link to="/login" className="btn btn-link">
            J'ai déjà un compte
          </Link>
        </div>
      </form>
    </>
  );
};

export default ProRegisterPage;



How to disable button without changing of ng-if condition for input type checkbox using angularjs?

I have one interesting situation, I have the below code.

Js:

<script>
  var app = angular.module('MyApp', []);    
    app.controller('MyCtrl', function($scope) {
      $scope.a=10;
    });
</script>

html:

<body ng-app="MyApp">
  <div ng-controller="MyCtrl">
    Click Me: <input type="checkbox" ng-model="checked" ng-if="a===10"/> <br />
    <button ng-disabled="checked">Test</button>
  </div>
</body>

If I run the above code, Test button is not disabling. I am not sure why ?

But, as per my requirement, that ng-if condition should be there in <input /> tag only and I cannot write or combine <input /> and <button> tags in one <div> as well.

So, please help me, to have any other way to get my Test button should be in disabled mode on clicking of input type checkbox without changing of above sample code.

Codepen.




jeudi 26 mars 2020

I want to add a class to a previous selector using the .prevUntil()

<!DOCTYPE html>
<html>

<head>

this is the jquery aspect'

   <script>
    $(document).ready(function() {
      $(".check").click(function() {
       $(this).toggleClass('start');
       $(this).toggleClass('check');

this is to add class "checking" to all previous checkbox input

       if ($(this).prop('checked') === true) {
           $("input.start").prevUntil('input.stop').toggleClass('checking');
           $(this).val(1);
       } 
       else {
           $(this).prop('checked', false);
           $(this).addClass('check');
           $(this).val(0);
        }

this is to get values of the checkbox input that were a class of "checking"

        var list = document.getElementsByClassName("checking");
        for (var i = 0; i < list.length; i++) {
          alert($(list[i]).val());
         }
       });
});

this is the html part

 <body>
  <div class="col-sm-4" style="text-align: center; display: block;">
Contact Section Forms
<br>
<div class="col-md-3" style="display: inline-block;">
  <label>SCSF  1</label>
  <input value="0" type="hidden" name="scsf_i">
  <input class="form-control form-control-user check stop" value="0" type="checkbox" name="scsf_i">
</div>

for instance, if i run the code, the checking rather added as a class to the label

  <div class="col-md-3" style="display: inline-block;">
  <label>SCSF  2</label>
  <input value="0" type="hidden" name="scsf_ii">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="scsf_ii">
</div>
<div class="col-md-3" style="display: inline-block;">
  <label>SCSF  3</label>
  <input value="0" type="hidden" name="scsf_iii">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="scsf_iii">
</div>
  </div>
  <div class="col-sm-4" style="text-align: center; display: block;">

Other Documents

<br>
<div class="col-md-3" style="display: inline-block;">
  <label>Form A</label>
  <input value="0" type="hidden" name="form_a">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="form_a">
</div>
<div class="col-md-3" style="display: inline-block;">
  <label>Ungraded</label>
  <input value="0" type="hidden" name="ungraded_i">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="ungraded_i">
</div>
<div class="col-md-3" style="display: inline-block;">
  <label>Graded</label>
  <input value="0" type="hidden" name="graded_i">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="graded_i">
</div>
 </div>
  </body>

 </html>



how to use checkbox list to select multiple table names from database and download the checked tables as excel file sheet

I have multiple tables in mysql database and created a list of checkboxes in wodpress page with download button, I want the user be able to download the selected tables with checkboxes and select specific row of checked tables, so there will be two list of checkboxes first list is to select column name(governorates) and the second check box list is to select table name(sector), after selecting the value of both check boxes click on the download button to download the selected data as excel file sheet.

take a look at the design image to understand the idea




I want to get the value of each attr('selector') using the .prevUntil() and pass it into an array in jquery

I want to get the value of each attr('selector') using .prevUntil() and pass it into an array in jQuery.

<script>
  $(document).ready(function() {
  $(document).ready(function() {
  `
<script>
      var checkbox = "check";
      $(document).on('click', '.'+checkbox, function() {
        var old = $(this).attr('class');
        var new_class = 'start';
        $(this).addClass(''+new_class);
        var added = $(this).attr('class');
        alert($('input.stop').nextUntil('input.'+new_class).attr('name'));
      });
    });
</script>
</head>

<body>
  <input class="form-control form-control-user check stop" value="0" type="checkbox" name="scsf_i">
  <input class="form-control form-control-user check" value="0" type="checkbox" name="scsf_ii">

  <input class="form-control form-control-user check" value="0" type="checkbox" name="scsf_iii">

  <input class="form-control form-control-user check" value="0" type="checkbox" name="form_a">

  <input class="form-control form-control-user check" value="0" type="checkbox" name="ungraded_i">

  <input class="form-control form-control-user check" value="0" type="checkbox" name="graded_i">
</body>
</html>



(WPF) How can I find ancestor about two ItemsControl in code behind?

I have a ItemsControl(A). ItemSourece is a Class "Account".It contains some controls and another ItemsControl(B).

ItemsControl(B) includes some CheckBox. It's ItemSourece is ObservableCollection included in Class "Account". CheckBox's Content is binding to Content. CheckBox's IsChecked is bindind to IsChecked.

enter image description here

Now when I click CheckBox, I want to get ID and User in Class "Account", but I don't know hot to get them. I already try to use

    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        CheckBox checkBox = sender as CheckBox;
        var parentElement = (ContentPresenter)VisualTreeHelper.GetParent(checkBox);           
    }

but it still can't get parent.

Please help me! Thanks!




mercredi 25 mars 2020

Counting checked checkboxes in realtime without submiting or any other action in html5

I´m doing a management page for a learning institute as a homework of programming languages subject, and I need to make an assistance database and its frontend. I made a table with students IDs, names and a column with checkboxes that you checked if that student is present. I want to count the number of present students, let´s say, on-the-fly. I have found a lot of examples that counts checkboxes when you clicked a buttom or something like that like this ->Count checkboxes..., but I need another thing. I want to show that number as I checked boxes in "realtime" without clicking another thing, in a text below like 'Total students Present: "n"', and n changes as you check each box. I will be very greatful with any sugestion or tip.




How to open urls through submit of a form with checked checkbox

I want to build a form with some checkboxes. To each checkbox is bundled an url. User checks one or more checkboxes, press submit and urls of checked checkboxes open in new tabs.

I tried a snippet, which illustrates my idea, but without success:

<form>

    <label for="cb1">G</label>
    <input id="cb1" type="checkbox" onSubmit="window.open('http://google.com/','_blank')">

    <label for="cb2">Y</label>
    <input id="cb2" type="checkbox" onSubmit="window.open('http://yahoo.com/','_blank')">

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

</form>



How to create a form in PHP with checkbox groups and associated select menu for each checkbox

I'm trying to do with PHP and HTML, a form that contains a group of checkboxes and drop-down menus.

I would like that for each chexboxes, there is an associated select menu.

I create checkbox groups dynamically from a MySQL database

For exemple :

Form :

Checkbox 1 (0:off/1:on) - Selectmenu 1 (0:Red, 1:green, 2:blue, 3:yellow)

Checkbox 2 (0:off/1:on) - Selectmenu 2 (0:Red, 1:green, 2:blue, 3:yellow)

Checkbox 3 (0:off/1:on) - Selectmenu 3 (0:Red, 1:green, 2:blue, 3:yellow)

Checkbox 4 (0:off/1:on) - Selectmenu 4 (0:Red, 1:green, 2:blue, 3:yellow)


I managed to create this, and get via POST the checkbox values through an array (input name="check_list[]")

By cons I can not retrieve the values of select menus, and even less to associate them with the corresponding checkbox

Exemple : I would like to get variables like this (via POST):

Checkbox1 and Selectmenu 1 = 0,3  (off and yellow)

Checkbox2 and Selectmenu 2 = 0,2  (off and blue)

Checkbox3 and Selectmenu 3 = 1,1  (off and green)

Checkbox4 and Selectmenu 4 = 0,0  (off and red)

I hope my question is clear enough.

How do I get there?

Thanks




How to close CSS checkbox menu when clicking on links with JS?

So I made a pure CSS checkbox menu and everything looks how I want it, except for when clicking the links. In my single page layout clicking the links navigates to a section of the page, but upon clicking the link, it just smooth scrolls to the section and the menu remains visible. I have read multiple similar questions and none of the solutions have worked for me. I would prefer to use JavaScript and no jQuery.

My website is still in working progress; check it out to really see what happens on mobile size https://www.itsalaam.com/

Here is my code:

/* NAVIGATION */
.header {
    width: 100%;
    position: fixed;
    top: 0;
    background: linear-gradient(rgba(0, 0, 0, 0.7), transparent);
    z-index: 999;
    overflow: hidden;
    /* transition: background .2s ease-out; */
}
.header ul {
    margin: 0;
    padding: 0;
    list-style: none;
    overflow: hidden;
}
.header ul a {
    display: block;
    padding: 15px;
    text-align: center;
    color: rgb(224, 224, 224);
    font-size: 1.7rem;
}
.header ul a:hover {
    color: #fff;
}
.header .logo {
    float: left;
    display: block;
    padding-top: 15px;
    padding-left: 30px;
}
.header .logo img {
    width: 50px;
    transition: width .5s ease;
}
.header .menu {
    clear: both;
    float: right;
    max-height: 0;
    text-align: center;
    width: 100%;
    transition: max-height .2s ease-out;
    transition: background 0.2s ease-out;
}
.header .menu-icon {
    padding: 28px 20px;
    position: relative;
    float: right;
    cursor: pointer;
    /*menu-icon serves as the parent element of the span nav-icon the is nested within. so the span is the child element*/
}
.header .menu-icon .nav-icon {
    /*creates the middle bar of the nav-icon*/
    background: #fff;
    display: block;
    height: 2px;
    width: 18px;
    position: relative;
    transition: background .2s ease-out;
}
.header .menu-icon .nav-icon:after,
.header .menu-icon .nav-icon:before {
    background: #fff;
    content: "";
    display: block;
    height: 100%;
    width: 100%;
    position: absolute;
    transition: all .2s ease-out;
}
.header .menu-icon .nav-icon:before {
    top: 5px;
}
.header .menu-icon .nav-icon:after {
    top: -5px;
}
.header .menu-btn {
    display: none;
}
.header .menu-btn:checked~.menu {
    /* the ~ selects the next sibling  */
    max-height: 100vh;
    background: #000;
    z-index: 99;
    transition: background 0.2s ease-out;
    /*because the max height was set to 0 on the .menu once the menu-btn is checked, the for attribute must match the id of the input checkbox. so when you click the label it targets the check box, which was set to display none.*/
}
/* the X for closing */
.header .menu-btn:checked~.menu-icon .nav-icon {
    background: transparent;
}
/*middle line disappears*/
.header .menu-btn:checked~.menu-icon .nav-icon:before {
    transform: rotate(-45deg);
    top: 0;
}
.header .menu-btn:checked~.menu-icon .nav-icon:after {
    transform: rotate(45deg);
    top: 0;
}
<header class="header">
      <a href="index.html" class="logo"><img src="/img/globeWireframe.png" alt="salaam" /></a>
      <input type="checkbox" class="menu-btn" id="menu-btn" />
      <label for="menu-btn" class="menu-icon"><span class="nav-icon"></span></label>
      <ul class="menu">
        <li><a href="#" class="current">Home</a></li>
        <li><a href="#about">About</a></li>
        <li>
          <a href="#" type="button" data-toggle="modal" data-target="#exampleModal">Resume</a>
        </li>
        <li><a href="#projects">Projects</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </header>
    
  



Preventing double-click on checkbox with label

Today I got very interesting situation and really want to find solution. I found a lot of similar topics, but answers don't helps.

So I need to prevent doubleclick on my checkbox with Jquery. First of all I tried the simplest way:

$("input[type='checkbox']", this).dblclick(function() {
    alert( "Double Clicked" );
});

But alert don't coming up on dblclick. I found an solution like this:

$("input[type='checkbox']", this).on("change", function() {
    $("input[type='checkbox']", this).prop('disabled', true);
    sleep(750).then(() => {
        $("input[type='checkbox']", this).prop('disabled', false);
    }) 
})

This event is nicely triggered, but checkbox not disabled for 750ms (but if I put alerts, alert coming at right time, when button must enabled/disabled) and I am still able to double-click on it. Any solution for this?




Gravity forms pre-selected choices checkboxes field

I am using Gravity forms with one Radio Button and one Checkboxes field they both have same choices. What I need is when my user chooses a choice on Radio Button, this choice is automatically pre-selected on the Checkboxes field. He doesn't have to select it again.

I saw I have to use some filter, for example, the one below, but I cannot succeed to customize it in order to do what I need.

If someone could help me he will save my life.

<?php

# Make sure to replace {id} with your form's id
add_filter( 'gform_pre_render_{id}', 'my_populate_checkbox' );

function my_populate_checkbox( $form ) {

/**
* Loop through form fields
*
* Note we are using the `$field` array as a direct reference using `&`. 
* This means that changing its value will within the loop will 
* change the corresponding `$form` array item
*/
foreach( $form['fields'] as &$field ) {

# Make sure to change `1` to the ID of the checkbox field that you want to pre-populate
if( 1 === $field->id ) {

  /**
   * Loop through the choices for this checkbox
   *
   * Note again that we are passing `$choice` by reference in order to change the 
   * corresponding array item within the `$field` array
   */
  foreach( $field->choices as &$choice ) {

    /**
     * If this choice has a value of 'red' or 'blue', then make sure the checkbox is pre- 
   checked
     * by setting the `isSelected` parameter to `true`
     */

    if( 'red' === $choice['value'] || 'blue' === $choice['value'] ) {
      $choice['isSelected'] = true;
    }
   } # end foreach: $field->choices
   } # end if: $field->id equals 1
   } # end foreach: $form['fields']

    # return the altered `$form` array to Gravity Forms
   return $form;

    } # end: my_populate_checkbox



React setState: using checkbox to change boolean value

React beginner here. Checked through similar topics and haven't found the answer. I am building a page where you create items and update information. But right now I'm struggling with a simple checkbox. When it's checked, the active state should change to true and vice versa. However, when I click, the stat doesn't change. I've checked with console log and the function works fine, tried using prevState and simple setState active:true, but I still can't change it. I'm probably missing something obvious, so thanks in advance if you can point it out.

The App Code

import React from 'react';
import './App.css';
import ProductList from "../ProductList/ProductList";
import NewProd from "../NewProd/NewProd";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
            name: "", 
            ean: "", 
            type: "", 
            weight: "", 
            color: "", 
            active: null,
            products: [{name: "Cabbage", ean: "00000000", type: "Vegetable", weight: "2kg", color: "Green", active: false}, 
            {name: "Banana", ean: "111111111", type: "Fruit", weight: "0.3kg", color: "Yellow", active: false}, 
            {name: "Chocolate", ean: "22222222222", type: "Candy", weight: "0.2kg", color: "Brown", active: false}, 
            {name: "Orange", ean: "3333333333", type: "Fruit", weight: "0.5kg", color: "Orange", active: false}, 
            {name: "Cucumber", ean: "4444444444", type: "Vegetable", weight: "1kg", color: "Green", active: false}, ]
    };
    this.isActive = this.isActive.bind(this);
};

handleFormSubmit = (e) => {
  e.preventDefault();
  let products = [...this.state.products];

  products.push({
      name: this.state.name,
      ean: this.state.ean,
      type: this.state.type,
      weight: this.state.weight,
      color: this.state.color,
      active: false,
  });
  this.setState({ products, name: "", ean: "", type: "", weight: "", color: "", active: false}
  );
}
handleInputChange = (e) => {
  let input = e.target;
  let name = e.target.name;
  let value = input.value;
  this.setState({[name]: value})
  };

deleteProduct = (delIndex) => {
  let products = [...this.state.products].filter((product, index) => index !== delIndex);
  this.setState({ products });
};
isActive = () => {
  this.setState({active: !this.state.active})
}
render() {
  return (
    <div className="App">
      <ProductList products={this.state.products} 
      deleteProduct={this.deleteProduct}
      isActive={this.isActive} />
      <NewProd handleFormSubmit={this.handleFormSubmit}
      handleInputChange={this.handleInputChange}
      newName={this.state.name}
      newEan={this.state.ean}
      newType={this.state.type}
      newWeight={this.state.weight}
      newColor={this.state.color} />
    </div>
  );
  }
}

export default App;

The List Code

import React from "react";
import "./ProductList.css";

class ProductList extends React.Component {
    render() { 
        const products = this.props.products;
        return (
            <div>
                <h1>Product List</h1>
                <table>
                    <tr>
                        <th>Name</th>
                        <th>EAN Code</th>
                        <th>Type</th>
                        <th>Weight</th>
                        <th>Color</th>
                        <th>Active</th>
                    </tr>
                    {products.map((product, index) => {
                        return (
                            <tr key={index}>
                                <td>{product.name}</td>
                                <td>{product.ean}</td>
                                <td>{product.type}</td>
                                <td>{product.weight}</td>
                                <td>{product.color}</td>
                                <td><input type="checkbox" onChange={this.props.isActive} /></td>
                                <td><button>View</button></td>
                                <td><button>Edit</button></td>
                                <td><button onClick={() => this.props.deleteProduct(index)}>Delete</button></td>
                            </tr>
                        )
                    })}
                </table>
            </div>
        )
    }
}
export default ProductList;



Checkbox is not visible on Firefox 74.0 (64-bit) on Ubuntu

When I navigate to sample page with checkbox https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

<div>
  <input type="checkbox" id="scales" name="scales"
         checked>
  <label for="scales">Scales</label>
</div>

<div>
  <input type="checkbox" id="horns" name="horns">
  <label for="horns">Horns</label>
</div>

I do not see checkboxes.

enter image description here

Also when I click on label, I can not notice if checkbox is selected or not. This is unlikely to be a bug, I hope it is a problem with some configuration.




mardi 24 mars 2020

Using Flutter Checkbox() and obtaining initial value from Firestore

I'm no experienced programmer and I could find no guidance, hence this question. I have a working solution but not sure if this is good practice.

I am using the widget Checkbox() in a Form(). Widgets like TextFormField() and DateTimeField() have a parameter called 'initialValue'. Checkbox() does not.

For TextFormField() and DateTimeField() I obtained the initialValue by:

@override Widget build(BuildContext context) { final user = Provider.of(context);

return StreamBuilder<UnitDetails>(
  stream: DatabaseServices(uid: user.userUid, unitUid: widget.unitUid)
      .unitByDocumentID,
  builder: (context, unitDetails) {
    if (!unitDetails.hasData) return Loading();
    return Scaffold(
    etc

The Checkbox(value: residentialUnit,) can not have its initial value set inside the builder:. The parameter 'value:' needs to be set true or false before the builder: ie before the value is obtained from Firestore! The way I solved this is by using initState(). An extra call to Firestore and more code for this one input widget.

@override void initState() { super.initState();

Firestore.instance
    .collection("units")
    .document(widget.unitUid)
    .snapshots()
    .listen((snapshot) {
  residentialUnit = snapshot.data['unitResidential'];
});

}

Is there a better way?




How can I default checked a checkbox in WPF MVVM

I have an Employee Table. and I have an WPF Screen. in screen I want to have an "Exclude Former Employees" checkbox (checked as default) when it checked I generate report there is no Former Employee in table. but When I remove check in checkbox I want to see former employee.

See in my xaml:

<CheckBox Content="Exclude Former Employees" IsChecked="{Binding ExcludeFormerEmployees}" Margin="4" />

in ViewModel:

private bool _excludeFormerEmployees;
        public bool ExcludeFormerEmployees
        {
            get { return _excludeFormerEmployees; }
            set { Set(ref _excludeFormerEmployees, value); }
        }

In Generate Report Button Command (It's employee reports)

   if (_excludeFormerEmployees) hd.ExcludeFormerEmployees();

in Method:

 public void ExcludeFormerEmployees()
        { 
            RemoveAll(ef => Employee.IsDelegation==false&& Employee.Status==0);

        }

Thank you for all your helps.




CSS - style checkbox of different format - normal CF7 checkbox

I have a Wordpress CF7 form which uses checboxes of two kinds, normal checkbox and acceptance checkbox. I used acceptance checkboxes, then it turned out I need more than 1 checkboxes, but this plugin supports only 1 acceptance box, hence I need to add a normal checkbox too.

So far I managed to style pretty well the acceptance checkbox, which has this code:

      <div class="checkbox2">
        <span class="wpcf7-form-control-wrap your-consent">
          <span class="wpcf7-form-control wpcf7-acceptance optional">
            <span class="wpcf7-list-item">
              <label class="container">
              <input type="checkbox" name="your-consent" value="1" aria-invalid="false" class="acceptance">
                <span class="wpcf7-list-item-label checkmark">&nbsp;</span>
                 </label>
            </span>
          </span>
        </span>
        <span class="checkbox-text">I consent</span></div>

    </div>

Now I am struggling to create new css for the normal checkbox. It has a different HTML structure, which I can't change.

      <div class="checkbox1">
        <span class="wpcf7-form-control-wrap checkbox-766 container">
          <span class="wpcf7-form-control wpcf7-checkbox wpcf7-validates-as-required acceptance">
            <span class="wpcf7-list-item first last">
              <input type="checkbox" name="checkbox-766[]" value="I agree ">
              <span class="wpcf7-list-item-label">I agree to the privacy policy</span>
            </span>
          </span>
        </span>
      </div>

Can anyone help me to apply the code of checkbox2 to checkbox1?

It can be completely new css/scss, doesn't matter if it stops working for checkbox2. I will add it with a parent #id and both will work fine.

Here is the code in codepen.




How can I make a QCheckBox for (un)checking several QCheckBoxes?

I am writing a subclass of QCheckBox that I would like to display to the user for checking or unchecking a set of existing check boxes. It works by reacting on the toggled(bool) signals of the check boxes.

The "master" check box must be a tristate check box. When some of the "slave" check boxes are checked but not all of them, the master is set to Qt::CheckState::PartiallyChecked.

It doesn't work well enough. Although I want to set the master check box to "partially checked" within my code, the user should not be able to do that. Clicking onto the master check box should completely check all check boxes except if all of them are already checked. In that case it should uncheck them all. Yet, my master check box also switches to the intermediate state when I click onto it.

I guess that I can change that by overriding void QAbstractButton::checkStateSet() and void QAbstractButton::nextCheckState(), but I do not understand the documentation of these methods. What should they do? And how can I override them to get the expected behaviour?




Handling outlook checkbox when sending email with python

My company has an outlook add-in that pops up a checkbox when sending email to an external source. I have a python program that needs to send an email to the same external email address every time. So looking for a way in my code to automatically check the box and click the send button.

import win32com.client as win32

outlook = win32.dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.to = 'external email address here'
mail.subject = 'update'
mail.body = 'body of the message'
mail.Send()



Why my captcha doesn't display? And I can't click on the checkbox and the button?

I'm using Chrome and I am trying to create a Payflow Gateway Account. I went to https://registration.paypal.com/ and followed all the steps to register. But when I was in step 3 (there are 4 steps in this step), it requires me to log in to the Paypal account. So I entered the email and the password, moreover, it requires me to enter the code in the captcha. But I just saw a broken picture. I used the listen option but I can't hear anything! Can anyone explain to me why this happens, is it because my network is weak or because my browser is having a problem (or because of Paypal). I have also tried to enter a random code but when I was in the Product Selection / Billing step, I can't click on the checkbox and the button. Is it because of that random code or because of another error? And if anyone can create for me an account, I will very appreciate that! If after 2 days and there still no answer, I will run a bounty.




Is React data grid opensource or paid?

I have come across different grids like ag-grid, syncfusion, react data grid. I am looking for open source. Is React data grid is open source?




how to implement oncheck event of td on one2many list view

I have added a checkbox to my one2many field listview(using the web_one2many_selectable_10 module) I want to get every id of the selected line in my one2many field oncheck of the check box instead of onclick of the "Create DR" button

one2many checkbox

here's the javascript code

odoo.define('web_one2many_selectable_10.form_widgets', function (require) {
    "use strict";

    var core = require('web.core');
    var form_common = require('web.form_common');
    var _t = core._t;
    var QWeb = core.qweb;
    var Model = require('web.Model');
    var FieldOne2Many = core.form_widget_registry.get('one2many');


    var One2ManySelectable = FieldOne2Many.extend({
        // my custom template for unique char field
        template: 'One2ManySelectable', 

        multi_selection: true,
        //button click
        events: {
            "click td.o_list_record_selector": "get_id_lines",
        },
        start: function() 
        {
            this._super.apply(this, arguments);
            var self=this;          
           },
        get_id_lines: function(e){
            var self=this;
            console.log('im here')

        },
        //collecting the selected IDS from one2manay list
        get_selected_ids_one2many: function ()
        {
            var ids =[];
            this.$el.find('td.o_list_record_selector input:checked')
                    .closest('tr').each(function () {

                        ids.push(parseInt($(this).context.dataset.id));
                        console.log(ids);
            });
            return ids;
        },


    });
    // register unique widget, because Odoo does not know anything about it
    //you can use <field name="One2many_ids" widget="x2many_selectable"> for call this widget
    core.form_widget_registry.add('one2many_selectable', One2ManySelectable);
});

When I change the code

events: {
            "click td.o_list_record_selector": "get_id_lines",
        },

to

events: {
            "click th.o_list_record_selector": "get_id_lines",
        },

it is working fine but when i also check the checkbox in the td of the table it wont call the get_id_lines function it's only working when i check the checkbox on the thead part of the table




lundi 23 mars 2020

How to add validation for checkboxes in JQuery?

I have a form like below and I want to add vaidation for JQuery, I tried using html required attribute but it is not working, help me in this

The code is

//question 1
<label class="container">
  <input class="chk check_answer1" type="checkbox" name="answers[]" value='1' required="required">
  <span class="checkmark"></span>
</label>
<label class="container">
  <input class="chk check_answer1" type="checkbox" name="answers[]" value='1" required="required">
  <span class="checkmark"></span>
</label><label class="container">
  <input class="chk check_answer1" type="checkbox" name="answers[]" value='1" required="required">
  <span class="checkmark"></span>
</label>

//question 2
<label class="container">
  <input class="chk check_answer2" type="checkbox" name="answers[]" value='2' required="required">
  <span class="checkmark"></span>
</label>
<label class="container">
  <input class="chk check_answer2" type="checkbox" name="answers[]" value='2" required="required">
  <span class="checkmark"></span>
</label><label class="container">
  <input class="chk check_answer2" type="checkbox" name="answers[]" value='2" required="required">
  <span class="checkmark"></span>
</label>

//question 3
<label class="container">
  <input class="chk check_answer3" type="checkbox" name="answers[]" value='3' required="required">
  <span class="checkmark"></span>
</label>
<label class="container">
  <input class="chk check_answer3" type="checkbox" name="answers[]" value='3" required="required">
  <span class="checkmark"></span>
</label><label class="container">
  <input class="chk check_answer3" type="checkbox" name="answers[]" value='3" required="required">
  <span class="checkmark"></span>
</label>

This is the code I wrote and In this page the user has to select atleast one option for every question




Python PyQt5 - Checkbox to add and remove itens from a list

I'm building a user interface with PyQt5 (and python 3.7) which I'm using a check box to add elements in a general list (input_columns_general) when it's checked and remove/delete then when unchecked. Every time when I check a check box the added elements must follow a default position order in the specific list. With this task I'm having two problems:

  1. For each one of the check boxes that I have I need to build up a function which call the separately the "isChecked()" class and the correspond list that I want to add to "input_columns_general". In the case below I showed 2 lists: input_columns_mixer (with one element) and input_columns_microreactor (with five elements). How can I build up just one function (def) able to receive both situations?

  2. When I check a check box, the idea is the correlated list receive the correspondent list always at the correct postion of the general list (input_columns_general). As example: should "input_columns_microreactor" be always the first elements and "input_columns_mixer" be after "input_columns_micrreactor" without considering which one was checked first. I'm dealing with 4 check boxes and each one of them has a list which must be added regarding the correct position independently if other check box was pressed in order or not.

In the code showed below, regard a try that consider how can I add and remove the elements of the general list (but it doesn't work properly due it's not deleting all the desired elements in the list), and I didn't figure a way how can I always place in the correct position new list elements.

Do someone has a hint about this case?

I hope that I described enough code to the code be understandable about the task I'm seeking.

""'

```
    self.mixer_checkbox = QtWidgets.QCheckBox(self.tab_2)
    self.mixer_checkbox.setObjectName("mixer_checkbox")
    self.mixer_checkbox.stateChanged.connect(lambda: self.state_changed_mixer(self.mixer_checkbox)) 
    self.microreactor_checkbox = QtWidgets.QCheckBox(self.tab_2)

    self.mixer_checkbox = QtWidgets.QCheckBox(self.tab_2)
    self.microreactor_checkbox.setObjectName("microreactor_checkbox")
    self.microreactor_checkbox.stateChanged.connect(lambda:self.state_changed_microreactor(self.microreactor_checkbox))

def state_changed_mixer(self, int):
    if self.mixer_checkbox.isChecked():
        input_columns_general[4:5] = input_columns_mixer
    else:
        for element in input_columns_mixer:
            input_columns_general.remove(element)


def state_changed_microreactor(self, int):
    if self.microreactor_checkbox.isChecked():
        input_columns_general[0:4] = input_columns_microreactor
    else:
        for element in input_columns_microreactor:
            input_columns_general.remove(element)


```



React JS Material-UI Table Checkbox and Row

I want to differentiate between a checkbox click and a row click. For example I want this behaviour, when I click the checkbox, only the checkbox is checked and when I click the row, only the row is selected but the checkbox is not selected. How can I achieve this?

Below is my code

handleClick = (row) => {
var self = this;
var currentlist = self.state.routelist;

let newarray = [...this.state.routelist];

if (newarray[row].isselected === true) {
  newarray[row].isselected = false;
} else if (newarray[row].isselected === false) {
  newarray[row].isselected = true;
}

self.setstate({ routelist: newarray });

if (!isnan(row)) 
{
    var pos = 
    {
      routeid: currentlist[row].routeid,
      isvisible: currentlist[row].isselected
    };

    var param = {
      receiver: "event_map",
      command: "show_route",
      data: pos
    };

    //console.log("show_route: " + param.data.routeid + " visible: " + param.data.isvisible);
    this.msgdispatcher.triggermessagedispatcher(param);

    //zoom to route
    if (currentlist[row].routeid != null ||currentlist[row].routeid != undefined) 
    {
      var param = {
        receiver: "event_map",
        command: "zoom_to_route",
        data: currentlist[row].routeid
      };

      //console.log("zoom_to_route: routeid=" + param.data);
      this.msgdispatcher.triggermessagedispatcher(param);
    }
}
}

And here is the render method

render() {
return (
  <div style=>
    <div style=>
    <Table  
        onCellClick={this.handleClick}
        height={window.innerHeight}
        multiSelectable={this.state.multiSelectable}
        selectable={this.state.selectable}
      >
        <TableBody 
          displayRowCheckbox={this.state.displayRowCheckbox}
          showRowHover={this.state.showRowHover}
          deselectOnClickaway={this.state.deselectOnClickaway}
          >
          {this.state.routeList.map((row, index) => (
            <TableRow
              key={index}
              style=
              selected={this.state.routeList[index].isSelected}
            >
              <TableRowColumn style=>
                <ListItem
                  style=
                  primaryText={row.Description}
                  secondaryText={
                    <div>
                      <div>
                        {"Direction : " + row.EntryDirection + " > " + row.ExitDirection}
                      </div>
                      <div>{"Distance (meter) : " + row.Distance}</div>
                    </div>
                  }
                  secondaryTextLines={5}
                />
              </TableRowColumn>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      <hr />
    </div>
  </div>
);
}



the sub checkbox is not working or not clickable as long as I add scss

I am making checkbox with sub checkboxes. All the functions works fine without scss. I wonder why as long as I add scss, only the main checkbox is working but not the sub checkboxes. I found out it seems like once the scss is applied, my mouse can only access the main checkbox but when the mouse is trying to indicate the sub options..it only can access the .checkbox area. photo for showing when mouse is trying to hover over the sub options

Could anyone please advise? Thank you very much!

    <div className="checkbox">
        <label htmlFor="option" className="checkbox__label checkbox__label--parent">

            <input
                type="checkbox"
                id="option"
                ref={parentRef}
                onChange={handleAllChecked}
                className="checkbox__input checkbox__input--main"
            />

            <span className="checkbox--fake"/>
            {/* <span>All</span> */}
        </label>

        <ul className="checkbox__list">
            {options.map((opt, i) => {
                return (
                    <li key={opt.id} className="checkbox__list--item">
                        <label htmlFor={opt.country} className="checkbox__label 
                         checkbox__label--subOption">
                            <input
                                type="checkbox"
                                name={opt.country}
                                className="checkbox__input checkbox__input--subOpt"
                                checked={opt.checked}
                                onChange={handleOptions}
                                value={opt.country}
                            />
                            <span className="checkbox--fake"/>
                            {/* <span>{opt.country}</span> */}
                        </label>
                    </li>
                );
            })}
        </ul>
        <label htmlFor="disabled" className="checkbox__label--disabled">
        <input type="checkbox" disabled className=" checkbox__input checkbox__input-- 
             disabled"/>
        Disabled
        </label>
    </div>
Scss part
  .checkbox {
      &__label {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 30px;
    margin: 0 auto;
    border-radius: 5px;
    background: transparent;
}
&__input{
    border: 0;
    padding: 0;
    width: 1px;
    height: 1px;
    margin: -1px;
    opacity: 0;
    position: absolute;

    &:not(:disabled) {
        &:checked {
            + span {
                background-color: #6200eeff;
                &::after {
                    content: '';
                    opacity: 1;
                    height: 6px;
                    width: 12px;
                    -webkit-transform-origin: left top;
                    transform-origin: left top;
                    border-left: 2px solid #f9f9f9;
                    border-bottom: 2px solid #f9f9f9;
                    left: 50%;
                    top: 50%;
                    border-radius: 0;
                    position: absolute;
                    transition: all .3s ease; /* to define how the effect will be */
                }
            }

            &:hover {
                + span {
                    box-shadow: 0px 0px 0px 12px rgba(72, 35, 219, 0.15);
                }
            }
        }
    }
    &:not(:disabled) {
        &:hover {
            + span {
                box-shadow: 0px 0px 0px 12px rgba(131, 131, 131, 0.15);
            }
        }
        &:focus {
            + span {
                box-shadow: 0px 0px 0px 12px rgba(131, 131, 131, 0.35);
            }
        }
        &:active {
            + span {
                box-shadow: 0px 0px 0px 12px rgba(131, 131, 131, 0.35);
            }
        }
    }
}
&--fake {
    width: 24px;
    height: 24px;
    position: relative; 
    background-color: #6200eeff;
    border-radius: 2px;
    display: block; 
    transition: all .5s ease;

    &::after {
        opacity: 0;
        height: 24px;
        width: 24px;
        border-radius: 50%;
        content: '';
        left: 50%;
        top: 50%;
        transform: translate(-50%) rotate(-45deg);
        position: absolute; 
    }
}
&__list {
    list-style: none;
    pointer-events: none;
    &--item {
        margin: 10px;
    }
}

}