mercredi 29 décembre 2021

How to filter dropdown from ajax to display checkbox with the name on it?

How can i filter drop down list that when i select the type it shows the type that on ajax response in the checkbox of the name

This is the code for html

<div class="container position">
  <div class="row">
    <label for="recyclable-type" class="col-form-label"> <b>Recyclable Type:</b> </label> &nbsp;&nbsp;
    <select id="recyclable-type" name="recyclable-type" class=" custom-select col-4">
      <option selected value="">All</option>

    </select>
  </div>
</div>

<div class="container-body ">
  <div id="checkbox" class="checkbox">

  </div>
</div>

This is the code for ajax where i call my drop down and checkbox for type and name

$.ajax({
                // The url that you're going to post
                /*

                This is the url that you're going to put to call the
                backend api,
                in this case, it's
                https://ecoexchange.dscloud.me:8090/api/get (production env)

                */
                url:"https://ecoexchange.dscloud.me:8090/api/get",
                // The HTTP method that you're planning to use
                // i.e. GET, POST, PUT, DELETE
                // In this case it's a get method, so we'll use GET
                method:"GET",
                // In this case, we are going to use headers as
                headers:{
                    // The query you're planning to call
                    // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
                    query:"RecyclableTypeGet()",
                    // Gets the apikey from the sessionStorage
                    apikey:sessionStorage.getItem("apikey")
                },
                success:function(data,textStatus,xhr) {
                    // console.log(data);
                    for (let i = 0;i<data.length;i++) {
                        $("#recyclable-type").append(
                            `
                            <option val="${data[i]["RecyclableType"]}">${data[i]["RecyclableType"]}</option>
                            `
                        );
                        // can also use this way
                        // $("#select-recyclables").append(
                        //  `
                        //  <option val="${data[i]["RecyclableType"]}">${data[i]["RecyclableType"]}</option>
                        //  `
                        // );
                    }
                },
                error:function(xhr,textStatus,err) {
                    console.log(err);
                }
            });


            $.ajax( {
            url: 'https://ecoexchange.dscloud.me:8090/api/get',
            type: 'GET',
            dataType: 'json',
            headers:{
                query: "RecyclableGet(0)",
                // Gets the apikey from the sessionStorage
                apikey: sessionStorage.getItem("apikey")
            },
            success: function(data) {
            //console.log(data);
            var html='';
            $.each(data, function(key, value) {
                html +='<input type="checkbox" name="recyclable_id[]" value="'+value.RecyclableID+'"><label style="padding-left: 10px;">'+value.Name+'</label><br>';
                //console.log(value)
            });
            $('#checkbox').html(html);

            }
        });

This is how my ajax response look like

[
    {
        "RecyclableID": 1,
        "Name": "recyclable",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 3,
        "Name": "test recyclable 2",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 129,
        "Name": "test recyclable 4",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 131,
        "Name": "test recyclable 6",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 132,
        "Name": "test recyclable 7",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 133,
        "Name": "test recyclable 8",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 134,
        "Name": "test recyclable 34",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 138,
        "Name": "recyclable thing",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 139,
        "Name": "recyclable thing 2",
        "RecyclableType": "Ewaste"
    },
    {
        "RecyclableID": 153,
        "Name": "test recyclable 10",
        "RecyclableType": "Other"
    },
    {
        "RecyclableID": 154,
        "Name": "test recyclable 11",
        "RecyclableType": "Ewaste"
    },
    {
        "RecyclableID": 155,
        "Name": "test recyclable 123",
        "RecyclableType": "test recyclable type 2"
    },
    {
        "RecyclableID": 159,
        "Name": "some recyclable name",
        "RecyclableType": "CC"
    },
    {
        "RecyclableID": 161,
        "Name": "some recyclable name 2",
        "RecyclableType": "Ewaste"
    },
    {
        "RecyclableID": 162,
        "Name": "recyclable 2",
        "RecyclableType": "test recyclable type 2"
    },
    {
        "RecyclableID": 165,
        "Name": "test recyclable 15",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 166,
        "Name": "test recyclable 18",
        "RecyclableType": "testing type"
    },
    {
        "RecyclableID": 167,
        "Name": "some recyclable name 23",
        "RecyclableType": "Ewaster"
    },
    {
        "RecyclableID": 168,
        "Name": "Lorem ipsum dolor sit amet, consectetur",
        "RecyclableType": "test recyclable type"
    },
    {
        "RecyclableID": 169,
        "Name": "Copper",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 170,
        "Name": "Choking Bar",
        "RecyclableType": "Ewaste"
    },
    {
        "RecyclableID": 171,
        "Name": "Cabinet",
        "RecyclableType": "Other"
    },
    {
        "RecyclableID": 172,
        "Name": "Cash Box",
        "RecyclableType": "WASTE"
    },
    {
        "RecyclableID": 173,
        "Name": "Copper Telephone Cable",
        "RecyclableType": "Other"
    },
    {
        "RecyclableID": 174,
        "Name": "Rope",
        "RecyclableType": "CC"
    },
    {
        "RecyclableID": 175,
        "Name": "Silver",
        "RecyclableType": "test recyclable type"
    }
]

This is how example image of the website look like when i have call the ajax enter image description here

Now i would wan that if the type is selected it display the name to whatever the type it has in the ajax response how can i do it ?




mardi 28 décembre 2021

how to make a checkbox and check the state of it(if its correct or no)

hello i want to make 3 checkboxes one saying cpu, one saying gpu and one saying cll and i want to check if the answer is correct so can u show me how to do that

import time
import tkinter as tk

import pygame

window = tk.Tk()
pygame.mixer.init()
img = tk.PhotoImage(file='C:\\Users\\laithmaree\\PycharmProjects\\create_apps_with_python\\brainicon.ico.png')
window.title("Quiz Game")
# pygame.mixer.music.load('ForestWalk-320bit.wav')
# pygame.mixer.music.play()
# i created an icon
# i made a title


window.geometry("800x600")
window.resizable(width=False, height=False)
window.iconphoto(False, img)


label1 = tk.Label(window, text='Quiz App', font=("Arial Bold", 25))
label1.pack()

txtbox = tk.Entry(window, width=50)


def playbuttonclicked():
    label1.destroy()
    playbtn.destroy()
    quitbtn.destroy()
    label2 = tk.Label(window, text='What is the short form of computer science',font=("Arial Bold", 25))
    label2.pack()
    txtbox.place(x=250, y=200, height=40)

    def chkanswer():
        useranswer = txtbox.get()  # Get contents from Entry
        if useranswer == 'cs':
            lblcorrect = tk.Label(window, text='correct', )
            lblcorrect.pack()
            def delete():
                lblcorrect.destroy()
                label2.destroy()
                txtbox.destroy()
                submitbtn.destroy()
                label3 = tk.Label(window, text='whats is the short form of central proccessing unit', font=('Arial Bold', 25))
                label3.pack()
            lblcorrect.after(1001, delete)

        else:
            lblwrong = tk.Label(window, text='Try Again')
            lblwrong.pack()

            def deletefunction():
                lblwrong.destroy()

            lblwrong.after(1000, deletefunction)









    submitbtn = tk.Button(window, text='Submit', font=('Arial Bold', 30), command=chkanswer, bg='red')
    submitbtn.place(x=305, y=400)
    submitbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
    submitbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))


playbtn = tk.Button(window, text='Play', font=("Arial Bold", 90), bg='red', command=playbuttonclicked)
playbtn.place(x=10, y=200)
playbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
playbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))


def quitbuttonclicked():
    window.destroy()


quitbtn = tk.Button(window, text='Quit', font=("Arial Bold", 90), bg='red', command=quitbuttonclicked)
quitbtn.place(x=400, y=200)
quitbtn.bind('<Enter>', lambda e: e.widget.config(bg='grey'))
quitbtn.bind('<Leave>', lambda e: e.widget.config(bg='red'))
window.mainloop()

the question is label 3 (whats is the short form of central proccessing unit) and i want to make sure the answer is correct because i am creating a quiz app thx




dimanche 26 décembre 2021

To keep the checkbox checked once checked while browsing entire website

I am using the checkbox to toggle the black and dark theme color using HTML, CSS, and JS. I have this code inside my navbar. It is working well. But once refreshed or changed to other pages inside the website, it no longer stays dark.

<div>
  <input type="checkbox" class="checkbox" id="chk" />
  <label class="label" for="chk">
    <i class="fas fa-moon"></i>
    <i class="fas fa-sun"></i>
    <div class="ball"></div>
   </label>
</div>

Someone suggested the concept of using local storage and I tried this, but it's not working.

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
});


// for checkbox remained checked

document.getElementById('chk')(function(){
    var test = localStorage.input === 'true'? true: false;
    document.getElementById('chk')('input').prop('checked', test || false);
});

document.getElementById('chk')('input').on('change', function() {
    localStorage.input = document.getElementById('chk')(this).is(':checked');
    console.log(document.getElementById('chk')(this).is(':checked'));
});

Please somebody help me.

PS: I'm not a web developer. I use HTML and CSS from here and there for my blog. I'm using GitHub pages to host my website. https://amatya-aditya.github.io/




mercredi 22 décembre 2021

Flutter: CheckboxListTile inside ListView jumps to top

So I know there are some similar questions about this issue but none of them worked for me. I have a ListView with different CheckboxListTiles and when I scroll down and choose an item, the ListView automatically jumps to the top. Is there a way to prevent this from happening? Thank you very much! I've added a screenshot, so you can better understand. This is my code:

class CheckboxWidget extends StatefulWidget {
  const CheckboxWidget({
    Key key,
    this.item,
    this.type,
    this.state,
  }) : super(key: key);

  final Map<String, bool> item;
  final String type;
  final Map<String, dynamic> state;

  @override
  State<CheckboxWidget> createState() => _CheckboxWidgetState();
}

class _CheckboxWidgetState extends State<CheckboxWidget> {
  @override
  void initState() {
    super.initState();
    if (widget.state[widget.type].isEmpty) {
      widget.item.updateAll((key, value) => value = false);
    }
  }

  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    final FilterProvider filterProvider = Provider.of<FilterProvider>(context);

    return Expanded(
      child: ListView(
        key: UniqueKey(),
        children: widget.item.keys.map(
          (key) {
            return CheckboxListTile(
              contentPadding: EdgeInsets.only(left: 2, right: 2),
              title: Text(
                key,
                style: TextStyle(fontSize: 19, fontWeight: FontWeight.w400),
              ),

              value: widget.item[key],
              activeColor: Color(0xffF6BE03),
              checkColor: Color(0xff232323),
              shape: CircleBorder(),
              //contentPadding: EdgeInsets.all(0),
              onChanged: (value) {
                value
                    ? filterProvider.multifiltervalue = [widget.type, key]
                    : filterProvider.multifiltervalue = [
                        widget.type,
                        key,
                        false
                      ];
                setState(
                  () {
                    widget.item[key] = value;
                  },
                );
              },
            );
          },
        ).toList(),
      ),
    );
  }
}



How to customize MaterialCheckBox in android?

I want to make a circular MaterialCheckBox it works perfectly as circular but the color of the circle is changed this is not the color which I set in ic_checked and ic_unchecked. Here is my code. why this is not picking the vector color

XML layout

 <com.google.android.material.checkbox.MaterialCheckBox
            android:id="@+id/selection_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:button="@drawable/custom_checkbox"
            />

drawable/custom_checkbox

<?xml version="1.0" encoding="utf-8"?>
<selector  xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:drawable="@drawable/ic_checked"/>
    <item
        android:state_pressed="true"
        android:drawable="@drawable/ic_checked"/>
    <item
        android:state_pressed="false"
        android:drawable="@drawable/ic_unchecked"/>
</selector>

drawable/ic_checked

<vector android:height="20dp" android:tint="#F44336"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="20dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#ffffff" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z"/>
</vector>

drawable/ic_unchecked

<vector android:height="20dp" android:tint="#FFFFFF"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="20dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FF000000" android:pathData="M12,2C6.47,2 2,6.47 2,12s4.47,10 10,10 10,-4.47 10,-10S17.53,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>



dimanche 19 décembre 2021

How to make in vuejs remove all and select all checkbox after upload image

I want to make a method that when executed will check all inputs that have images and text, where this method will run on the input checkbox with the label Select All, which when select all is checked automatically all the input checkboxes on the uploaded image will be checked. Like the example I made on the imageChecked() method which worked successfully where when the input is checked, the checked image data will be entered/returned to the image array in crudData{‘image’:[]}, and the text input data will be entered/returned to the array name in crudData{‘name’:[]}. Does anyone understand the case I’m asking about? Thank you.

Here is the complete code https://jsfiddle.net/cd59bLxu/1/

export default {
  data() {
    return{
      crudData:{
        ‘id’: null,
        ‘name’: [],
        ‘image’: [],
        ‘arrImage’: [],
      },
    }
  },
  methods: {
    imageChecked() {
      let checkedImages =          this.crudData.arrImage.filter(img =>   img.checked)
      this.crudData.image =   checkedImages.map(img => img.image)
      this.crudData.name = checkedImages.map(img => img.name)
      console.log({imageFiles:    this.crudData.image, names:       this.crudData.name})
    },
    selectAll(){
      ..... the code will create in here
    },
    removeAll(){
      ..... the code will create in here
    }
  }}



samedi 18 décembre 2021

Customize hover effect for Bootstrap checkbox

Starting with this answer, I'm trying to avoid the hover effect on a Bootstrap checkbox that appears like a button:

<input type="checkbox" class="btn-check" id="btn-enable-cromo" autocomplete="off" checked>
<label class="btn btn-outline-success btn-sq-responsive" for="btn-enable-cromo"><img src="images/Cromo.svg" /></label>

in CSS:

.btn-check:hover,
.btn-sq-responsive:hover {
    color: transparent;
}

I need this because on both desktop or mobile environment, when you click (or tap) on the checkbox you don't see anything until you click (or tap) elsewhere. The hover color is identical to the checked one so you have no feedback about.

Instead my goal is to show the actual state of the checkbox immediately.

The code above changes nothing: the behavior is the same. I'm using the Bootstrap v5.1.3.




select checkbox, previous selected check box will uncheck in excel

I have an excel file that I place a check box as I cannot use the radio button due the check box is linked with formula on excel, in the selection i.e. 1 2 3 4 if I select check box 1, then I select check box 3, check box 1 check should uncheck automatically

Sample Picture




How can i do multiple values filter for multiple fields in Django?

for loc,deg,dept,key,job_role,insti_loc,insti_name,mark,gen,job_type in zip(lst2,lst5,lst6,lst1,lst4,lst8,lst9,lst10,lst11,lst12):

        if sample_register.objects.filter(city=loc,job_role_1=job_role,qualification=deg,qualification_dept=dept).exists():
            print("Inside location and jobrole1 and qualification and department search")
            for i,j,k,l in zip(lst5,lst2,lst6,lst4):
                pro_log=sample_register.objects.filter(Q(city=j) & Q(job_role_1=l) & Q(qualification=i) &  Q(qualification_dept=k))
                



React mui 5 checkbox don't change value under function

When Checkbox is under a FormControlLabel and function, the value don't change when useState change another variable.

If I comment the useState, checkbox works.

If I move the same code (checkbox and formcontrolLabel) on a render, not in function, checkbox work.

The sample code :

import * as React from "react";
import {
  Theme,
  useTheme,
  Box,
  Stack,
  Checkbox,
  FormControlLabel,
} from "@mui/material";

export const RunnerRaces2: React.FC<{}> = (props) => {
  const theme = useTheme();
  const [dataSource, setDataSource] = React.useState<[]>(
  );
  const FrmCheckBox: React.FC<{ label: string }> = (props) => {
    const [checked, setChecked] = React.useState(true);
    return (<FormControlLabel
      label={props.label}
      control={
        <Checkbox
          // checked={checked}
          // defaultChecked
          size="small"
          onChange={(
            event: React.ChangeEvent<HTMLInputElement>
          ) => {
            const value = event.target.checked;
            setDataSource([]);
          }}
        />
      }
    />);
  };

  return (
    <Box>
      <Stack
        direction="row"
      >
        <FrmCheckBox
          label={"t1"} />
        <FrmCheckBox
          label={"t2"} />
        <FrmCheckBox
          label={"t3"} />
        <FrmCheckBox
          label={"t4"} />
      </Stack>
    </Box>
  );
};

I don't understand, it's mui 5 bug ? react bug ? or a wrong code from me ?

sample on codesandbox.io




vendredi 17 décembre 2021

Vuejs multiple forms different values same method

I have a page with three same forms but with differents dynamic values each. What i want to achive is to take the inputs of the specifiec form when checkbox checked. My work so far is:

<form ref="form">
  <label class="form-check-label">
    <input ref="submit" type="checkbox" value="1" name="question" @click="choiceCheck">
    <input type="text" :value="dynamic feedback 1" name="feedback">
    <input type="number" :value="dynamic points 1" name="points">
    <h2>Dynamic value 1</h2>
  </label>
</form>
<form ref="form">
  <label class="form-check-label">
    <input ref="submit" type="checkbox" value="2" name="question" @click="choiceCheck">
    <input type="text" :value="dynamic feedback 2" name="feedback">
    <input type="number" :value="dynamic points 2" name="points">
    <h2>Dynamic value 2</h2>
  </label>
</form>
<form ref="form">
  <label class="form-check-label">
    <input ref="submit" type="checkbox" value="2" name="question" @click="choiceCheck">
    <input type="text" :value="dynamic feedback 3" name="feedback">
    <input type="number" :value="dynamic points 3" name="points">
    <h2>Dynamic value 3</h2>
  </label>
</form>

And my script

export default {
  data() {
    return {
      inputs: [],
      feedback: "",
      points: "",
    };
  },

  methods: {
    choiceCheck () {
      this.$refs.submit.click()
      console.log(
       this.$refs.form.feedback.value + this.$refs.form.points.value)
    },
  },
};

With this method take always the last form fields, i want when check the checkbox to take form data belong to this checkbox!




List Index value is -1 even after selecting all items in listbox

Background: I have a userform in MS Access with a MultiColumn (2 colums) listbox, One checkbox and a command button. The Multicolumn listbox provides output via a query, the check box (name- Select all) used to select all the lines in the listbox and the command button is to get the values selected in the listbox and delete them.

Problem: The Select All check box checks all the selected items in the listbox, but when i use the command button to delete the values i still get row index as -1

Code behind the checkbox

Me.List45.SetFocus
If Me.Check55.Value = True Then 
    For i = 0 To Me.List45.ListCount
    Me.List45.Selected(i) = True
    Next i
Else
    For i = 0 To Me.List45.ListCount
    Me.List45.Selected(i) = False
    Next i

End If

Code in the Command button

rowIndex = Me.List45.ListIndex
If rowIndex = -1 Then
MsgBox "Select an Item in List Box!", vbApplicationModal
Exit Sub
End If

If i select any value in the list box and try to delete it works fine - any suggestions what i am missing here.




jeudi 16 décembre 2021

Flutter/Dart - Cannot modify unmodifiable map error

Ive created an app with Flutter bloc package.Ive created a screen named learning_dashboard_screen which contains a list fetched from a server. inside that same screen I have a filter button which on press will show a filter screen using the bottom sheet widget.

enter image description here

it has got different categories for the list to be filtered. In the learning_dashboard_screen_state screen Ive got a Map named filteroptions which is of type Map<String, Map<String, dynamic>>.This map is used to populate the checkboxes by mapping the map with the checkbox widget.

part of 'learning_dashboard_screen_bloc.dart';

class LearningDashboardScreenState extends Equatable {
  static ScrollController controller = ScrollController();
  final int courseLimit = 3;
  final List<GPaginatedCoursesData_paginatedCourses_data> courses;
  final DataRetrievalStatus initialCoursesStatus;
  final Map<String, Map<String, dynamic>> filterOption;
 Map<String, Map<String, dynamic>> getFilterOption() {
    return filterOption;
 }

  final int currPage;
  final bool hasNextPage;
  final DataRetrievalStatus moreCoursesStatus;

  LearningDashboardScreenState(
     {this.courses = const [],
     this.initialCoursesStatus = DataRetrievalStatus.NOT_INITIALIZED,
     this.filterOption = const {
      "Certificate Provider": {"NVQ": false, "City and Guilds": false},
      "Course Language": {"Sinhala": false, "English": false, "Tamil": false},
      "Duration": {"6 Months": false, "8 Months": false, "1Year": false},
      "Category": {
        "Baby Care": false,
         "First Aid": false,
          "Adult Care": false,
          "Mental Care": false,
          "Physiotherapy": false,
          "Baby First Aid": false,
          "Light Housekeeping": false,
           "Assist Methods": false
         }
       },
       this.currPage = 0,
       this.hasNextPage = false,
       this.moreCoursesStatus = DataRetrievalStatus.NOT_INITIALIZED});

      @override
      List<Object?> get props => [
       courses,
       filterOption,
      initialCoursesStatus,
      courseLimit,
      currPage,
      hasNextPage,
      moreCoursesStatus
     ];

   LearningDashboardScreenState copyWith(
        {List<GPaginatedCoursesData_paginatedCourses_data>? course,
         DataRetrievalStatus? courseStatus,
         int? currPage,
         bool? hasNextPage,
         Map<String, Map<String, dynamic>>? filterOption,
         DataRetrievalStatus? moreCourseStatus}) {
        return LearningDashboardScreenState(
          courses: course ?? this.courses,
          filterOption: filterOption ?? this.filterOption,
          initialCoursesStatus: courseStatus ?? this.initialCoursesStatus,
          currPage: currPage ?? this.currPage,
          hasNextPage: hasNextPage ?? this.hasNextPage,
           moreCoursesStatus: moreCourseStatus ?? this.moreCoursesStatus);
         }

         ScrollController getScrollController() {
           return controller;
         }
       }

what I want is to change the boolean value of the filteroption map in the state according to the chackbox value. For that what Ive done is ,

1.I created an event in the event class ,

  class CheckBoxValueChangedEvent extends LearningDashboardScreenEvent {
   String filterOption;
   String filterValue;
   bool isChecked;


  CheckBoxValueChangedEvent({required this.filterOption,required this.filterValue,required 
     this.isChecked});

  @override
   List<Object?> get props => [];
  }
  1. I called that event in the on press of the checkbox

                CheckBox(
                   label: entry.key,
                   onChanged: (isChecked) {
                      context
                   .read<LearningDashboardScreenBloc>()
                   .add(CheckBoxValueChangedEvent(filterOption: widgetName, filterValue: 
                    entry.key, isChecked: isChecked));
    
             },
             key: GlobalKey<CheckBoxState>(),
             initValue: entry.value,
           ),
    

3.In the bloc class I wrote the function to change the bool value in the state class and emit the state,

void _onCheckBoxValueChangedEvent(CheckBoxValueChangedEvent event,
  Emitter<LearningDashboardScreenState> emit) {
Map<String, Map<String, dynamic>> filterOption = {};
filterOption=new Map<String, Map<String, dynamic>>.from(state.filterOption);
if (event.isChecked = true) {
  filterOption[event.filterOption]![event.filterValue] = true;
} else {
  filterOption[event.filterOption]![event.filterValue] = false;
}
emit(state.copyWith(filterOption: filterOption));

}

My problem is when I tick a checkbox I get,

Error: Unhandled error Unsupported operation: Cannot modify unmodifiable map occurred in 
 Instance of 'LearningDashboardScreenBloc'.



mercredi 15 décembre 2021

Theme switcher not working - Uncaught TypeError: checkbox is null [duplicate]

The problem:


When i click the "checkbox" it's supposed to change the theme of the website, but it't prints out an error in the console.

Uncaught TypeError: checkbox is null

I watched many videos but it still wouldn't work.

Sources:

-Html

<label id="colorswitch" for="switcher">
   <input type="checkbox" id="switcher">
   <span class="slider round"></span>
</label>
<p class="switchtext">Light mode</p>

-CSS

:root {
   --linkcolor: rgb(241, 165, 0);
   --bgcolor: rgb(30, 30, 30);
   --gridbgcolor: rgb(40, 40, 40);
   --textcolor: rgb(220, 220, 220);
   --logobgcolor: rgb(80, 80, 80);
   --logobghovercolor: rgb(110, 110, 110);
}

body[data-theme="light"] {
   --linkcolor: rgb(220, 220, 220);
   --bgcolor: rgb(220, 220, 220);
   --gridbgcolor: rgb(220, 220, 220);
   --textcolor: rgb(220, 220, 220);
   --logobgcolor: rgb(220, 220, 220);
   --logobghovercolor: rgb(220, 220, 220);
}

-Javascript

const checkbox = document.getElementById('switcher');
checkbox.addEventListener('change', (e) => {
    if (e.target.checked) {
        document.body.setAttribute('data-theme', 'light')
    } else {
        document.body.setAttribute('data-theme', 'dark');
    }
});


if (e.target.checked) {
    document.documentElement.setAttribute('data-theme', 'light');
    localStorage.setItem('theme', 'light');
}
else {
    document.documentElement.setAttribute('data-theme', 'dark');
    localStorage.setItem('theme', 'dark');
}



mardi 14 décembre 2021

Anyone who can help me with this problem today is my daedline so I hope everyone can help me

enter image description here

I need to calculate the total of this table, if each tick in the checkbox is finished, then the total amount selected in the above table can be calculated.




Rails permit params not working for multiple checkboxes and multi select

Creating new entry for Associate model have book_id and tag_id. My requirement is to have a list of checkboxes of books and multi-select for tags, which I have done like that

<%= form.collection_check_boxes(:book_id, books_hash, :last, :first) do |b| %>
  <div class="form-check form-check-inline">
      <%= b.check_box class: 'form-check-input' %>
      <%= b.label class: 'form-check-label' %>
  </div>
<% end %>

<div class="field">
   <%= form.label :tag_id %>
   <%= form.select :tag_id, options_for_select(Tag.pluck(:title,:id)), {}, {:multiple => true, :class => "chzn-select" } %>
</div>

Permit params are like this

params.require(:book_tag).permit(book_id: [], tag_id: [])

But issue is that when I save the record it gives an error

ActiveRecord::RecordInvalid (Validation failed: Book must exist, Tag must exist):

I can't understand what exactly i am missing.




lundi 13 décembre 2021

Accessing widgets using global keys in dart

Ive got a Map of data type Map<String, Map<String, Key?>> in the state with data

Map<String, Map<String, Key?>> filterOption = {
"Certificate Provider": {
  "NVQ": GlobalKey(),
  "City and Guilds": GlobalKey()
},}

and I use this list to populate 2 check boxes by mapping the list to a custom checkbox widget I made .

Widget certificateProvider(
  BuildContext context, Map<String, Key?> widgetData) {
return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: widgetData.entries
        .map(
          (entry) => CheckBox(
            label: entry.key,
            onChanged: (value) {},
            key: entry.value,
          ),
        )
        .toList());

} complete ui

A global key is from the state list above is passed to identify the checkboxes uniquely. What I want is , when The apply button is clicked... the program should use the global key to iterate through each checkbox to see if its checked or not . How can I access the checkboxed uniquely with the global key ?




dimanche 12 décembre 2021

How to implement “select all” check box in contact form 7

I am having 10 options in checkboxes but also want a select all option where all 10 boxes are automatically highlighted




VueJs3 checkbox automatically checked all when select all after upload image

I want to make a method that when executed will check all inputs that have images and text, where this method will run on the input checkbox with the label Select All, which when select all is checked automatically all the input checkboxes on the uploaded image will be checked. Like the example I made on the imageChecked() method which worked successfully where when the input is checked, the checked image data will be entered/returned to the image array in crudData{'image':[]}, and the text input data will be entered/returned to the array name in crudData{'name':[]}. Does anyone understand the case I'm asking about? Thank you.

Here is the complete code https://jsfiddle.net/ntkpx7c0/5/

<script>
export default {
    data() {
        return{
            crudData:{
                'id': null,
                'name': [],
                'image': [],
                'arrImage': [],
            },
        }
    },
    methods: {
        imageUpload(e, maxItem){                    
            ....
        },
        uploadImage(e){
            ...
        },
        removeImage(key){
            ...
        }, 
        imageChecked() {
            let checkedImages = this.crudData.arrImage.filter(img => img.checked)
            this.crudData.image = checkedImages.map(img => img.image)
            this.crudData.name = checkedImages.map(img => img.name)
            console.log({imageFiles: this.crudData.image, names: this.crudData.name})
        }
    }


}



samedi 11 décembre 2021

How to get row index in material table Angular

How to get row index in material table angular

 <td mat-cell *matCellDef="let row">                                                                            
   <mat-checkbox (click)="$event.stopPropagation()"                                                                                
     (change)="$event ? selection.toggle(row) : null;isSomeSelected()"                                                                               
     [checked]="selection.isSelected(row)">                                                                           
 </mat-checkbox></td>



jeudi 9 décembre 2021

How to get the values from CheckboxListTile together with TextField inputs for a model class

I have a form with Textfields, checkboxes and radio buttons. I am sending the data from the form to an api, I have a modal class called User and an APIService class. I am looking for a way to get the values from the checkboxes.

Here is how the checkboxes are, there is a list of interest

List<Map> interests = [
    {
      "name": "Football",
      "isChecked": false
    },
    {
      "name": "Hand Ball",
      "isChecked": false
    },
];

The widget shows the checkboxes and the selected items, There is also

Container(
              margin: EdgeInsets.all(2),
              child: TextField(
                controller: nameController,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Name',
                ),
              ),
            ),
            SizedBox(height: 10,),
            Column(
                children: interests.map((interests) {
                  return CheckboxListTile(
                      value: interests["isChecked"],
                      title: Text(interests["name"]),
                      onChanged: (newValueInterests) {
                        setState(() {
                          interests["isChecked"] = newValueIntersts;
                        });
                      });
                }).toList()),
            SizedBox(height: 10),
            SizedBox(height: 10),
            Wrap(
              children: availableInterests.map((interests) {
                if (interests["isChecked"] == true) {
                  return Card(
                    elevation: 3,
                    color: Colors.amber,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(interests["name"]),
                    ),
                  );
                }

                return Container();
              }).toList(),
            ),

Here is My modal class, but I am not sure how to capture the interest in here

class User {
  final String id;
  final String name;


  User({ required this.id, required this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['_id'] as String,
      name: json['name'] as String,
    );
  }

  @override
  String toString() {
    return 'User{id: $id, name: $name}';
  }
}

And also in my ApiService code, how do I pass the interests?

  Future<Users> createUser(Users users) async {
    Map data = {
      'name': user.name
//The interest should be part of this data. But I am not sure how to capture it
    };

    final Response response = await post(
      apiUrl,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(data),
    );
    if (response.statusCode == 200) {
      return Users.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to post cases');
    }
  }




mercredi 8 décembre 2021

Editing the look of a checkbox in WooCommerce Wordpress

I added an optional checkbox to my site by adding a bit of code to functions.php. It’s great and all, however I want it to look just like the delivery checkbox. Instead of clicking on the checkbox to reveal the price, I want there to be “Assembly” under the delivery fee, and on the right side I want the default option to be No assembly and the option under to be Assembly – 170€ (for each product). I made a few screenshots AND I Photoshopped exactly what I need.

THIS is what it looks like when it’s not checked (Montaža).

THIS is what it looks like when it’s checked – I just want to disable the first checkbox, so it looks the way it it when it’s checked.

THIS is what I’m looking for.

I hope since you have the checkbox for delivery by default on WooCommerce, that adding the same checkbox, just with different options will be easy to solve.

The code I added to functions.php:

// Display the custom checkbow field in checkout
add_action( 'woocommerce_review_order_before_order_total', 'fee_installment_checkbox_field', 20 );
function fee_installment_checkbox_field(){
    echo '<tr class="packing-select"><th>';

    woocommerce_form_field( 'installment_fee', array(
        'type'          => 'checkbox',
        'class'         => array('installment-fee form-row-wide'),
        'label'         => __('Montaža v 14 dneh'),
        'placeholder'   => __(''),
    ), WC()->session->get('installment_fee') ? '1' : '' );

    echo '</th><td>';
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
    // Only on Checkout
    if( is_checkout() && ! is_wc_endpoint_url() ) :

    if( WC()->session->__isset('installment_fee') )
        WC()->session->__unset('installment_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('form.checkout').on('change', 'input[name=installment_fee]', function(){
            var fee = $(this).prop('checked') === true ? '1' : '';

            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'installment_fee',
                    'installment_fee': fee,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                },
            });
        });
    });
    </script>
    <?php
    endif;
}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_installment_fee', 'get_installment_fee' );
add_action( 'wp_ajax_nopriv_installment_fee', 'get_installment_fee' );
function get_installment_fee() {
    if ( isset($_POST['installment_fee']) ) {
        WC()->session->set('installment_fee', ($_POST['installment_fee'] ? true : false) );
    }
    die();
}

// Add a custom calculated fee conditionally
add_action( 'woocommerce_cart_calculate_fees', 'set_installment_fee' );
function set_installment_fee( $cart ){
    if ( is_admin() && ! defined('DOING_AJAX') || ! is_checkout() )
        return;

    if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
        return;

    if ( 1 == WC()->session->get('installment_fee') ) {
        $items_count = WC()->cart->get_cart_contents_count();
        $fee_label   = sprintf( __( "Montaža" ), '&times;', $items_count );
        $fee_amount  = 170 * $items_count;
        WC()->cart->add_fee( $fee_label, $fee_amount );
    }
}

add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_installment_checkbox', 10, 4 );
function remove_optional_txt_from_installment_checkbox( $field, $key, $args, $value ) {
    // Only on checkout page for Order notes field
    if( 'installment_fee' === $key && is_checkout() ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

Please help me out :)




I need help adding a Discount checkbox/checkboxes to my Javascript Price Calculator [closed]

i have found this code for a js calculator here on this site and it is great! Javascript Price Calculator Issues (Checkboxes) Now want to add a checkbox/radio button to calculate a discount (e.g. if checked 25% off)

And if thats possible: i would love to have a pulldown menu for one category (all with the same price...lets say 5) so if i select 3 its 15 and so on.

Any help would be greatly appreciated!

//ARRAY
var eventEquipmentArray = new Array();
eventEquipmentArray["15 Inch Speakers"] = 5;
eventEquipmentArray["18 Inch Subwoofer"] = 10;
eventEquipmentArray["LED Par Cans"] = 5;
eventEquipmentArray["Smoke Machine"] = 5;
eventEquipmentArray["Moving Head"] = 10;
eventEquipmentArray["4 Gun Laser System"] = 5;
eventEquipmentArray["Red Gun Laser System"] = 5;
eventEquipmentArray["1500W Strobes"] = 10;
eventEquipmentArray["Mirror LED Lighting"] = 5;

//CHECKBOX - EVENT EQUIPMENT
function getEventEquipment() {
  var EventEquipment = 0;
  var theForm = document.forms["quote"];
  var selectedEquipment = theForm.elements["selectedEquipment"];

  for (var i = 0; i < selectedEquipment.length; i++) {
    if(selectedEquipment[i].checked){
        EventEquipment += eventEquipmentArray[selectedEquipment[i].value] || 0;
    }
  }

  return EventEquipment;
}

//DIV - TOTAL PRICE TEST
function getTotals() {
  //var totalPrice = getEventDuration() + getEventSuburb() + getEventEquipment();
  var totalPrice = getEventEquipment();
  var totalPriceDIV = document.getElementById("totalPrice");
  totalPriceDIV.innerText = "Total: $ " + totalPrice;
}
<form id="quote">
  <p>
    <label>
      <input type="checkbox" name="selectedEquipment" value="15 Inch Speakers" id="selectedEquipment_0" onChange="getTotals()" /> 15" Speakers</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="18 Inch Subwoofer" id="selectedEquipment_1" onChange="getTotals()" /> 18" Subwoofer</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="LED Par Cans" id="selectedEquipment_2" onChange="getTotals()" /> LED Par Cans</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="Smoke Machine" id="selectedEquipment_3" onChange="getTotals()" /> Smoke Machine</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="250W Moving Head" id="selectedEquipment_4" onChange="getTotals()" /> 250W Moving Head</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="Mirror LED Lighting" id="selectedEquipment_5" onChange="getTotals()" /> Mirror LED Lights</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="4 Gun Laser System" id="selectedEquipment_6" onChange="getTotals()" /> 4 Gun Laser Light</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="Red Gun Laser System" id="selectedEquipment_7" onChange="getTotals()" /> Red Laser Star Light</label>
    <br />
    <label>
      <input type="checkbox" name="selectedEquipment" value="1500W Strobes" id="selectedEquipment_8" onChange="getTotals()" /> 1500W Strobes</label>
    <br />
  </p>

  <div id="totalPrice" style="color: red; text-align: center; font-size: 18px;"></div>

</form>



checkboxes and radio buttons not checking

I'm not able to get my radio buttons or checkboxes to either check or uncheck. My application is wrapped inside of an 'app container'. The containers used for the main layout use flexbox for alignment. When I move the html outside of the application container, the checkboxes and radio buttons work perfectly but they are unresponsive inside of the app container. Any ideas of what could be causing this issue? It's a pretty big program so I will just upload the HTML for now. Thanks for any and all help.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="src/sass/main.scss" />
        <!-- leaflet css -->
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin=""/>
        <!-- Make sure you put this AFTER Leaflet's CSS -->
        <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
       
        <script defer src="src/js/controller.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDKARpdUTPxgRIUyJpEoUfTt9goQmnkSvk&callback=initMap"></script>
        </script>
        <script src="https://unpkg.com/@googlemaps/markerwithlabel/dist/index.min.js"></script>

        <title>Find Your Dream Home!</title>
    </head>
    <body>
        <div class="app__container">
            <div class="nav__container">
                <div class="nav__top">
                    <ul class="u-margin-left-xs nav__top--actions nav__top--actions--left">
                        <li class="u-margin-right-s nav__top--items nav__top--items--left">
                            <a href="" class="nav__top--links nav__top--links--left">Buy</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--left">
                            <a href="" class="nav__top--links nav__top--links--left">Rent</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--left">
                            <a href="" class="nav__top--links nav__top--links--left">Sale</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--left">
                            <a href="" class="nav__top--links nav__top--links--left">Home Loans</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--left">
                            <a href="" class="nav__top--links nav__top--links--left">Agent Finder</a>
                        </li>
                    </ul>
                    <div class="logo__container">
                        <div class="logo__container--home">
                            <img src="./src/img/logo__house.svg" alt="logo-homes" class="logo logo__homes">
                        </div>
                        <div class="logo__container--txt">
                            <img src="./src/img/logo__txt.svg" alt="logo-txt" class="logo logo__txt">
                        </div>
                    </div>
                    <ul class="u-margin-right-xs nav__top--actions nav__top--actions--right">
                        <li class="u-margin-right-s nav__top--items nav__top--items--right">
                            <a href="" class="nav__top--links nav__top--links--right">Manage Rentals</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--right">
                            <a href="" class="nav__top--links nav__top--links--right">Advertise</a>
                        </li>
                        <li class="u-margin-right-s nav__top--items nav__top--items--right">
                            <a href="" class="nav__top--links nav__top--links--right">Help</a>
                        </li>
                        <li class="nav__top--items nav__top--items--right">
                            <a href="" class="nav__top--links nav__top--links--right">Sign In</a>
                        </li>
                    </ul>
                </div>
                <div class="nav__bottom">
                  
                    <div class="city__input--container u-margin-left-xs">
                        <form id = "city__input--form">
                            <input type="text" class = "city__input" id = 'city__input' name = 'city__input' placeholder =" Enter a U.S. city" autocomplete="off">
                            <img src="./src/img/pin-home.svg" alt="home-pin" class = "home-pin">
                        </form>
                        <div class="auto-complete__container">
                            <div class="black-border">
                                <div class="black-border--left hide"></div>
                                <div class="black-border--triangle hide"></div>
                                <div class="black-border--right hide"></div>
                            </div>
                            <ul class="auto-complete__list">
                          
                            </ul>
                        </div>    
                    </div>
                 
                    <div class="nav__btn--container">
                        <div class="btn__marker btn__active btn__for-sale--container u-margin-right-xxs " data-marker = 0>
                            <button class="btn btn__for-sale btn__marker--active">
                                <img src="./src/img/red-active-circle.svg" alt="red active circle" class="active-circle">
                                For Sale
                            </button>
                        </div>
                        <!-- <div class="for-sale__container">
                            <div class="for-sale__container--top">
                                <div class="for-sale">
                                    <label class = 'form-control form-control--for-sale' for = 'search-options--radio'>
                                        <input value="homes-for-sale" type="radio" name = 'homes-for-sale-name' id ='search-options--radio' class = 'search-options--radio--active' value = 'for-sale'>
                                                     
                                        <div class="red-circle"></div>
                                        <p class="p5">For Sale</p>
                                    </label>       
                                </div>
            
                                <div class="for-rent">
                                    <label class = 'form-control' for = 'search-options--radio'>
                                        <input value="homes-for-sale" type="radio" name = 'homes-for-sale-name' id ='search-options--radio' value = 'for-sale' class = 'search-options--radio'>
                                                
                                        <div class="purple-circle"></div> 
                                        <p class="p5">For Rent</p>
                                    </label>
                                </div>
                                <div class="sold">
                                    <label class = 'form-control' for = 'search-options--radio'>
                                        <input value="homes-for-sale" type="radio" name = 'homes-for-sale-name' id ='search-options--radio' value = 'for-sale' class = 'search-options--radio'>
                                                
                                        <div class="yellow-circle"></div>
                                        <p class="p5">Sold</p>
                                    </label>
                                </div>
                            </div>
                            <div class="for-sale__container--bottom">
                                <div class="done__container">
                                    <button class="btn__done">
                                        Done
                                    </button>
                                </div>
                            </div>
                        </div> -->
                        <div class="btn__marker btn__price--container u-margin-right-xxs" data-marker = 1>
                            <button class="btn btn__price">
                                Price
                            </button>
                            <!-- <div class="price__container">
                                <div class="price__container--top">
                                    <p class="p3 price-range--header">Price Range</p>
                                    <div class="price-range--inputs">
                                        <label for="price-range--low" class="price-range--label price-range--label--low">
                                            <input type="text" id = 'price-range--low' class = 'price-range--low dropdown__wide price-range--input' value = '100,000'>
                                        </label>
                                        <p class="dash">-</p>
                                        <label for="price-range--high" class="price-range--label price-range--label--high">
                                            <input type="text" id = 'price-range--high' class = 'price-range--high dropdown__wide price-range--input' value = '500,000'>
                                        </label>
                                    </div>
                                </div>
                                <ul class="prices p3">
                                    <li class="price"><span>$</span>0<span>+</span></li>
                                    <li class="price"><span>$</span>100,000<span>+</span></li>
                                    <li class="price"><span>$</span>200,000<span>+</span></li>
                                    <li class="price"><span>$</span>300,000<span>+</span></li>
                                    <li class="price"><span>$</span>400,000<span>+</span></li>
                                    <li class="price"><span>$</span>500,000<span>+</span></li>
                                    <li class="price"><span>$</span>600,000<span>+</span></li>
                                </ul>   
                                <div class="price__container--bottom">
                                    <div class="done__container">
                                        <button class="btn__done">
                                            Done
                                        </button>
                                    </div>
                                </div>
                            </div> -->
                        </div>
                        <div class="btn__marker btn__bb--container u-margin-right-xxs" data-marker = 2>
                            <button class="btn btn__bb">
                                Beds & Bath
                            </button>
                            <!-- <div class="bed-bath__container">
                               <p class="p3 bed-text">Bedrooms</p>
                                <ul class="bed-amount p3">
                                    <li class="bed-number bed-number--any">Any<span>+</span></li>
                                    <li class="bed-number">1<span>+</span></li>
                                    <li class="bed-number">2<span>+</span></li>
                                    <li class="bed-number">3<span>+</span></li>
                                    <li class="bed-number">4<span>+</span></li>
                                    <li class="bed-number">5<span>+</span></li>
                                </ul>
                                <p class="p3 bath-text">Bathrooms</p>
                                <ul class="bath-amount p3">
                                    <li class="bath-number bath-number--any">Any<span>+</span></li>
                                    <li class="bath-number">1<span>+</span></li>
                                    <li class="bath-number">1.5<span>+</span></li>
                                    <li class="bath-number">2<span>+</span></li>
                                    <li class="bath-number">3<span>+</span></li>
                                    <li class="bath-number">4<span>+</span></li>
                                </ul>     
                                <div class="bed-bath__container--bottom">
                                    <div class="done__container">
                                        <button class="btn__done">
                                            Done
                                        </button>
                                    </div>
                                </div>
                            </div> -->
                        </div>
                        <div class="btn__marker btn__home-type--container u-margin-right-xxs" data-marker = 3>
                            <button class="btn btn__home-type">
                                Home Type
                            </button>
                            <!-- <div class="home-type__container">
                                <p class="p3 home-type--text">Home Type</p>
                                <div class="home-type--select-all--container">
                                    <p class="checkmark">&#10003;</p>
                                    <p class="select-all--text">Deselect all</p>
                                </div>
                                <label for="home-type-house" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-house' >
                                    <p class="p3 home-type-list-text">Houses</p>
                                </label>
                                <label for="home-type-town-homes" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-town-homes' checked>
                                    <p class="p3 home-type-list-text">TownHomes</p>
                                </label>
                                <label for="home-type-multi-family" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-multi-family' >
                                    <p class="p3 home-type-list-text">Multi-family</p>
                                </label>
                                <label for="home-type-condos" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-condos' >
                                    <p class="p3 home-type-list-text">Condos/Co-ops</p>
                                </label>
                                <label for="home-type-lots" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-lots' >
                                    <p class="p3 home-type-list-text">Lots/Land</p>
                                </label>
                                <label for="home-type-apartments" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-apartments' checked>
                                    <p class="p3 home-type-list-text">Apartments</p>
                                </label>
                                <label for="home-type-manufactured" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-manufactured' checked>
                                    <p class="p3 home-type-list-text">Manufactured</p>
                                </label>      
                                 <div class="home-type__container--bottom">
                                     <div class="done__container">
                                         <button class="btn__done">
                                             Done
                                         </button>
                                     </div>
                                 </div>
                             </div> -->
                        </div>
                        <div class="btn__marker btn__More--container u-margin-right-xxs" data-marker = 4>
                            <button class="btn btn__More">
                                More
                            </button>
                        </div>
                        <div class="btn__marker btn__save-search--container" data-marker = 5>
                            <button class="btn btn__save-search">
                                Save Search
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="app__body">
                <div class="map__container">
                    <div class="test" id = "map"></div>
                </div>
                <div class="results__section--container">
                    <div class="results__section--title--container">
                       
                    </div>
                    <div class="results__section--options--container">  
                        <button class="btn btn__results btn__agent btn__results--active">
                            <span class="results__totals"></span>Agent Listings
                          </button>
                          <button class="btn btn__results btn__other btn__savedHomes">
                            <span>0 </span> &nbsp;Saved Homes
                          </button>
                          <div class="sort__container">
                              
                            <p class="sort__text">Sort by:</p>
                            <div class="dropdown" data-dropdown-open = '0'><p>Homes for You</p>
                            <span class="arrow-down__container">
                            <img src="./src/img/arrow_down.svg" alt="arrow_down" class = "arrow-down">
                            </span>
                            <div class="border-glow"></div>
                            </div>
                            <div class = "sort__options">
                              <ul class = "sort__list">
                                <li class = "sort__item sort__high-to-low" data-sort = "High to Low" data-list-position = '1'>Price (High to Low)</li>
                                <li class = "sort__item sort__price" data-sort = "Low to High" data-list-position = '2'>Price (Low to High)</li>
                                <li class = "sort__item sort__newest" data-sort = "Home Type" data-list-position = '3'>Home Type</li>
                                <li class = "sort__item sort__bedrooms" data-sort = "Bedrooms" data-list-position = '4'>Bedrooms</li>
                                <li class = "sort__item sort__bathrooms" data-sort = "Bathrooms" data-list-position = '5'>Bathrooms</li>
                                <li class = "sort__item sort__square-feet" data-sort = "Square Feet" data-list-position = '6'>Square Feet</li>
                              </ul>
                            </div>
                          </div>        
                    </div>
                    <div class="home__list">
                        <div class="pagination__container"></div>
                    </div>           
                </div>
            </div>
    
        </div>
    </body>
</html>

here is some of the code with some of my checkboxes and radio buttons

<div class="home-type__container">
                                <p class="p3 home-type--text">Home Type</p>
                                <div class="home-type--select-all--container">
                                    <p class="checkmark">&#10003;</p>
                                    <p class="select-all--text">Deselect all</p>
                                </div>
                                <label for="home-type-house" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-house' >
                                    <p class="p3 home-type-list-text">Houses</p>
                                </label>
                                <label for="home-type-town-homes" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-town-homes' checked>
                                    <p class="p3 home-type-list-text">TownHomes</p>
                                </label>
                                <label for="home-type-multi-family" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-multi-family' >
                                    <p class="p3 home-type-list-text">Multi-family</p>
                                </label>
                                <label for="home-type-condos" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-condos' >
                                    <p class="p3 home-type-list-text">Condos/Co-ops</p>
                                </label>
                                <label for="home-type-lots" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-lots' >
                                    <p class="p3 home-type-list-text">Lots/Land</p>
                                </label>
                                <label for="home-type-apartments" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-apartments' checked>
                                    <p class="p3 home-type-list-text">Apartments</p>
                                </label>
                                <label for="home-type-manufactured" class = 'home-type--label'>
                                    <input type="checkbox" id = 'home-type' class="home-type--checkbox" name = 'home-type-manufactured' checked>
                                    <p class="p3 home-type-list-text">Manufactured</p>
                                </label>      
                                 <div class="home-type__container--bottom">
                                     <div class="done__container">
                                         <button class="btn__done">
                                             Done
                                         </button>
                                     </div>
                                 </div>
                             </div>



lundi 6 décembre 2021

Change border color of material ui checkbox

Here is my checkbox when checked:

enter image description here

Here is my checkbox when not checked:

enter image description here

All of the posts relating to styling the checkbox pertain to the fill color, the check color, etc. I must be missing something obvious here - just trying to make the border dark!

My code:

<Grid item xs={12}>
  <FormControlLabel control={<Checkbox onChange={(event) => {
    console.log(event.target.checked)
    setValue('isParty', false)
  }} />} label="Party" />
</Grid>



Checkbox toggle doesn't work in mobile nav-menu (wp_nav_menu)

I'm trying to make the hamburger icon clickable, so that it opens the .top-bar nav menu. But it doesn't work, am I not targeting it correctly? It does hide the .top-bar and display hamburger icon when I resize the window, but on click, nothing happens. I've tried playing with multiple classes in order to target the top-bar, all without any success. Does the problem lay in how I display the top bar?

Please find the code below.

HTML (header)

<header class="header" id="myHeader">

        <div class="container">
            <?php
            $custom_logo_id = get_theme_mod('custom_logo');
            $logo = wp_get_attachment_image_src($custom_logo_id, 'full');

            if (has_custom_logo()) {
                echo '<a href="http://mywebpage.test/" class="site-link pull-left"> <img class="site-logo" src="' . esc_url($logo[0]) . '" alt="' . get_bloginfo('name') . '"> </a>';
            } else {
                echo '<h1 class="site-logo">' . get_bloginfo('name') . '</h1>';
            }
            ?>

        <label for="toggle">&#9776</label>
        <input type="checkbox" class="toggle">
            <?php
            wp_nav_menu(
                array(
                    'theme_location' => 'top-menu',
                    'menu_class' => 'top-bar'
                )
            );
            ?>
        </div>
    </header>

CSS

header .container {
    height: 100%;
    z-index: 10;
    display: flex;
    align-items: center;
    position: relative;
}

header .container .top-bar {
    list-style-type: none;
    display: flex;
}

header .container .site-link,
.site-logo {
    margin-right: auto;
}

header .top-bar li a {
    padding: 0 2rem;
    color: var(--off_white);
    font-size: 1.3rem;
    text-decoration: none;
    z-index: 1000;
}

header .top-bar li.current-menu-item a {
    background: var(--secondary);
    padding: 2.5rem 2rem 2.5rem 2rem;
}

header label {
    cursor: pointer;
    font-size: 2rem;
    color: var(--off_white);
    display: none;
}

.toggle {
    display: none;
}

@media (max-width: 992px) {
    header label {
        display: block;
    }
    .top-bar li {
        display: none;
    }
    .toggle:checked~li {
        display: block;
    }
}



Cypress: How to verify generated checkBox is checked and has attribute aria-checked="true"

I want to verify that a checkbox is checked. But it isn't a usually checkbox from type="checkbox", so it HASN'T the property "checked". Instead of this you can find in the HTML-Doom aria-checked="true". How can I read out this value?

HTML-Snipet:


<mat-checkbox class="mat-checkbox mat-primary mat-checkbox-checked" aria-label="checkBoxCapacityBaseEditDayofWeek: 1" id="DAY1">
  <label class="mat-checkbox-layout" for="DAY1-input">
  <span class="mat-checkbox-inner-container">
   <input type="checkbox" class="mat-checkbox-input cdk-visually-hidden" id="DAY1-input" tabindex="0" value="1" aria-checked="true">

What I've tried for so long:

Cypress-Code (nothing works):

// cy.get('#DAY2')
    // .should('have.value', 'aria-checked="true"')
    
    cy.get('#DAY1')
    .should('have.attr', 'aria-checked', 'false')

    cy.get('#DAY2')
    .should('have.attr', 'aria-checked', 'true')

    // .invoke('val', 'aria-checked')
    // .should('eq', true)
    // .should('have.prop', 'aria-checked', true)
    // .should('have.attr', 'aria-checked', 'true')

How can I get to the value true?

EDIT: I found the solution: Cypress-Code:

cy.get('#DAY1-input').should('have.attr', 'aria-checked', 'true')



On-Screen Alert checkbox

I have a PHP page with some checkboxes.

I need to do that: When I click on a button, an alert comes out to show me all the IDs of the selected boxes. How can I do this?

Visual example:

| BUTTON| - View the selected tests in an alert.

□ ALL | PRODUCT | SAMPLE ID

□ - - - - Test 1 - - - - SD7168

□ - - - - Test 2 - - - - BH1560

□ - - - - Test 3 - - - - CP4327

So I want if, for example, I selected test 1, an alert comes to me informing me the ID (SD7168) of the test I selected.

// Button 
<h4>
   <a href="" class="btn btn-info" onclick="return confirm('View selected tests')">
     <br><small>TEST ID</small></a>
</h4>

// Checkbox select all
<tr>
    <th><input type="checkbox" name="select-all" id="select-all"/>
         <label for="select-all" class='smallLabel'></label>
    </th>
</tr>

// Checkbox select single

<tr>
    <td>
       <input type="checkbox" name="<?='checkbox-'.$num?>" id="<?='checkbox-'.$num?>"/>
          <label for="<?='checkbox-'.$num?>" class='smallLabel'></label>
    </td>

// ID parameter
                    
    <td>
       <?=$test->sampleID?> Select: <input id="<?='checkbox-'.$num?>" type="checkbox"/> <br>
    </td>

// JS Checkboxes

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

// Listen for click on toggle checkbox
    $('#select-all').click(function(event) {   
        if(this.checked) {
            // Iterate each checkbox
            $(':checkbox').each(function() {
                this.checked = true;                        
            });
        } else {
            $(':checkbox').each(function() {
                this.checked = false;                       
            });
        }
    }); 


// JS che I created to manage the alert

$('<?='checkbox-'.$num?>').click(function() {
    alert("Checkbox state (method 1) = " + $('<?='checkbox-'.$num?>').prop('checked'));
    alert("Checkbox state (method 2) = " + $('<?='checkbox-'.$num?>').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>




Requiring at least 2 check boxes be clicked using JavaScript

I am trying to build a form that requires at least two check boxes to be selected. I have tried everything that I could find without any sort of success.

function cb_require() {
  let chckbx = document.forms['form_name']['contact'].value;

  for (chckbx.length === 1) {
    if (i = 0; i < chckbx.length; i++) {
      alert('check 2');
      return false;
    }
  }
}
<form method="post" name="form_name" id="form_name" action="mailto:bb@yahoo.com" enctype="text/plain" onsubmit="return cb_require()">
  <label for="cont">Preferred Contact Method:</label>
  <input type="checkbox" id="Phone" name="contact" value="Phone">
  <label for="Phone">Phone</label>
  <input type="checkbox" id="E-mail" name="contact" value="E-email">
  <label for="E-mail">E-mail</label><br>
  <input type="checkbox" id="Mail" name="contact" value="Mail">
  <label for="Mail">Mail</label>
  <input type="checkbox" id="LinkedIn" name="contact" value="LinkedIn">
  <label for="LinkedIn">LinkedIn</label><br><br>
</form>

Thanks in advance for any help or advice!




Is there a way to style checkbox appearance in p5js to become a toggle switch?

I'm trying to change the appearance of a checkbox in p5 canvas using javascript to have the same appearance as a toggle switch like this

I've tried experimenting in the css file in this sketch but it doesn't seem to be working

Any help would be much appreciated. Thanks




dimanche 5 décembre 2021

Displaying mysql table data with an added column for a checkbox

So I have this function that displays all the data in my mysql table.

function maindbdisplay(){
    echo "<table style='border: solid 1px black;'>";
    echo "<tr><th>DBid</th><th>Firstname</th><th>Lastname</th><th>email</th><th>NFCid</th></tr>";
    class TableRows extends RecursiveIteratorIterator {
        function __construct($it) {
          parent::__construct($it, self::LEAVES_ONLY);
        }
      
        function current() {
          return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
        }
      
        function beginChildren() {
          echo "<tr>";
        }
      
        function endChildren() {
          echo "</tr>" . "\n";
        }
    }

    global $conn;
    $stmt = $conn->prepare("SELECT * from registered;");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
       //$v is table data with headers, $k is table headers only  
       //this displays all headers first, then each loop displays values under the next header   
       echo $v;
    }

    global $sql;
    $sql="select * from registered;"; $conn->exec($sql);
}

Now, I would like to have an extra column at the beginning of the table where there is a checkbox for each data entry, so I can select entries and for example delete them. I did not find any plausible answers while searching for a solution.




Access an HTML input of type checkbox from event rowDataBound

In a asp:gridview i have one input column of type checkbox. im trying to access it from code-behind(vb) because i need to determine visibility = true\false.

The column define like this:

<asp:TemplateField HeaderText=" " ItemStyle-BorderWidth="1" HeaderStyle-Width="3%" ItemStyle-Width="3%" HeaderStyle-CssClass="box_border table_title" ItemStyle-CssClass="box_border">
<ItemTemplate>               
<input type="checkbox" id="chkHaktzaa" onclick="chkHaktzaa_click('<%# Container.DataItemIndex %>')" />
</ItemTemplate>
</asp:TemplateField>

I try to use this method in event rowDataBound:

CType(e.Row.FindControl("chkHaktzaa"), HtmlInputCheckBox).Visible = False

but i get thos error messege:

System.NullReferenceException: Object reference not set to an instance of an object.

Thank you for the help.




samedi 4 décembre 2021

ExtJs - Checkbox selection model, disable checkbox per row and lose clearing all the selections

I have a grid with a checkbox selection model.

There are some rows that not be selectable, based on a value in a field. It's work.

My problem is that clearing all the selections by clicking the checkbox in the column header doesn't work. On this link I see that costa was faced the same problem as me: ExtJs - Checkbox selection model, disable checkbox per row.

This listener is worked, but it's break checkbox clearing.

Code:

xtype: 'grid',
border: false,

selModel: {
    selType: 'checkboxmodel',
    listeners: {
        beforeselect: function(grid, record) {
            if (!record.get('supplier')) {
                return false;
            }
        }
    }

colums:[
....
],
....

Does anyone have an idea how to do this?

Thank you.




Is it possible assign the checked state to the value of the current checkbox in razor form without onclick method?

I have an ASP.Net Core MVC Web Application project. I want to send the checkbox's checked state as the value to the model's related parameter on form submit. I have seen so many examples that using jquery to get/set the value of the checkbox via onchange methods.

What I wonder is that is it possible to assign the current checkbox's checked state to the value in a similar way to the code below.(it doesn't work)

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActiveTournament" value="(this.checked)" 

One of the simplest working examples I found is the following but it returns false if the checkbox is checked by default and its state is not changed.

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" onchange="if(this.checked) this.value='true'; else this.value='false';" >

I know that there are many ways to achieve what I want but I want the cleanest solution.

Thanks in advance!




Could you show me how to convert checkboxes to dropdown fields in WordPress?

Is it possible to convert checkboxes to dropdown options? Here's my code. Is it also possible to include checkboxes within the dropdown for multi-selection?

<ul class="kw-features-list">

    <?php foreach( $job_tags as $feature ): ?>
        <li>
        <label for="kw-feature-<?php echo esc_attr( $feature->slug ) ?>" class="checkbox-inline">
            <?php $checked = ( in_array( $feature->slug, $atts['selected_feature'] ) ) ? ' checked="checked"' : ''; ?>
            <input class="search_feature" name="search_feature[]" <?php echo esc_attr($checked)  ?>        
             id="kw-feature-<?php echo esc_attr( $feature->slug ) ?>" type="checkbox" value="<?php echo esc_attr($feature->slug) ?>">
            <?php echo esc_attr($feature->name) ?>
        </label>
        </li>
    <?php endforeach; ?>

    </ul><!--/ .kw-features-list-->



Update the Page values in data table without reloading the entire page?

I want to update the specific page data in the data table.

For example,

I have a table with 100 data. So I have used the pagination. And now I want to update the 3rd-page data in the table without reloading the entire page and want to be on the same page( 3rd)

Thanks in Advance




vendredi 3 décembre 2021

cpp ImGui::CheckBox registers clicks but does nothing

I have a few Checkboxes assigned to variables. But when i click them nothing happens. It registers when they're clicked because it goes slightly bright but no tick appears. The bool that appears in the loop is static so that should not effect this. Code

static bool aimColor = false;
ImGui::Checkbox(skCrypt("Show Aim Color Picker"), &aimColor);

The aimColor Bool does not change at all




Add gap between outer and inner border of checkbox

I'm styling a bunch of form elements and need to customize the style of the checkbox. It needs to look like this when checked:

enter image description here

The closest I can get to that is as you see at this fiddle here: https://jsfiddle.net/ufhav6Lw/2/

enter image description here

I've tried using background-size:50%; at line 24 of the CSS in the fiddle.

How do I create the gap between the inner and outer square of the checkbox?




Is there a way to preserve html checkbox state after reload in Django?

Sample code is below. I would like to keep the checkbox checked after page reload once submit button has been pressed

<td><input type="checkbox" value="" name="selectedcheckbox"/></td>



How to create multiple selected options of a option

I am trying to create a question in which there are two options but one option has multiple sub options. I have tried to search a lot but I have not found a way to achieve this using radio and checkbox button. Does anybody has any reference or can guide me that how can I achieve this?

Do you have a product ready to be marketed immediately in the US?
a. Ready for immediate export
b. I am missing some items (check all that apply)
- Packing
- Label
- FDA
- Price and conditions of sale
- Registered Trademark
- SKU
- Entry rules in the destination country
- Other



Get Values of dynamically added checkboxes in React

I am just fighting with the values of dynamically added checkboxes in React with MUI.

I have a list of values where those checkboxes are created and now I would need the status checked or not of those ones.

Code of generation of the checkbox:

const country = ['Österreich', 'Deutschland', 'Schweiz', 'Nordeuropa', 'Westeuropa',
        'Mitteleuropa', 'Osteuropa', 'Südosteuropa', 'Südeuropa', 'Gesamt-Europa'];

<FormControl component="fieldset" sx=>
     <RadioGroup
           aria-label={"decisionMakerCountry"+props.id}
           name={"decisionMakerCountry"+props.id}
           defaultValue={props.formData !== null && props.formData !== undefined ? props.formData["decisionMakerCountry"+props.id] : ''}
       >
         {
             country.map((field, index) => (
                     <FormControlLabel value={field} control={<Checkbox/>} label={field}
                         key={index}/>
             ))
         }
      </RadioGroup>
</FormControl>

How I get all other values of the form:

const handleNext = async (event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        handleFormData(formData);
}

For all other fields e.g. textfields, Radiobuttons, ... I receive the data correctly, just for the checkbox it is not working.

Thank you for all your answers!




put information from a javascript array in an html checkbox

I'm trying to create a test to see what football shoe somebody needs. I have a javascript array and i want to put it in a loop so it creates an html checkbox for each question in the array.

My array:

    var FootballShoeTest = [
        [
            'Whats your size?',
            ['41', 'url1'],
            ['42', 'url2'],
            ['43', 'url3']
        ],
        [
            'What color would you like?',
            ['Red', 'url1'],
            ['Blue', 'url2'],
            ['Yellow', 'url3'],
            ['Green', 'url4']
        ],
        [
            'What brand would you like?',
            ['Adidas', 'url1'],
            ['Nike', 'url2'],
            ['Puma', 'url3']
        ]
    ];

    var SizeUrl = '';
    var ColorUrl = '';
    var BrandUrl = '';

I need to create multiple input quiz like questions looking like this:

What's your size?
[ ] 41
[ ] 42
[ ] 43

What color would you like?
[ ] Red
[ ] Blue
[ ] Yellow
[ ] Green

What brand would you like?
[ ] Adidas
[ ] Nike 
[ ] Puma

And when I click on an awnser for my size i want the variable SizeUrl to change to the url that belongs to the awnser (so when I click on 42 it would change to url2) and the same counts for the other questions. Does anybody know a way to do this?




jeudi 2 décembre 2021

checkboxes wont align to the right

Ive got a custom CheckBox widget where it returns a label and a checkbox field,

@override
Widget build(BuildContext context) {
 return Padding(
  padding: const EdgeInsets.all(16.0),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Text(widget.label, style: Theme.of(context).textTheme.headline4),
      Checkbox(
        activeColor: LightSeaGreen,
        checkColor: White,
        value: _checkbox,
        onChanged: (value) {
          setState(() {
            _checkbox = !_checkbox;
          });
          widget.onChanged(value);
        },
      ),
    ],
  ),
);

}

So right now,It looks like this,

enter image description here

what I want is for the checkboxes to align to the right like this

enter image description here

Ive tried the Align fuction,Spacer,MainAxisAlignment.spaceBetween but nothing works

please help me




Storing Drupal Form Checkboxes in a Database

Working on a form that will have 25 checkboxes in a checkboxes set. I need to store the checked keys in a database, and be able to restore the Edit form to it's checked state. I do have a solution, but it just seems odd. This is my first effort at a form and am looking for a best practice on how to solve this problem.

A prototype of my checkboxes set:


$form['medical'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Medical Conditions you currently or have previously suffered.'),
      '#options' => [
        'Asthma' => $this->t('Asthma'),
        'Anxiety' => $this->t('Anxiety'),
        'Diabetes' => $this->t('Diabetes'),
        'Schizophrenia' => $this->t('Schizophrenia'),
        'Low Blood Sugar' => $this->t('Low Blood Sugar'),
        'High Blood Pressure' => $this->t('High Blood Pressure'),
        'Stroke' => $this->t('Stroke'),
        'HIV' => $this->t('HIV'),
        'IBS' => $this->t('IBS'),
      ],
      '#default_value' => $savedArray,

I get the checked keys using

$medical = $form_state->getValue('medical');
$chked = implode(',', $medical);

This gives me a comma separated string, something like something like 'Asthma,Diabetes,Low Blood Sugar,Stroke,IBS,0,0,0,0'.

I get the portion before the first ',0', the first unchecked checkbox and save that to the database.

$chked = substr($chked, 0, strpos($val, ',0'));

So the database is storing a comma separated list of Key values that represent the checked boxes.

To restore the state of the form, I get that string value from the database and explode it into an array, and use that array as the #default_value of the checkbox set.

 $savedArray = explode(',', $chked)
 #default_value => $savedArray

This all works, but it just seems pretty weird. I am new to Drupal and php. Is this an reasonable solution? Is there some built in functionality that manages this? This feels a lot like Jr programmer hackery to me!




Click in checkbox gives me undefined

I am new in php and I have problem whith checkbox. Infact when I check one of the checkboxs in table it should gives me my data but unfortunately it gives me undefined.

here is my code befor click in checkbox enter image description here

and after click for exemple in the checkbox in the first line enter image description here

and this is my code :

$(document).on('click', '.check_box', function(){
    var html = '';
    if(this.checked)
    {
        html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-Projet="'+$(this).data('Libelle_Projet')+'" data-Num-Produit="'+$(this).data('Num_Produit')+'" data-Libelle-Produit="'+$(this).data('Libelle_Produit')+'" data-Titre-Foncier-Produit="'+$(this).data('Titre_Foncier_Produit')+'" data-Superficie-Produit="'+$(this).data('Superficie_Produit')+'" data-Date-Reception-Administratif-Temp="'+$(this).data('Date_Reception_Administratif_Temp')+'" data-Date-Contrat-Temp="'+$(this).data('Date_Contrat_Temp')+'" class="check_box" checked /></td>';
        html += '<td>'+$(this).data("Libelle_Projet")+'</td>';
        html += '<td>'+$(this).data("Num_Produit")+'</td>';
        html += '<td>'+$(this).data("Libelle_Produit")+'</td>';
        html += '<td>'+$(this).data("Titre_Foncier_Produit")+'</td>';
        html += '<td>'+$(this).data("Superficie_Produit")+'</td>';
        html += '<td><input type="date" name="Date_Reception_Administratif_Temp[]" class="form-control" value="'+$(this).data("Date_Reception_Administratif_Temp")+'" /></td>';
        html += '<td><input type="date" name="Date_Contrat_Temp[]" class="form-control" value="'+$(this).data("Date_Contrat_Temp")+'" /><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" /></td>';
    }
    else
    {
        html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-Projet="'+$(this).data('Libelle_Projet')+'" data-Num-Produit="'+$(this).data('Num_Produit')+'" data-Libelle-Produit="'+$(this).data('Libelle_Produit')+'" data-Titre-Foncier-Produit="'+$(this).data('Titre_Foncier_Produit')+'" data-Superficie-Produit="'+$(this).data('Superficie_Produit')+'" data-Date-Reception-Administratif-Temp="'+$(this).data('Date_Reception_Administratif_Temp')+'" data-Date-Contrat-Temp="'+$(this).data('Date_Contrat_Temp')+'" class="check_box" /></td>';
        html += '<td>'+$(this).data('Libelle_Projet')+'</td>';
        html += '<td>'+$(this).data('Num_Produit')+'</td>';
        html += '<td>'+$(this).data('Libelle_Produit')+'</td>';
        html += '<td>'+$(this).data('Titre_Foncier_Produit')+'</td>';
        html += '<td>'+$(this).data('Superficie_Produit')+'</td>';
        html += '<td>'+$(this).data('Date_Reception_Administratif_Temp')+'</td>';    
        html += '<td>'+$(this).data('Date_Contrat_Temp')+'</td>';         
    }
    $(this).closest('tr').html(html);
});

my table code :

<form method="post" id="update_form">
        <div id="divShow" class="table-responsive">
          <table class="table table-bordered table-striped">
            <thead>
              <th width="2%"></th>
              <th width="15%">Projet</th>
              <th width="10%">Numéro Produit</th>
              <th width="15%">Dénomination</th>
              <th width="10%">Titre Foncier</th>
              <th width="5%">Superficie</th>
              <th width="15%">Date Réception Admin</th>
              <th width="15%">Date Contrat</th>
            </thead>
            <tbody></tbody>
          </table>
        </div>
        
        <br />

        <div align="left">
          <input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Valider"  style="display: none;" />
        </div>

        <br />

        <div id="msgSelectProduit" style="display: none;"></div>
        <div id="msgSelectDateContrat" style="display: none;"></div>
      </form>

$.ajax({
        url:"selectTOUT.php",
        method:"POST",
        dataType:"json",
        success:function(data)
        {
            var html = '';
            for(var count = 0; count < data.length; count++)
            {
                html += '<tr>';
                html += '<td><input type="checkbox" id="'+data[count].id+'" data-Projet="'+data[count].Libelle_Projet+'" data-Num-Produit="'+data[count].Num_Produit+'" data-Libelle-Produit="'+data[count].Libelle_Produit+'" data-Titre-Foncier-Produit="'+data[count].Titre_Foncier_Produit+'" data-Superficie-Produit="'+data[count].Superficie_Produit+'" data-Date-Reception-Administratif-Temp="'+data[count].Date_Reception_Administratif_Temp+'" data-Date-Contrat-Temp="'+data[count].Date_Contrat_Temp+'" class="check_box"/></td>';
                html += '<td>'+data[count].Libelle_Projet+'</td>';
                html += '<td>'+data[count].Num_Produit+'</td>';
                html += '<td>'+data[count].Libelle_Produit+'</td>';
                html += '<td>'+data[count].Titre_Foncier_Produit+'</td>';
                html += '<td>'+data[count].Superficie_Produit+'</td>';
                html += '<td>'+data[count].Date_Reception_Administratif_Temp+'</td>';
                html += '<td>'+data[count].Date_Contrat_Temp+'</td></tr>';
            }
            $('tbody').html(html);
        }
    });