mardi 30 juin 2020

How to keep checkbox checked in one fragment when we move to another fragment and come back

I have an checkbox which gives me a dialog box when checked. I need my checkbox to be checked when i click OK in my dialog box and when i go back to another fragment and come back to the fragment where my checkbox is present.

this is my block of code:

else if(SettingKeyConstants.BACK_UP.equals(key)) {
            Boolean value = backup.isChecked();
            Qlog.d(TAG, "onPreferenceChange() Prefvalue:"+value);
            if(value) {
                SettingsAPI.setBooleanValue(SettingKeyConstants.BACK_UP, false);
            }else {
                DialogEventHandler warningDialogEventHandler = new BaseDialogEventHandler() {
                    @Override
                    public void onOkButtonPressed() {
                        super.onOkButtonPressed();
                        backup.setEnabled(true);
                        SettingsAPI.setBooleanValue(SettingKeyConstants.BACK_UP, true);
                        //backup.setChecked(true);
                        //TODO................
                    }
                    @Override
                    public void onCancelButtonPressed() {
                        super.onCancelButtonPressed();
                        backup.setEnabled(true);
                        backup.setChecked(false);
                    }
                };
                T3DialogManager.showWarningDialog(getString(R.string.back_up_title), getString(R.string.back_up_message), warningDialogEventHandler);
            }
            return true;
        }



Can Excel4node module create checkbox?

I use javascript and node to create an excel file

I want to set checkbox like this: enter image description here

Somebody suggest module for create checkbox in excel please




CheckboxTreeview not showing checkboxes when using SQLite query populate the rows

I'm trying to use the CheckboxTreeview from ttkwidgets to put checkboxes in front of each line of a treeview I populate with an SQLite query. This is my code:

from ttkwidgets import CheckboxTreeview
import tkinter as tk
import sqlite3
root = tk.Tk()
tree = CheckboxTreeview(root)
connection = sqlite3.connect('lambtracker_db.sqlite')
cursor = connection.cursor()
cmd = "select id_deathreasonid, death_reason from death_reason_table"
cursor.execute(cmd)
rows = cursor.fetchall()
for row in rows:
    print(row)
    tree.insert('', 'end', values=row)
tree.pack()
root.mainloop()

It puts up a blank tree with checkboxes. empty checkbox treeview I can verify that the command is working properly because I do get this printed out in the console

(1, 'Died Unknown')
(2, 'Died Old Age')
(3, 'Died Predator')
(4, 'Died Illness')
(5, 'Died Injury')
(6, 'Died Stillborn')
(7, 'Died Birth Defect')
(8, 'Died Meat')
(9, 'Died Euthanized')
(10, 'Died Dystocia')
(11, 'Died Other')
(12, 'Died Culled')

But a standard Treeview works

import tkinter as tk
from tkinter import ttk
import sqlite3
root = tk.Tk()
tree = ttk.Treeview(root, column=("column1", "column2"), show='headings')
tree.heading("#1", text="id_deathreasonid")
tree.heading("#2", text="Death Reason")
connection = sqlite3.connect('lambtracker_db.sqlite')
cursor = connection.cursor()
cmd = "select id_deathreasonid, death_reason from death_reason_table"
cursor.execute(cmd)
rows = cursor.fetchall()
for row in rows:
    print(row)
    tree.insert('', 'end', values=row)
tree.pack()
root.mainloop()

standard treeview showing up properly and if I try to add the column and header info to the CheckboxTreeview version it looks the same as the standard ttk.Treeview version

from ttkwidgets import CheckboxTreeview
import tkinter as tk
import sqlite3
root = tk.Tk()
tree = CheckboxTreeview(root, column=("column1", "column2"), show='headings')
tree.heading("#1", text="id_deathreasonid")
tree.heading("#2", text="Death Reason")
connection = sqlite3.connect('lambtracker_db.sqlite')
cursor = connection.cursor()
cmd = "select id_deathreasonid, death_reason from death_reason_table"
cursor.execute(cmd)
rows = cursor.fetchall()
for row in rows:
    print(row)
    tree.insert('', 'end', values=row)
tree.pack()
root.mainloop()

How do I get checkboxes in front of the rows in a treeview when I fill the tree view via an SQLite query?




Python - Flask unable to detect a checkbox selected or not

I am able to process the form if checkbox is chosen, but unable to save a default 'None' value in case the checkbox is not selected.

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':
        if request.form['rear_rack'] == 'yes':
            chosen = 'YESSSSSSSS'
        else:
            chosen = 'NOOOOOOOOO'
        return render_template('test.html', name=chosen)
    else:
        return '''
            <h1>TEST<h1>
            <form method='POST'>
                NAME:
                <input type = 'checkbox' id = 'rear_rack' name = 'rear_rack' value = 'yes'>
                <input type='submit'>
            </form>
        '''



Excel - checkboxes in existing file won't show up with a certain user

All,

I have an Excel file with various checkboxes which is used by different users without any problems. The checkboxes are not visible for 1 user. Anyone have an idea?




Checkbox rows - slideUp complete issue

I have multiple divs of 3 checkboxes – each div has a show/hide button (jQuery slideUp) that hides the 'ul.task-list' to display the H2 heading.

<div class="row" id="row-0">
    <button class="toggle">Toggle</button>
    
    <h2>Row 0</h2>
    
    <ul class="task-list">
        <li><input type="checkbox" id="task-0-0" class="task" value="0" /></li>
        <li><input type="checkbox" id="task-0-1" class="task" value="1" /></li>
        <li><input type="checkbox" id="task-0-2" class="task" value="2" /></li>
    </ul>
</div>

<div class="row" id="row-1">
    <button class="toggle">Toggle</button>
    
    <h2>Row 1</h2>
    
    <ul class="task-list">
        <li><input type="checkbox" id="task-1-0" class="task" value="0" /></li>
        <li><input type="checkbox" id="task-1-1" class="task" value="1" /></li>
        <li><input type="checkbox" id="task-1-2" class="task" value="2" /></li>
    </ul>
</div>

I call a 'checkTotal' function, and if everything in the row is checked, add the class of "complete" and slideUp the UL.

let sections = $('.row').map(function() { return this.id }).get(); // gets id of row

const tasksTotal = 3; // the total checkboxes in each row

function checkTotal() {
    sections.forEach(function(i) { // loops section IDs
        let total = $('#'+i+' input:checked').length; // checked in row
        total == tasksTotal ? ($('#'+i).addClass('complete'), $('#'+i+' .task-list').slideUp()) : ($('#'+i).removeClass('complete')); // add class & hide row
    });
}

checkTotal();

The issue is, if I click to show row 0 (after complete) and then check anything in row 1 – it will automatically slide row 0 up again – as complete remains true (all items are checked).

I just can't figure out how to separate these, so they act independently and without looping through again.




React Multiple Checkboxes are not visible as selected after change

I have a list of checkboxes. Checkbox is not visible as selected even after the value has been changed.

Below is my code: -

import React, { useState } from "react";
import { render } from "react-dom";

const CheckboxComponent = () => {
  const [checkedList, setCheckedList] = useState([
    { id: 1, label: "First", isCheck: false },
    { id: 2, label: "Second", isCheck: true }
  ]);

  const handleCheck = (e, index) => {
    checkedList[index]["isCheck"] = e.target.checked;
    setCheckedList(checkedList);
    console.log(checkedList);
  };

  return (
    <div className="container">
      {checkedList.map((c, index) => (
        <div>
          <input
            id={c.id}
            type="checkbox"
            checked={c.isCheck}
            onChange={e => handleCheck(e, index)}
          />
          <label htmlFor={c.id}>{c.label}</label>
        </div>
      ))}
    </div>
  );
};

render(<CheckboxComponent />, document.getElementById("root"));

I was working fine for a simple checkbox outside the loop. I am not sure where is the problem.

Here is the link - https://codesandbox.io/s/react-multiple-checkboxes-sczhy?file=/src/index.js:0-848




UWP 10 XAML Strikeout Content in Checkbox

I am Building a To-Do-List App and want to strikeout the Content in my Checkbox if it is Checked. But i dont know how. Can maybe someone help me?

<StackPanel Orientation="Horizontal">
                            <CheckBox x:Name="checkBoxToDo" 
                                      IsChecked="{Binding istErledigt, Mode=TwoWay}"
                                      Content="{Binding ToDoName}"  />
                        </StackPanel>
internal class ToDoViewModel
   {
       public string ToDoName { get; set; }
       public bool istErledigt { get; set; }
   }
}



Control multiple checkboxes in Material UI

I have a dropdown menu with several checkboxes and I'm trying to add onClick event on each of them. But when I check one of the checkboxes, all of them are checked. This is what I've tried to do:

const [isChecked, setIsChecked] = React.useState(false);

const isCheckboxChecked = () => {
    setIsChecked(isChecked ? false : true)
}

return menuItems.map((item, index) => (
        <React.Fragment>
            <MenuItem
                value={item.value}
                selected={item.value === value}
                key={index}
            >
                <Checkbox
                    key={index}
                    checked={isChecked}
                    onClick={() => isCheckboxChecked()}
                >
                    <Label>{item.label}</Label>
                </Checkbox>
            </MenuItem>
            {index === 2 || index === 3 ? <hr /> : null}
        </React.Fragment>
    ));

As I understand, all checkboxes are using the same state isChecked and I'm wondering how to make them independent.




Declare global CheckBox variable in Word VBA

My word-document has at minimum 2 CheckBoxes. I want to declare them as a global variable to use them often. For some reason I am unable to declare them as variables, which is bad.

Dim cb1 As CheckBox
Dim cb2 As CheckBox
'here are n CheckBoxes possible

cb1 = ActiveDocument.FormFields(1).CheckBox 'here I got a error
'same code for the n CheckBoxes

After I declared them as a global variable I want to set the value of cb2 to False if cb1.Value = True. With this:

If cb1.Value = True Then
    cb2.Value = False
End If

Hopefully you can help me.




Angular mat-checkbox different border-colors for different checkboxes

I need to change the border colors for the following checkboxes , one to green and other to red.

<div style="margin-left:30%;margin-top: 20%;">
    <mat-checkbox>Hello</mat-checkbox><br>
    <mat-checkbox>Hai</mat-checkbox>
</div>



lundi 29 juin 2020

Size of tick does not change when checkbox size increases ANTD

I am using checkboxes from ANT Design and this is the default size of checkbox. default

Now, I want to increase the size of checkbox, so I changed the width and height and now my checkbox looks like this: enter image description here

How can I change the size of tick? This is my CSS:

.ant-checkbox-checked .ant-checkbox-inner{
    background-color: #008000;
    width: 30px;
    height: 30px;

}   



How to select a specific checkbox with dynamic id's with Cypress

I'm trying to select a checkbox but there isn't a single identifier I can figure out that will let me select a specific checkbox.

HTML: enter image description here

Note, this is checkbox two of three on the page. The ID will change depending on my flow, so I can't use the ID to grab this. While it currently shows up as 4 it could be much higher by the time my test gets to it.

This is what I used to find all checkbox's on the current page: cy.get('.mat-checkbox-input')

However, I can't use .eq() to select the second option as it throws an error that the element is detached from the DOM.

Is there any good way to grab a list of checkboxes or selectors in general, and then iterate through them to use only the one I want? In this scenario, i know the checkbox is always the second checkbox.

Everything in this image is identical to the other two checkboxes with the exception of the ID. I guess this is how Angular tends to work. Of course as noted earlier, the ID will change as the page loads, or things are interacted with making it impossible to tell what the number is.

All also have the same label code: enter image description here




Changing Checkbox state using RadioButton input and Button command

I am learning Tkinter/python and still struggling to use them. I already search for my problem here and didn't find anything yet.

I am creating a user interface where:

  • I have several frames
  • two radio-button (protA and protB - left frame) defining if the user wants to do either Protocol A or Protocol B
  • some check-boxes defining steps in Protocol A or B to do (checkbutton1_check - middle frame)
  • one button (StatusButton - left frame) that is supposed to grey out the check-boxes of prot B if Radiobutton indicates Prot A and vice versa

My StatusButton's command is to grey out the checkboxes using the button.config(state='disabled') command. However, I received an error: AttributeError: 'NoneType' object has no attribute 'config'. I am sure checkboxes have this attribute. So maybe you can only define their state in their definition? In that case how can I change the state according to the radiobutton is it is in an other class?

Here is what I wrote so far:

from tkinter import *
from excelRead import *


class MainFrame(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        '''Frame on the middle'''
        self.middleFrame = MiddleFrame(self, bd=2, relief=GROOVE, padx=5, pady=5)
        self.middleFrame.grid(row=3, column=3)

        '''Frame on the Left'''
        self.leftFrame = LeftFrame(self, bd=2, relief=GROOVE, padx=5, pady=5)
        self.leftFrame.grid(row=3, column=2)

        self.StatusButton = Button(master=self.leftFrame, text="Send selection",
                                   command=lambda: self.leftframe_command()).grid(row=4, column=1)

    def leftframe_command(self):
        print(self.leftFrame.Var.get())

        selected = self.leftFrame.Var.get()
        self.middleFrame.checkbutton1_check.config(state='disabled' if selected == 0 else 'normal')

#  LEFT FRAME

class LeftFrame(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.Var = IntVar()
        self.protA = Radiobutton(self, text="Protocol A", variable=self.Var, value=0).grid(row=2, column=1)

        self.protB = Radiobutton(self, text="Protocol B", variable=self.Var, value=1).grid(row=3, column=1)


#  MIDDLE FRAME

class MiddleFrame(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.checkbutton1_var = IntVar()
        self.checkbutton1_check = Checkbutton(master=self, text="step 1",
                                            variable=checkbutton1_var).grid(row=5, column=2)
        
# other checkboxes are here


if __name__ == "__main__":
    # GUI root implementation
    root = Tk()
    root.title("Worklist generator")
    root.geometry("600x600")
    MainFrame(root).grid(row=0, column=0)

    root.mainloop()

I know it is a long code, and maybe not so easy to understand because not elegant! However, if someone knows why I have this attributeError, it would help me a lot.

Also, I tried to type self.checkbutton1_check = Checkbutton(master=self, text="step 1",variable=self.checkbutton1_var, state='normal' if self.parent.leftFrame.Var == 0 else 'disabled').grid(row=2, column=2)

but it tells me that 'MainFrame' object has no attribute 'leftFrame' which is false.

Thank you in advance for your time :)




JS script to change input type from checkbox to radio?

I have a mailpoet form with a list so people can choose out of multiple subscriptions.

  <label class="mailpoet_segment_label">title</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="9" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="2278B8F3-5F48-4047-9B6D-131ED484ADF5">
    Alle Job Alerts</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="4" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="DB7A7A5C-BA6F-4508-9F8F-958BD0B69F58">
    List 1</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="5" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="0F392140-FE75-45C1-970E-AC57D9011B1D">
    List 2</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="8" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="415437C4-9B0D-43BD-9E6D-091EA5F12EC8">
    List 3</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="6" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="28C9611D-DCD1-46BE-8164-FFD1EFCCE257">
    List 4</label>
  <label class="mailpoet_checkbox_label">
    <input type="checkbox" class="mailpoet_checkbox" name="data[form_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz][]" value="7" data-parsley-required="true" data-parsley-group="segments" data-parsley-errors-container=".mailpoet_error_segments" data-parsley-required-message="Selecteer een lijst" data-parsley-multiple="dataform_field_YzQxYmU0Njc5OTk5X3NlZ21lbnRz" wtx-context="33C371EB-732F-4D1F-B5B2-1ED87F3A524C">
    List 5</label>
  <span class="mailpoet_error_segments"></span>

Problem is, I only want them to pick one. Basically, The list does not need te be a checkbox, but a radio button (only one selection allowed).

This Is the way the list is generated, zo I cant edit the html.

What would be the right script to replace the input type to radio (and allow only one selection.)




Wordpress form not displaying check boxes or radio buttons

My check boxes in contact Form 7 (and other contact form plugins) isn't working. I tried on various different themes as well. I suspect it's the CSS disabling their visibility but I'm struggling to identify where and what I need to add! Contact form is here, where there is a tick box: https://wedgewoodroadmanagement.co.uk/contact/

Any help would be greatly appreciated!

Many thanks




how to detect tickmark and checkbox from image

I am trying to detect tick in tickbox in 2nd number table and the number of checkboxes. I am not able to detect it using OCR and by tesseract.here's the link of image




Change color of tick in ANTD Checkbox

How can I change the color of thing tick inside a checkbox? This is what I have done:

.ant-checkbox-checked .ant-checkbox-inner{
    color:#000000;
    background-color: #008000;
}   

.ant-checkbox-checked .ant-checkbox-input{
    color:#000000;
    background-color:#000000;
}



dimanche 28 juin 2020

Attempting to use checkbox in adobe using java Script to reset the values of fields and add in another

I am trying to figure out how to get a checkbox in adobe using javascript to change the values from current value of multiple fields if checked to 0 and another field to change the value to 85

    var FX1 = Number(this.getField("RegistrationFee").valueAsString);
    var FX2 = Number(this.getField("TitleFee").valueAsString);
    var FX3 = Number(this.getField("LienFee").valueAsString);
    var FX4 = Number(this.getField("CountyFee").valueAsString);
    var FX5 = Number(this.getField("TransferFee").valueAsString);
    var FX6 = Number(this.getField("TagFee").valueAsString);
    
    if (this.getField("OutOfState").value != "Off") {
    event.value(FX1,FX2,FX3,FX4,FX5) = 0;
event.value = (FX6 = 0, +85)}

kinda gave up on last part, im still new to coding and would appreciate the help!




acrobat javascript when checkbox is checked, make separate field required

Being a designer, not a coder, I have limited coding ability. I have created an acrobat form with a number of due date fields. They are only required if a corresponding checkbox is checked.

What is the javascript to say that 'if checkbox A is checked, then make date field A required'?

Also, do I save this as a document javascript, or link it to the checkbox? Thanks




React: trying to check/uncheck checkbox

I'm trying to make an obligatory Todo app to help with my React learning . The behavior I'm going for is multiple Todo lists, where you select a todo name and the list of todo items for that show. Select a different todo name and it's list todo items show, etc (like wunderlist/msft todo). For now it's using static json where each item has a child array.

I'm trying to check/uncheck a checkbox in order to mark the todo as done. My problem is that when a click the checkbox it doesn't update until a click away and then click back. What do I need to do to get it to update immediately?

code sandbox: https://codesandbox.io/s/github/cdubone/todo-react-bootstrap?file=/src/App.js

Here's the relevant code:

The function:

const updateChecked = todo => {
todo.IsChecked = !todo.IsChecked;
};

Properties on the component:

onChange={() => updateChecked(todo)}
isChecked={todo.IsChecked}

The input in the component:

<input
type="checkbox"
id={props.id}
name={props.id}
value={props.title}
checked={props.isChecked}
onChange={props.onChange}
/>

Here's the rest of the code if this helps -

JSON:

const TodoData = [
    {
        "Id": 1,
        "Title": "Groceries",
        "TodoList": [
            {
                "Id": 1,
                "Title": "Apples",
                "IsChecked": false
            },
            {
                "Id": 2,
                "Title": "Oranges",
                "IsChecked": false
            },
            {
                "Id": 3,
                "Title": "Bananas",
                "IsChecked": true
            }
        ]
    },
    {
        "Id": 2,
        "Title": "Daily Tasks",
        "TodoList": [{
            "Id": 11,
            "Title": "Clean Kitchen",
            "IsChecked": false
        },
        {
            "Id": 12,
            "Title": "Feed Pets",
            "IsChecked": false
        },
        {
            "Id": 13,
            "Title": "Do Stuff",
            "IsChecked": false
        }]
    },
    {
        "Id": 3,
        "Title": "Hardware Store",
        "TodoList": []
    },
    {
        "Id": 4,
        "Title": "Costco",
        "TodoList": [{
            "Id": 21,
            "Title": "Diapers",
            "IsChecked": false
        },
        {
            "Id": 22,
            "Title": "Cat Food",
            "IsChecked": false
        },
        {
            "Id": 23,
            "Title": "Apples",
            "IsChecked": false
        },
        {
            "Id": 24,
            "Title": "Bananas",
            "IsChecked": false
        }]
    },
    {
        "Id": 5,
        "Title": "Work",
        "TodoList": [
            {
                "Id": 34,
                "Title": "TPS Reports",
                "IsChecked": true
            }
        ]
    }
]

export default TodoData;

App.js

function App() {
  const [todoData, setTodoData] = useState([]);
  const [activeTodoList, setActiveTodoList] = useState(null);
  const [todoListFormValue, setTodoListFormValue] = useState('');
  const [todoListEditorToOpen, setTodoListEditorToOpen] = useState('');
  const [todoListToAdd, setTodoListToAdd] = useState('');
  const [todoItemToAdd, setTodoItemToAdd] = useState('');

  useEffect(() => {
    setTodoData(TodoData);
    setActiveTodoList(TodoData[0]);
  }, []);

  const addTodoList = e => {
    e.preventDefault();
    const newItem = {
      "Id": randomNumber(),
      "Title": todoListToAdd,
      "TodoList": []
    };
    const newArray = [...todoData, newItem];
    setTodoData(newArray);
    setActiveTodoList(newItem);
    setTodoListToAdd('');
  };

  const deleteTodoList = (todolist) => {
    const newArray = todoData.filter(x => x !== todolist);
    setTodoData(newArray);
    setActiveTodoList(newArray[0]);
  };

  const saveEditTodoListTitle = (e) => {
    e.preventDefault();
    const id = Number(e.currentTarget.dataset.id);
    const result = todoData.find(x => x.Id === id);
    result.Title = todoListFormValue;
    closeTodoListTitleEditor();
  };

  const openTodoListTitleEditor = (todo) => {
    setTodoListEditorToOpen(todo.Id);
    setTodoListFormValue(todo.Title);
  };

  const closeTodoListTitleEditor = () => {
    setTodoListEditorToOpen('');
  };

  const addTodoHandler = e => {
    e.preventDefault();
    const newItem = {
      "Id": randomNumber(),
      "Title": todoItemToAdd,
      "IsChecked": false
    };
    const newArray = [...activeTodoList.TodoList, newItem];
    activeTodoList.TodoList = newArray;
    setTodoItemToAdd('');
  };

  const updateChecked = todo => {
    todo.IsChecked = !todo.IsChecked;
  };

  const deleteTodo = (todo) => {
    const newArray = activeTodoList.TodoList.filter(x => x !== todo);
    console.log(newArray);
    activeTodoList.TodoList = newArray;
    setActiveTodoList(activeTodoList);
  };

  const randomNumber = () => {
    return Math.floor(Math.random() * 200) + 100;
  };

  const updateEditTodoList = e => {
    setTodoListFormValue(e.target.value);
  }

  const updateAddList = e => {
    setTodoListToAdd(e.target.value);
  };

  const updateAddTodo = e => {
    setTodoItemToAdd(e.target.value);
  };

  return (
    <div className="App">
      <div className="container">
        <Header />
        <div className="row">
          <ul className="list-group col-sm-4 offset-sm-1">
            {todoData.map(todo => (
              <TodoListItem key={todo.Id}//Not a prop
                onClick={() => setActiveTodoList(todo)}
                title={todo.Title}
                length={todo.TodoList.length}
                selected={activeTodoList.Id === todo.Id}
                deleteClick={() => deleteTodoList(todo)}
                editClick={() => openTodoListTitleEditor(todo)}
                saveEdit={saveEditTodoListTitle}
                closeEditClick={() => closeTodoListTitleEditor()}
                editorOpen={todoListEditorToOpen === todo.Id}
                updateForm={updateEditTodoList}
                value={todoListFormValue}
                id={todo.Id} />
            ))}
            <TextInput
              onSubmit={addTodoList}
              placeholder="Add New List"
              value={todoListToAdd}
              onChange={updateAddList} />
          </ul>
          <div className="col-sm-6">
            {activeTodoList && (
              <ul className="list-group">
                <h2>{activeTodoList.Title} List</h2>
                {activeTodoList.TodoList.map(todo => (
                  <TodoItem key={todo.Id} //not a prop
                    id={todo.Id}
                    title={todo.Title}
                    onChange={() => updateChecked(todo)}
                    isChecked={todo.IsChecked}
                    deleteClick={() => deleteTodo(todo)} />
                ))}
              </ul>
            )}
            <TextInput
              onSubmit={addTodoHandler}
              placeholder="Add New Todo"
              value={todoItemToAdd}
              onChange={updateAddTodo} />
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

TodoItem.js

import React from 'react';
import { PencilIcon, XIcon } from '@primer/octicons-react';
// import PropTypes from "prop-types";

function TodoItem(props) {

    let wrapperClass = "list-group-item list-group-item-action todo-item";
    if (props.isChecked === true) {
        wrapperClass += " done";
    }

    return (
        <li className={wrapperClass}>
            <input
                type="checkbox"
                id={props.id}
                name={props.id}
                value={props.title}
                checked={props.isChecked}
                onChange={props.onChange}
            />
            <label htmlFor={props.id}>{props.title}</label>
            <div className='modify-todo'>
                <button><PencilIcon size={16} /></button>
                <button data-parent={props.id} onClick={props.deleteClick}><XIcon size={16} /></button>
            </div>
        </ li>
    )
}

export default TodoItem;



Migrating from localstorage to localforage - saving a checkbox

I have some localstorage code to save whether a checkbox is checked or not to hide or show a div in a group of div's (as well as hide it for printing if checked). It works well. Trying to migrate the same code to localforage fails. Most likely due to my own lack of understanding! I am hoping someone can point me in the right direction.

My localstorage code:

var checkboxValuesCommon=JSON.parse(localStorage.getItem("formValuesCommon"))||{},
$checkboxesCommon=$("input.printitCommon"),
$commonDrugCommon=$(".eachdrug.eachcommondrug");

function updateStorageCommon(){
$checkboxesCommon.each(function()
{
checkboxValuesCommon[this.id]=this.checked,this.checked? 
$(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print"):$(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print")}),
localStorage.setItem("formValuesCommon",JSON.stringify(checkboxValuesCommon))}

$checkboxesCommon.on("change",function(){
this.checked?$(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print"):$(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print"),updateStorageCommon()}),

$.each(checkboxValuesCommon,function(e,r) 
{$("#"+e).prop("checked",r)}),
$checkboxesCommon.each(function(){
$(this).is(":checked")?$(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print hidden"):$(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print hidden")
});

Localforage code:

localforage.getItem('formValuesCommon').then(function(value) {
var checkboxValuesCommon = value;
var $checkboxesCommon = $("input.printitCommon"),
$commonDrugCommon = $(".eachdrug.eachcommondrug");
function updateStorageCommon() {


$checkboxesCommon.each(function() {
    checkboxValuesCommon[this.id] = this.checked, this.checked ?  $(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print") : $(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print")
}); localforage.setItem("formValuesCommon", true);
}

 $checkboxesCommon.on("change", function() {
this.checked ? $(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print") :  $(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print"); 
updateStorageCommon()
}); 
$.each(checkboxValuesCommon, function(e, r) {
$("#" + e).prop("checked", r)
}); 
$checkboxesCommon.each(function() {
this.checked ? $(this).closest(".eachdrug.eachcommondrug").removeClass("hidden-print hidden") : $(this).closest(".eachdrug.eachcommondrug").addClass("hidden-print hidden")
});
});



JQuery calling .elements returns undefined

I'm trying to loop through a group of checkboxes using jQuery. The checkboxes are written in HTML as such:

<div id="checkboxes">
    <div class="custom-control custom-checkbox">
        <input type="checkbox" name="XXX" class="custom-control-input" id="a" value="XXX">
        <label class="custom-control-label" for="a">XXX</label>
    </div>
    <div class="custom-control custom-checkbox">
        <input type="checkbox" name="XXX" class="custom-control-input" id="b" value="XXX">
        <label class="custom-control-label" for="b">XXX</label>
    </div>
    ...
</div>

I attempt to get an array of the checkboxes in JQuery with this (part of a response to a button click):

var choices = document.getElementById("checkboxes").elements;

However, when I call for(let i = 0; i < choices.length; i++), I get an error in the console:

Uncaught TypeError: Cannot read property 'length' of undefined

Apparently, the variable choices is undefined. I've done some research, but I can't find where the problem is or another way I can get an array of the checkbox elements.




Checkbox value in controller in laravel

I am trying to get all the payments that is been selected through the checkboxes and then update the value in the database by '1' which means its paid. But when I try to get the values of checkbox array I only get 1 data in the array and not all selected. Any help?

View

<form action="/paid/" method="post" enctype="multipart/form-data">   
        @csrf
     <td><input type="checkbox" name="checked[]" value=""></td>
     <td>  </td>
     <td>
         <input id="commission" type="text" class="form-control" name="commission" 
         value="" readonly  autocomplete="notes" style="width: 15%;" autofocus>
     </td>
                                        
     <td>  </td>
     <td> 
         @if($p->sellet_commission_paid == '0')
            <button type="submit" class="btn btn-default" style="background-color:red">
                <b><em>UNPAID</b></em>
            </button>
         @else
            <a href="#" class="btn btn-default" style="background-color:green"><b><em>PAID</b></em></a>
         @endif                                    
     <td>   
 </form>

Controller

$checked = $request->input('checked');
     //   $checkboxes = $request->checked;

   dd($checked);
   die();
    //    dd(checkboxes);



how to update hidden checkbox in html input

i have an html input page to add scores in a grid.

   status valueA valueB checkboxA checkboxB
1       4      5      2         x         x
2       3      3      1                   x
3       5      7      2                   
4       4      6      3         x

including some checkboxes like this one with a ng-hide condition (angularjs) if the status is 3. (means all status with the number 3 on it, i dont need to see so i am not able to check the checkbox.)

<form action="/save_score.php">
  ...
  <td><input type="hidden" value="0" name="checkboxA1"/>
  <input type="checkbox" value="1" name="checkboxA1" ng-hide="status1 == 3"/></td>
  ...
  <input type="submit" value="Save">
</form> 

this input page works fine. the checkboxA2 with status2 = 3 for example i cant see therefore cant check. and the others are visible and i can use them properly. the scores are added to the system correctly.

later on after i saved the scores, i can go into a kind of history page of all added scores of different dates where i see all the scores from previous times where i can change them (i need this page because sometimes it happens that i made a mistake and want to alter the scores) i click on Details of a score and come back in to the score grid.

Score History

Date        Score  
11-11-2019  89     Details 
10-10-2019  90     Details 
09-09-2019  88     Details 
...

among them also the checkboxes.

<form action="/update_score.php">
  ...
  <input type=“checkbox” value= “<?php echo $checkboxA1; ?>” name="checkboxA1" <?php if($checkboxA1) { 
  echo 'checked="checked"';} ?>></td> 
  ...
  <input type="submit" value="Update">
</form> 

now i would like to change this line so the checkboxes with status 3 are hidden. but till now i didnt find a way to hide the respective checkboxes without getting an update error.

i tried this in the input type... (that makes the respective checkboxes disappear)

  type="<?php if ($status1 > 3) {echo 'checkbox';} else { echo 'hidden';}?>"

the hidding of the checkboxes is a design feature, i wanted to add, because it looks nicer and it avoid additional errors during the entering and updating of the scores, but it doesnt work yet, because all the hidden checkboxes cant be updated. they all return "" which my mysql database update doesnt accept.

so my question is, how to hide the checkbox and get the update correctly




samedi 27 juin 2020

Is it possible in HTML to create an ALIAS for common tags with common attributes?

What I am looking into is to improve semantics. I wonder if I can reduce the amount of TAG attributes into a set of TAGs which would function as ALIASes.

For example, the tipical hidable control using checkbox is:

<label for="toggle">Do Something</label>
<input type="checkbox" id="toggle">
<div class="control-me">Control me</div>

I would like to use in a table, where a sub-grouping title is able to hide some rows: https://jsfiddle.net/diegoj2020/adfpt8n2/6/

What I would like to get the html is something like next code, where the input, the label, the class, style, type and id attributes are saved from the semantics

<tooglecontrol>Do Something<tooglecontrol>
<div class="control-me">Control me</div>

For creating new TAGs I have read an understand this other question, but I couldn't figure it out how to replace an INPUT element, in other words, how to make tooglecontrol to show and behave like a checkbox.

Is there a way to create your own html tag in HTML5?




toggling action in checkboxes in React-Redux doesn't work

Hello i have problem with my action in Redux. I want will check single checkbox and if it will be clicked, my state will change

FOR EXAMPLE: if i click on second element my value will change. Other elements will doesnt change
if i have state[0].question[0].answers[1].checked = true || false if i will click 2x in the same place

will be helpful:

state - I have state which is arr and have some objects inside (https://github.com/RetupK/QuizApp/blob/master/src/store/quiz/quizReducer.js)

actions creators - (https://github.com/RetupK/QuizApp/blob/master/src/actions/quiz/quizActions.js)

quizId - it depends on what we quiz we will choose. It is Routing match parametr. here is our routing (https://github.com/RetupK/QuizApp/blob/master/src/App.js)
here is our Component and showed how i did mapDispatchToProps and how i connected this with view (https://github.com/RetupK/QuizApp/blob/master/src/containers/quizContainer.js)

activeQuestion - it is which question is active this is local state in component.

Someone know how to resolve this problem with doesnt working this action?




How to change radio button color in ant design?

I'm using antd radios and checkboxes. I want to give custom colors to them. I found answer about checkbox but found no way to change radio button color.

Is there any way to do so?




jquery making html checkbox appear as blinking question mark and exclamatory mark

i have created a checkbox list group from bootstrap, the code is like below:

<link href="https://www.ishtasakhi.com/assets/css/bootstrap-checkbox-radio-list-group-item.css" rel="stylesheet" />
<link href="https://www.ishtasakhi.com/assets/css/bootstrap-checkbox-radio-list-group-item.min.css" rel="stylesheet" />
<div class="list-group checkbox-list-group">
  <div style="height:45px;" class="list-group-item">&nbsp;<label><input type="checkbox"><span class="list-group-item-text"><i class="fa fa-fw"></i> Large</span></label></div>
  <div style="height:45px;" class="list-group-item">&nbsp;<label><input type="checkbox"><span class="list-group-item-text"><i class="fa fa-fw"></i> Medium</span></label></div>
</div>


  <script src="https://www.ishtasakhi.com/assets/js/jquery-plugins.js"></script>

as you can see I have included my jquery file, now when u run the code it will start blinking questionmark and explanatory mark , where as it should show tickbox. can anyone please tell me what could be the reason for this error. thanks in advance




vendredi 26 juin 2020

Getting the values of all checkbox checked in a group as comma separated

I have a group of checkbox

<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely1" value="1">
  <label for="cmsms_which_days_are_you_most_likely1">Monday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely2" value="2">
  <label for="cmsms_which_days_are_you_most_likely2">Tuesday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely3" value="3">
  <label for="cmsms_which_days_are_you_most_likely3">Wednesday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely4" value="4">
  <label for="cmsms_which_days_are_you_most_likely4">Thursday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely5" value="5">
  <label for="cmsms_which_days_are_you_most_likely5">Friday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely6" value="6">
  <label for="cmsms_which_days_are_you_most_likely6">Saterday</label>
</div>
<div class="cl"></div>
<div class="check_parent">
  <input type="checkbox" name="cmsms_which_days_are_you_most_likely" id="cmsms_which_days_are_you_most_likely7" value="7">
  <label for="cmsms_which_days_are_you_most_likely7">Sunday</label>
</div>

                                        

When the checkbox values are changing I want to get the checked values of checkbox as an array or comma separated value using jQuery.




listview con 2 checkbox en xamamarin androide

una pantalla con una lista de usuario, cada uno se carga con 2 checkbox, uno para activo y otro inactivo, como puedo hacer para que al seleccionar, ya sea activo o inactivo almacenarlo y que al momento de dar click sobre el boton guardar se almacenen

esta es la plantilla que cree para asignarla en el adapter

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:padding="8dp">

    <LinearLayout 
       android:orientation="horizontal"
        android:id="@+id/linearLayout190"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
        
        <ImageView
        android:id="@+id/Image"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:padding="5dp"
        android:src="@drawable/lista_usuario" />
        <TextView
            android:text="Nombre de Usuario"
            android:id="@+id/Nombre_Usuario"
            android:layout_width="185dp"
            android:layout_height="match_parent"
            android:textSize="14dip"
            android:textStyle="italic"
            android:paddingTop="11dp"
            android:layout_marginLeft="5dp"/>
        <CheckBox
            android:paddingLeft="25dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"            
            android:paddingTop="15dp"
            android:layout_below="@+id/Nombre_Usuario"
            android:id="@+id/cb_Activo" />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_below="@+id/Nombre_Usuario"
            android:id="@+id/cb_Inactivo" />
    </LinearLayout>
</RelativeLayout>



Flutter: Change Checked Colour of Checkboxes

I am trying to create a bottom sheet with checkboxesenter image description here. I'm finding it difficult to get the checkboxes to be checked and show a different colour once tapped. At the moment the checkbox just stays empty.

How would I solve this?

bool isChecked = false;

...

Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.fromLTRB(50, 10, 10, 10),
                    child: Row(
                      children: <Widget>[
                        Expanded(child: Text('Classes Booked')),
                        Checkbox(
                          checkColor: isChecked
                              ? Colors.grey
                              : Theme.of(context).colorScheme.aqua,
                          value: isChecked,
                          onChanged: (bool value) {
                            setState(() {
                              value = true;
                            });
                          },
                        ),



adding custom angular checkBox


<div *ngFor="let conflictRule of conflictRulesMap1 | keyvalue, let p = index">
    <div *ngFor="let ruleContainer of conflictRule.value ,let k = index">
        <div align="left" class="existingRule">
         
               <!-- first CHECKBOX GOES HERE  -->
                <rule [changedConfigDataList]="getChangedConfigDataListConflict(conflictRule.key)"
                [configId]="conflictRule.key" [configLookupMetadata]="configLookupMetadata"
                [disableExpansion]="disableExpansion" [index]="k" [isSaveEnabled]="isSaveEnabled" [mode]="mode"
                [openState]="expandRules" [rule]="ruleContainer.updatedRule">
            </rule>
        </div>
        <div class="ruleSpearator"> OR </div>
        <div align="right" class="updatedRule">

             <!-- second  CHECKBOX GOES HERE  -->

            <rule [changedConfigDataList]="getChangedConfigDataListConflict(conflictRule.key)"
                [configId]="conflictRule.key" [configLookupMetadata]="configLookupMetadata"
                [disableExpansion]="disableExpansion" [index]="k" [isSaveEnabled]="isSaveEnabled" [mode]="mode"
                [openState]="expandRules" [rule]="ruleContainer.originalRule">
            </rule>
        </div>
        .
    </div>
</div>

here i want to add two checkBoxes at the mentioned place. The code is itearating a map for keys , then values for that corresponding key , only one of the two has to be selected..any help about forms or any way to do.




Dynamic checkboxes from one table and update a joining table

I am a total beginner and after long searches to no avail I have come to ask you for some help. I have 3 tables. Tutors, Availability and Periods. The periods table (ID, Name) contains a rows - Mornings, Afternoon, Evenings, Weekends The Availability table has FKs pointing to Users (ID) and Periods (ID)

The Periods table is displayed as a list of checkboxes so the Tutor can select which ones he/she wants.

I want to update the Availability table with the User ID and selected Period(s) row by row.

Also when I display the list of periods how do I show which ones the tutor selected?

And finally, how to I update the Availability table to store only the checked periods.

If the Availability table has the following:

ID User ID, Period ID  
1       1        1  
2       1        4

So User 1 is available for Mornings and weekends. If User 1 then de-selects period 1 how can I update the availability table to remove the correct row?

I hope this makes sense and I thank you in advance.




A checkbox on my form looks like a text Input

enter image description here[I have this code on my html fileÑ

<div class="input" style="height:20px">
        <img src="../img/pass.png" class="middle iconColor">
        <input type="password" class="inputNoBorder" placeholder="Contraseña" id="login-pass" />
    </div>       
     <div>
          <!-- An element to toggle between password visibility -->
        <input type="checkbox" ><span>Show password</span>
     </div>
    <br><br>
    <button class="blueButton" id="login">Iniciar Sesión</button>
    <br>

and it runs by nodeserver.js and appears like a text box]2




question mark and exclamation mark blinking in checkbox html instead of tick box

i have created a checkbox list group from bootstrap, the code is like below:

<link href="https://www.ishtasakhi.com/assets/css/bootstrap-checkbox-radio-list-group-item.css" rel="stylesheet" />
<link href="https://www.ishtasakhi.com/assets/css/bootstrap-checkbox-radio-list-group-item.min.css" rel="stylesheet" />
<div class="list-group checkbox-list-group">
  <div style="height:45px;" class="list-group-item">&nbsp;<label><input type="checkbox"><span class="list-group-item-text"><i class="fa fa-fw"></i> Large</span></label></div>
  <div style="height:45px;" class="list-group-item">&nbsp;<label><input type="checkbox"><span class="list-group-item-text"><i class="fa fa-fw"></i> Medium</span></label></div>
</div>

now instead of tickbox, the checkbox is showing question mark and exclamatory mark blinking like below,

enter image description here

this is how it actually should look like demo can anyone please tell me what could be wrong here. thanks in advance




Enabling or disbaling a field according to value of Yes/No (checkbox) field in sharepoint

I have created a list in sharepoint of the form below: enter image description here

I want to hide the fields 'Tool' and 'Responsible' when the checkbox for 'RCA Required' is unchecked (or No), otherwise the fields such as 'Tool' and 'Responsible' should be shown. I have tried the following code in script editor of sharepoint:

<script src="https://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select[title='RCA Required']").click(function() {
if ($('input[title="RCA Required"]').is(':checked'))
{
$('nobr:contains("Tool")').closest('tr').show();
$('nobr:contains("Responsible")').closest('tr').show();
}
else
{
$('nobr:contains("Tool")').closest('tr').hide();
$('nobr:contains("Responsible")').closest('tr').hide();
}
});
});
</script> 



Update multiple products boolean (active/inactive) value in single form in Ruby on Rails 4

I want to show the list of products in a single form with a single submit button. I need to update the product's active/inactive status with a checkbox in a form. Something like:

**Product**      **Status**
Product 1    Checkbox(:is_active) => True
Product 1    Checkbox(:is_active) => False

Save

I'm not sure how should I proceed. I went through the tutorial here

but I need to update active/inactive status at same time.




Checkbox is not getting updated in React JS Functional component

I'm trying to add a checkbox in react js but it is not changing its value.

function TestToolbar(args) {
  let overRideFlag=0;
  if (overRideFlag === 0){
    overRideFlag=false;
  }
  else{
    overRideFlag=true;
  }
  const handleOverRideChanges = (overRideFlagParm) => {
    overRideFlag=!overRideFlagParm;
  };
  return (
    <div className="">
  <Col sm={1}>
  <div className="" onClick={() => handleOverRideChanges(!overRideFlag)}>
        <input type="checkbox" id="overRideEnabled" name="override" checked={overRideFlag} onChange={() => handleOverRideChanges(overRideFlag)} />
        <label htmlFor="overrid">Override</label>
  </div>
  </Col>
  <Col sm={9}>
    <AddAnotherComponent disabled={disabled} overRideStatus={overRideFlag} />
}
);
}

The issue is that the value of overRideFlag is always true. it is not changing to false at no time. Another issue is checkbox is not getting checked even though its value is true. Finally am passing the value to another component as a prop but it is not getting change. Could anyone kindly advise how the issue can be resolved.

#UPDATE

When I click the checkbox actually the handleOverRide Changed execute twice




jeudi 25 juin 2020

How to get input checked items in Javascript

1'm trying to get user Input checkbox selection using Javascript, but I'm having some issues doing it. Here is the code I'm using to achieve that:

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

<label><input type="checkbox" onclick="toggle(this)"> Get All</label><br>
<label><input type="checkbox" name="value" value="1"> One</label><br>
<label><input type="checkbox" name="value" value="2"> Two</label><br>
<label><input type="checkbox" name="value" value="3"> Three</label><br>
<label><input type="checkbox" name="value" value="4"> Four</label><br>

<br>

<button onclick="getSelected()">Select Options</button>

<script>
  function getSelected() {

    var list = Array();

    $("input[type=checkbox]:checked").each(function() {
      list.push($(this).val());
    });
    console.log(list);

    if (Array.isArray(list) && list.length) {

      var myString = '';

      for (var i = 0; i < list.length; i++) {
        if (list.length > 1) {
          myString += '[';
          myString += list[i] + ']';
          if (i !== list.length - 1) {
            myString += ' NEST ';
          }
          console.log(myString);

        } else {
          myString = '[' + list[i] + ']';
          console.log(myString);

        }
      }

    }
    return myString;
  }

  function toggle(opc) {
    checkboxes = document.getElementsByName('value');
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = opc.checked;
    }
  }
</script>

Browser's console shows the following output:

[on] NEST [1] NEST [2] NEST [3] NEST [4]

Looking at the Input shown above, I don't have one option called "on", but the array always gives me "on" on the list.

(5) ["on", "1", "2", "3", "4"]
0: "on"
1: "1"
2: "2"
3: "3"
4: "4"
length: 5

I was expecting to get just [1] NEST [2] NEST [3] NEST [4]. I was unable to identify where that "on" option originates.

Any help or clue will be appreciated.

PS: I forgot to mention that this only happens when I mark Get All on the input option. If I mark one by one the code works fine.

Marcio




Multiple checkbox value in PHPMailer displays empty [duplicate]

I have set up PHP mailer to deliver contact form information on my website. I am having trouble sorting out the multiple checkbox inputs. It appears empty in emails. Here the form HTML code:

<div class="form-group">
            <label class="checkbox-inline">
                <input name="time" type="checkbox" id="inlineCheckbox1" value="AM"> AM
            </label>
            <label class="checkbox-inline">
                <input name="time" type="checkbox" id="inlineCheckbox2" value="PM"> PM
            </label>
        </div>

In my PHP code, I added below to check if there are inputs for the checkboxes:

if($_POST["time"])  {
        $time_array = $_POST['time'];
        $time_tostring = implode(", ", $time_array); 
    }

Then in the mail code, I added this:

$mail = new PHPMailer(true);
try {
    //Server settings
    $mail->isSMTP();
    $mail->Host = $config['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['username'];
    $mail->Password = $config['password'];
    $mail->SMTPSecure = $config['secure'];
    $mail->Port = $config['port'];

    //Recipients
    $mail->setFrom($config['from'], $config['fromName']);
    $mail->addAddress($config['sendTo']);
    //$mail->addCC($config['sendToCC']);            
    $mail->addBCC($config['sendToBCC']);            

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Website Contact Form';
    $mail->Body    = '<p>Emptied on: ' . $_POST['day'] . "</p>"
    . "<p>Time: "  . $time_tostring . "</p>"        
    . "<p>Name: " . $_POST['name'] . "</p>"
    . "<p>Address: " . $_POST['address'] . "</p>"
    . "<p>Phone Number: " . $_POST['number'] . "</p>"
    . "<p>Email: " . $_POST['email'] . "</p>"
    . "<p>Where did you hear about us: " . $_POST['how'] . "</p>"
    . "<p>Service interested in: " . $_POST['comments'] . "</p>"        
    ;

    $mail->send();
    echo json_encode(['status' => true, "data" => 'Message has been sent']);
} catch (Exception $e) {
    echo json_encode(['status' => false, "data" => "Message could not be sent\nMailer Error: " . $mail->ErrorInfo]);
}

In the email sent, the time is empty and do not display any value.

I also tried the line below directly but it didn't work too.

. "<p>Time: "  . implode(', ', $_POST['time']) . "</p>" 

I am not sure why this is not working. Any idea is appreciate.




MVC if checkbox is checked return true to controller and if it isn't, return false

Currently I have a checkbox that looks like this

 Adjust inventory levels <input type="checkbox" name="invChkBox" id="invChkBox" value="true" />

And my post controller method has parameters that look like this

 public ActionResult EditItemInstance(int ID, string serialNumber, int ItemID, bool invChkBox)

but when the chkBox isn't checked it returns an error page. That has an error message saying

null entry for parameter 'invChkBox' of non-nullable type 'System.Boolean'

How can I edit my code so that it returns false if the checkbox is not clicked?




mercredi 24 juin 2020

PySide2 Lambda Binding Issue

I am working on a (fairly basic) feature in a PySide2 application. The application contains a list of checkboxes, and when a checkbox is checked, I need to append the index of the checkbox to a list. My unsuccessful attempt at this can be seen below...

checked = []

cb1 = QCheckBox('1')
cb2 = QCheckBox('2')
cb3 = QCheckBox('3')

cbs = [cb1, cb2, cb3]

for n, cb in enumerate(cbs):
    cb.stateChanged.connect(lambda: checked.append(n) if cb.isChecked() else checked.remove(n))

I have found that the issue here is with "late binding" as described in python's common gotchas. The value of n is always 2 whenever the checkbox is activated. However, I have tried using the following solutions from the docs which also have failed.

for n, cb in enumerate(cbs):
    cb.stateChanged.connect(lambda n=n: checked.append(n) if cb.isChecked() else checked.remove(n))
for n, cb in enumerate(cbs):
    cb.stateChanged.connect(lambda n=n, button=button: checked.append(n) if cb.isChecked() else checked.remove(n))

The first solution gives seemingly random and incorrect values for n, and the second somehow turns the button variable into an integer. In a case with only a few checkboxes I would consider setting these functions one-by-one but in the actual application there needs to be around 20 checkboxes. Any insight on this would be greatly appreciated!




Need "add on" check box option with image after add to cart action with pop up woocommerce| Check screenshot

I need help to "add on" action after add to cart options(cross sale / up sell) with image after add to cart action with pop up woocommerce. Check the below screenshot that i took from other websites.

Thanks in advance

enter image description here




why is input[type=checkbox] not working in css in this example?

We are having a CSS problem. In an attempt to create an MWE multiple things were not working. So I created a CSS file containing * {} the default rule, an id #x which should be the highest specificity rule? as well as the original problem input[type=checkbox]. We are very confused.

Testing under chrome/chromium and firefox.

Can anyone explain:

  1. Why is hell not background yellow since the text is inside the div box?

  2. Why is the checkbox not font size 28pt and blue since it is a checkbox? It is not overriding input. it is as though input[type=checkbox] is not a legal css pattern, but there are answers all over including stackoverflow showing it. see: CSS/HTML: How do I change the color of the check mark within the checkbox input? https://www.geeksforgeeks.org/how-to-style-a-checkbox-using-css/

  3. How could we override and make disabled checkboxes look different than the default behavior? The default is to ghost out the checkboxes and it is hard to see whether they are checked or not. How would we set the color of the background, line and check of the checkbox only for disabled checkboxes?

CSS file:

#x {
  background-color: #cc0;
  font-size:10pt;
  color: #00f;
}
.answer {
  background-color: #800;
  color: #cc0;
  font-size:20pt;
}

input {
  font-size: 28pt;
  background-color: #0c0;
}

input[type="checkbox"] {
  font-size: 14pt;
  background-color: #00f;
}

input[type="checkbox"][disabled] {
  font-size: 14pt;
  background-color: #000;
}

* {
  background-color: #0cc;
}

We also tried input[type=checkbox] without quotes and input[type=checkbox]:disabled. I thought square brackets are for subtypes and colon is for pseudotypes, but I'm obviously very confused so an explanation would also be very useful.

HTML file:

<html>
<head>
  <link rel="stylesheet" href="styles.css"></link>
</head>
<body>
  <div id="x">
    hell
    <input  type="text" />
    <input  type="checkbox" value="A" >A</input>
    <input  type="checkbox" value="B" checked disabled>B</input>
    <input type="radio" value="C">C</input>
  </div>
  <div class="answer">
    hello
    <input  type="text" />
    <input  type="checkbox" value="A" checked>A</input>
    <input  type="checkbox" value="B" >B</input>
    <input type="radio" value="C">C</input>
  </div>
</body>
</html>



JQuery multiple checkbox selection "or" instead of "and"

In my shopify liquid code, in a for loop, I create multiple <ul> elements with multiple checkboxes inside each <ul> for selected tags. If a 1st checkbox is clicked, the tag is added to the url: .../tag1. If I select a 2nd checkbox, the 2nd tag is added to the url, the url then looks like .../tag1+tag2. I need the condition to be "or" when the checkboxes are located inside the same <ul> and "+", so "and", only for different <ul>. Example, one <ul> is for "artist", another for "price". If two artist checkboxes are ticked and one for price, I want to show the selected price tag for artist1 and selected price tag for artist2. So: If (artist-tag1 or artist-tag2) and price-tag1. At the moment all checkboxes are with "+" condition. Any ideas how to do that would be heavily appreciated! My liquid code and JQuery:



$('.filter_checkbox').off().change( function(){
var newURL = $(this).nextAll('a').attr('href');
window.location.href = newURL;
});



Output mysql database table with a checkbox column and query checked checkboxes in another file [duplicate]

The concept is to display mysql database table and add a column with a checkbox for each row. The user will just check the desired data and click a button which will direct the user to a new page.

I was successfully able to add a checkbox column but when i select a checkbox, nothing is displayed in the other page. I currently just have two files: index.php shows the table with checkbox and search.php shows the selected checkbox.

index.php

      <div style="overflow-x:auto;">
        <form action= 'search.php' method='post' name='check'>"
         <table id="test_data">
           <tr>
             <th> Select </th>
             <th> Test ID </th>
             <th> Path </th>
             <th> Video 1 Path </th>
             <th> Video 2 Path</th>
             <th> Video 3 Path</th>
             <th> Video 4 Path</th>
           </tr>

           <!--Prints out data from test_data table-->
    <?php
    $sql = "SELECT * FROM test_data";
    $result= mysqli_query($conn, $sql);
    $queryResults = mysqli_num_rows($result);

    if ($queryResults > 0) {
        // echo "<form action= 'ttt.php' method='post' name='check'>";
        while ($row = mysqli_fetch_assoc($result)) {
            echo "<tr>
                    <td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
                       <td> ".$row['test_id']." </td>
                       <td> ".$row['path']." </td>
                       <td> ".$row['video1_path']." </td>
                       <td> ".$row['video2_path']." </td>
                       <td> ".$row['video3_path']." </td>
                       <td> ".$row['video4_path']." </td>
                     </tr>";
        }
        echo "<input type='submit' name='update' value='Apply'/>";
        // echo "</form>";
        }
    ?>
         </table>
         <!-- <input type='submit' name='update' value='Apply'/> -->
        </form>
       </div>

search.php

<div style="overflow-x:auto;">
    <table id="test_data">
        <tr>
            <th> Test ID </th>
            <th> Path </th>
            <th> Video 1 Path </th>
            <th> Video 2 Path</th>
            <th> Video 3 Path</th>
            <th> Video 4 Path</th>
        </tr>

<script>
if (document.querySelector('form[name="check"] input[type="checkbox"]:checked')){

<?php
    if (!empty($_POST['checkbox_id'])) {
        $servername = "localhost";
        $username = "root";
        $password = "mysql";
        $database = "dat_simulation";
        $conn = new mysqli($servername, $username, $password, $database);
        // $checkbox_id = $_POST['checkbox_id'];
        if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $num_var= " ";
    $num_var= mysqli_real_escape_string($conn,$_POST['checkbox_id']);
    $sql= "SELECT * FROM test_data WHERE test_id= '$num_var'";
    $result = mysqli_query($conn, $sql);
    if (!$result) {
        echo 'MySQL Error: ' . mysqli_error($conn);
        exit;
    }
    // $queryResults = mysqli_num_rows($result);

    if ($result->num_rows > 0) {
        while ($row = $result->mysqli_fetch_assoc()){
            $field1name = $row["test_id"];
            $field2name = $row["path"];
            $field3name = $row["video1_path"];
            $field4name = $row["video2_path"];
            $field5name = $row["video3_path"];
            $field6name = $row["video4_path"];

            echo "<tr>
                    <td> ".$field1name." </td>
                    <td> ".$field2name." </td>
                    <td> ".$field3name." </td>
                    <td> ".$field4name." </td>
                    <td> ".$field5name." </td>
                    <td> ".$field6name." </td>
                  </tr>";
    ?>
    <?php
        }
    } 
    $conn->close();
    }
    ?>

    }else {
        alert("Please select checkbox ");
    }
    </script>
          </table>
        </div>

When i inspect the code in the browser i get the following error:

Uncaught SyntaxError: Unexpected token '<' if (document.querySelector('form[name="check"] input[type="checkbox"]:checked')){
Warning: mysqli_real_escape_string() expects parameter 2 to be string, array given in..

Can someone help me in this?

Is there a simpler solution to query checked checkboxes from a database using php/js? Thank you




mardi 23 juin 2020

I'm using a hidden for with a checkbox to send strings to a property, but they are sent even if the checkbox isn't checked

so I've been trying to use a checkbox to send a list of values to a string property in my model. but for some reason, the values are sent, even after i initialized with the bool false and left the checkbox unchecked.

these are my models

public class Profesor
{        
    public List<AsignaturaModelo> Asignaturas { get; set; }

    public Profesor()
    {
        Asignaturas = new List<AsignaturaModelo>();
    }

}

public class AsignaturaModelo
{
    public string NombreA { get; set; }


    public bool Selected { get; set; }
    
}

My controller

public ActionResult Create()
        {
            var model = new Profesor
            {
                Asignaturas = new[]
                {
                    new AsignaturaModelo{NombreA = "Programacion 1", Selected = false},
                    new AsignaturaModelo {NombreA = "Programacion 2", Selected = false}
                }.ToList()
            };
            return View(model);
        }

        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Profesor modelo)
        {
            try
            {
                
                if (ModelState.IsValid)
                {                   
                    profesors.Add(modelo);
                    return RedirectToAction(nameof(Index));
                }

            }
            catch
            {
                return View(modelo);
            }
            return View(modelo);
        }

My view

@Html.EditorFor(x => x.Asignaturas)

and my EditorTemplate

@model AsignaturaModelo

    <div>
        @Html.CheckBoxFor(x => x.Selected)
        @Html.HiddenFor(x => x.NombreA)
        @Html.LabelFor(x => x.Selected, Model.NombreA)
    </div>

Not sure what am i doing wrong, also sorry for the variable names. Thanks in advance!




Foreach duplicating checkbox inputs form

Instead of having 2 inputs with the full-time and the contractor box ticked, I have 4 inputs see below. How can I avoid the duplication of the inputs, and ends up with two inputs only that will have the boxes ticked for full-time and contractor?

Here is the code:

    <?php       
      $jobEmploymentType = "FULL_TIME,CONTRACTOR";
       $jobEmploymentTypeExplode = (explode(",",$jobEmploymentType));   
    //print_r($jobEmploymentTypeExplode);
           foreach ($jobEmploymentTypeExplode as $jobType) : ?>
                
   <span class="asterisk">*</span>  <label for="jobEmploymentType">Employment Type</label><br>
  <input type="checkbox" class="w3-check" id="fullTime" name="fullTime" value="FULL_TIME" <?= ($jobType == "FULL_TIME")? "checked":"";?>>
  <label for="fullTime"> FULL-TIME</label><br> 

  <input type="checkbox" class="w3-check" id="contractor" name="contractor" value="CONTRACTOR" <?= ($jobType == "CONTRACTOR")? "checked":"";?>>
  <label for="contractor"> CONTRACTOR</label><br>
        <?php endforeach; ?> 

enter image description here

Expecting result:

enter image description here




How to get the values of multiple checkboxes in Angular 8

I am trying to get the values of the checkboxes that are selected. I have the following code:

<div style="background-color:lightblue;" >
    <div class="content">
       <label class="label">Province</label>
       <div class="form-check form-check-inline" *ngFor = "let province of utilities.Provinces; let i of index">    
           <label class="form-check-label" for="inlineCheckbox1" ></label>
           <input class="form-check-input" [formControl]= "province" (change)="getSelectedProvinces()" type="checkbox" id="inlineCheckbox" value="option1"> 
      </div>
 </div>     

In .ts I have the following

import { Component, OnInit } from '@angular/core';
import { UtilitiesService } from '../_services/utilities.service';
import { Utilities } from '../models/utilities';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
selector: 'app-filtering',
templateUrl: './filtering.component.html',
styleUrls: ['./filtering.component.css']
})
export class FilteringComponent implements OnInit {
   utilities: Utilities;
   provinces:  string[] = [];
   selectedProvinces: string[] = [];
   selectedCategories: string[] = [];

   constructor(private utilityService: UtilitiesService) { }

   ngOnInit() {
     this.loadUtilities();
  }

  loadUtilities() {
    this.utilityService.getJSON().subscribe((utilities: Utilities) => {
    this.utilities = utilities;
    });

    for (const  province of this.utilities.Provinces) {
      this.provinces.push(province);
    }
  }

  getSelectedProvinces() {
      this.selectedProvinces = [];
      this.utilities.Provinces.forEach((_province, i) => {
          if (_province.value) {
          this.selectedProvinces.push(this.provinces[i]);
      }
  });
 console.log(this.selectedProvinces);
}

}

In my utilities.ts I have the following:

export interface Utilities {
  Provinces: Array<string>;
}

My service is written as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Utilities } from '../models/utilities';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UtilitiesService {

constructor(private http: HttpClient) {}

public getJSON(): Observable<Utilities> {
   return this.http.get<Utilities>('./assets/utilities.json');
}

}

The Json that is has the following content:

{
   "Provinces":["East","North West","North"]
}

When I try that, I have the following error:

TypeError: Cannot read property 'Provinces' of undefined.

The thing is, when I remove [formControl]= "province" (change)="getSelectedProvinces()", at least I am able to display the provinces on my page.

How can I go about this?




Select and plot lists through checkbuttons (python, tkinter)

Say I got a multidimensional list:

my_list = [[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]]

Now I want to create a GUI with Tkinter where one could check boxes to select which of these sub-lists should be plotted in a histogram. So for this example I imagine three checkboxes (labeled 0, 1, 2) and a Button "Show Histograms". Say I check boxes labeled 1 and 2 and press the "Show Histograms" Button, it should show the histograms of my_list[0]and my_list[1](preferably as subplots on one canvas). What would be the approach?




Why doesn't the gridview persist the checkbox values between pagination?

I am trying to store the checboxes values between paginations so if i go from 1 page to another and ocme back the the checkbox checked would persist.

Protected Sub gv_InforWO_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
       Try
            gv_InforWO.PageIndex = e.NewPageIndex

            If chkFiltersAvailable.Checked = False Then
                chkSelectAll.Checked = False
                BindGridInfoWO()
                'btnSync_Click(Nothing, Nothing)
            Else

                BindGridInfoWO()
                ' btnSync_Click(Nothing, Nothing)
            End If

            'checkbox persistence code
            Dim d As Integer = gv_InforWO.PageCount
            Dim values() As Boolean = New Boolean((gv_InforWO.PageSize) - 1) {}
            Dim chb As CheckBox
            Dim count As Integer = 0
            Dim i As Integer = 0
            Do While (i < gv_InforWO.Rows.Count)
                chb = CType(gv_InforWO.Rows(i).FindControl("chkSelect"), CheckBox)
                If (Not (chb) Is Nothing) Then
                    values(i) = chb.Checked
                End If

                i = (i + 1)
            Loop

            Session(("page" + CType(gv_InforWO.PageIndex, String))) = values


        Catch ex As Exception
             lblWaitingMsg.Text= ex.Message 
        End Try
    End Sub

On pre-render

Protected Sub gv_InforWO_PreRender(sender As Object, e As EventArgs)
        Try
            If (Not (Session(("page" + CType(gv_InforWO.PageIndex, String)))) Is Nothing) Then
                Dim chb As CheckBox
                Dim values() As Boolean = CType(Session(("page" + CType(gv_InforWO.PageIndex, String))), Boolean())
                Dim i As Integer = 0
                Do While (i < gv_InforWO.Rows.Count)
                    chb = CType(gv_InforWO.Rows(i).FindControl("chkSelect"), CheckBox)
                    chb.Checked = values(i)
                    i = (i + 1)
                Loop

            End If
        Catch ex As Exception

        End Try
       
    End Sub

but it doesn't persist the value and comes as false even if I tick the boxes.




How can i get the select all / deselect all in this table in react js for a table with checkbox as last row

Normal table with columns and code for the checkbox column as below: { title: 'Action', dataIndex: 'action', render: (text, record) => { return ( <Checkbox onClick={(event) => { let checked = event.target.checked; if(checked) this.onSetSelectedrecords(record)} }>    ) } }




Making an area un-editable using a checkbox

I have a word-document and want to make a specific area uneditable (greyed out) if the value of a checkbox is true. My problem is that there are some errors, which I am unable to fix it by myself, hopefully you can help me out with it.

Sub checkBoxStatus()

'declare variables
Dim cb3Y As CheckBox
Dim cb3N As CheckBox

Set cb3Y = ActiveDocument.FormFields(1).CheckBox

cb3Y.Value = False 'just needed this for debugging, to see if I got the right checkbox

End Sub

I got an error message all the time when running this code fragment. "Runtime Error '5941' The Requested Member of Collection Does Not Exist". Unfortunately I don't know where I can edit the id of the right checkbox I need.




lundi 22 juin 2020

Excel VBA Checkboxes - Need to Export Values to Spreadsheet

I'm a newbie teaching myself VBA and I have some basic code that I'm using. I've got the basics of everything except the checkboxes. I've tried different things but I keep running into issues. All I want is for the user to check one or both checkboxes and for the results to appear in a new line. Below is the code and the image that shows the interface (userform).

example Userform (Interface)

Private Sub CheckBox1_Click()
    'To select check box.
   CheckBox1.Value = True
    
    'To select check box.
    CheckBox1.Value = False
End Sub

Private Sub CheckBox2_Click()
    'To select check box.
    CheckBox2.Value = True
    
    'To select check box.
    CheckBox2.Value = False
End Sub

Private Sub cboClass_DropButtonClick()
    'Populate control.
    Me.cboClass.AddItem "Amphibian"
    Me.cboClass.AddItem "Bird"
    Me.cboClass.AddItem "Fish"
    Me.cboClass.AddItem "Mammal"
    Me.cboClass.AddItem "Reptile"
    
End Sub


Private Sub cboConservationStatus_DropButtonClick()
    'Populate control.
    Me.cboConservationStatus.AddItem "Endangered"
    Me.cboConservationStatus.AddItem "Extirpated"
    Me.cboConservationStatus.AddItem "Historic"
    Me.cboConservationStatus.AddItem "Special concern"
    Me.cboConservationStatus.AddItem "Stable"
    Me.cboConservationStatus.AddItem "Threatened"
    Me.cboConservationStatus.AddItem "WAP"

End Sub

Private Sub cboSex_DropButtonClick()
    'Populate control.
    Me.cboSex.AddItem "Female"
    Me.cboSex.AddItem "Male"
End Sub

Private Sub cmdAdd_Click()
    'Copy input values to sheet.
    Dim lRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("Animals")
    lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    With ws
        .Cells(lRow, 1).Value = Me.cboClass.Value
        .Cells(lRow, 2).Value = Me.txtName.Value
        .Cells(lRow, 3).Value = Me.txtTagNumber.Value
        .Cells(lRow, 4).Value = Me.txtSpecies.Value
        .Cells(lRow, 5).Value = Me.cboSex.Value
        .Cells(lRow, 6).Value = Me.cboConservationStatus.Value
        .Cells(lRow, 7).Value = Me.txtComment.Value
        .Cells(lRow, 8).Value = Me.CheckBox1.Value
        .Cells(lRow, 9).Value = Me.CheckBox2.Value
        
    End With
    
    'Clear input controls.
    Me.cboClass.Value = ""
    Me.txtName.Value = ""
    Me.txtTagNumber.Value = ""
    Me.txtSpecies.Value = ""
    Me.cboSex.Value = ""
    Me.cboConservationStatus.Value = ""
    Me.txtComment.Value = ""
    Me.CheckBox1.Value = ""
    Me.CheckBox2.Value = ""
        
End Sub

Private Sub cmdClose_Click()
    'Close UserForm.
    Unload Me
    
End Sub

Private Sub UserForm_Click()

End Sub



Checkbox limitation in PHP table while loop not working

I have this scrip, and i want to check only two checkbox. But not working, and I don't know why.

(Sorry my english, this is not my first languages :( )

This is the php code, with the while loop table creation.

 <?php
include "connection.php";
$sql = "SELECT * FROM $tablename";
if($result = mysqli_query($mysqli, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo "<table>";
            echo "<tr>";
                echo "<th>nev</th>";
                echo "<th>hely</th>";
                echo "<th>size</th>";
                echo "<th>valasztas</th>";
            echo "</tr>";          
        while($row = mysqli_fetch_array($result)){
            echo "<tr>";
                echo "<td>" . $row['nev'] . "</td>";
                echo "<td>" . $row['hely'] . "</td>";
                echo "<td>" . $row['size'] . "</td>";
                echo "<td><input type='checkbox' class='single-checkbox' name='checkbox[]' /></td>";
            echo "</tr>";
        }
        echo "</table>";
        // Free result set
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
  
mysqli_close($mysqli);
?>

And this is the code whit the jquery script.

<script type="text/javascript">
$(document).ready(function(){
  $('.single-checkbox').on('change', function(evt) {
     if ($('input[type="checkbox"]:checked').length >= 2)  {
      this.checked = false;
    };
  });
});
 </script>



Very long checklist box with tkinter

I'm using the code from this answer to make a list with checkboxes.

import tkinter as tk

root = tk.Tk()

class ChecklistBox(tk.Frame):
    def __init__(self, parent, choices, **kwargs):
        tk.Frame.__init__(self, parent, **kwargs)
        
        self.vars = []
        bg = self.cget("background")
        for choice in choices:
            var = tk.StringVar(value=choice)
            self.vars.append(var)
            cb = tk.Checkbutton(self, var=var, text=choice,
                                onvalue=choice, offvalue="",
                                anchor="w", width=20, background=bg,
                                relief="flat", highlightthickness=0
            )
            cb.pack(side="top", fill="x", anchor="w")
    
    
    def getCheckedItems(self):
        values = []
        for var in self.vars:
            value =  var.get()
            if value:
                values.append(value)
        return values

choices = [str(e) for e in range(100)]
checklist = ChecklistBox(root, choices, bd=1, relief="sunken", background="white")
checklist.pack()

Since the list of choices is very long, I would like to add a scrollbar to this list. What is the best way to do this ?


I tried to follow the example here, but ChecklistBox doesn't have a yview method, and has no yscrollcommand option. I don't know how to circumvent this problem.




VBA to show/hide data in Word

I am writing a huge procedural manual and would love to be able to hide/show sections as needed. I found the correct way to do it, through bookmarks, check boxes and VBA but am unable to get all three to come together.

These are the instructions I am using, which seem simple enough but I am unable to "view code" by right clicking on the checkbox. Is this a necessary step to add the code or can I just open a new macro and insert the code there?

Other ideas to achieve hiding/showing sections with bookmarks are welcome, too. Thank you!




Getting just true values returning from the checkbox Laravel livewire

Please Help i have in my database table questions and i have two attributes options[] and correct_answers[] So, I want to store just the correct answers not all in the database because if i check an option and then i unchecked , it store in database also the false answers picture in database

this is my code :

  <div>
        @foreach($options as $index => $option)
            <div class="flex items-center mb-2" wire:key="-option">
                    <input wire:model="answers." name="answers." id="answers" 
                    value="answers." type="checkbox">
                      <input type="text" wire:model="options."
                    class="w-full px-3 py-2 border rounded bg-white flex-1 mr-2"
                    placeholder="Option ()">
            </div>
            @error('options') <span style="color:red"class="error"></span> @enderror

        @endforeach
    </div>
 <div wire:key="submit-button">
        <button class="btn btn-success btn-lg">Create</button>
    </div>


 public function create()
{
    $this->validate([
        'question' => ['required', 'string', 'min:4', 'max:190'],
        'options' => ['required', 'array'],
        'options.*' => ['required', 'string'],
        'answers' => 'required' ,
        'type'=>'required',
        'titre'=>['required', 'string', 'min:4', 'max:190'],
    ]);


    $this->order=\App\Questions::where('exam_id',$this->exam->id)->count();
    $question=new Questions();
    $question->exam_id = $this->exam->id;
    $question->title = $this->titre;
    $question->question =$this->question; 
    $question->number_of_options = count($this->options); 
    $question->order = $this->order; 
    $question->response_type = $this->type; 
    $question->options =json_encode($this->options, JSON_UNESCAPED_UNICODE);
    $question->correct_answers =json_encode($this->answers, JSON_UNESCAPED_UNICODE);
    $question->save();

    $this->resetQuestion();
    $this->mount($this->exam);
    session()->flash('message', 'Ajout effectué avec succés.');
     $this->emit('closeModal');
    }



mat-checkbox restore SelectionModel using HttpClient Observable

I want to restore the mat-checkbox selection using http Observable stream. The selection is not reflected on the page.

Below is the structure of the code. A mat-table with first column containing the checkbox column.

html

-- Checkbox is first column of mat-table
<table mat-table [dataSource]="fixture.dataSource"
 <!-- Checkbox Column -->
  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef></th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? fixture.selectionModel1.toggle(row) : null"
                    [checked]="fixture.selectionModel.isSelected(row)"
                    [disabled]="fixture.selectionModel.selected.length >3 && !fixture.selectionModel1.isSelected(row)">
      </mat-checkbox>
    </td>
  </ng-container>

component.ts

this.fixture.dataSource = this.route.snapshot.data['fixtureresolver']
//structure of fixture object
fixture ={
    dataSource = [some data]
    selectionModel = new SelectionModel<Player>(true, [])
}

e.g. I have saved checkbox selection in monogdb from where I will retrieve the row identifier using httpclient, however just for sake of testing, i am first simply trying to select all the checkboxes by passing the row from the dataSource into the SelectionModel.select(row) function.


fixture.selectionModel.clear()
fixture.dataSource.subscribe(ds1=>{

 ds1.forEach(row => {
 fixture.selectionModel.select(row)
 });
})
this.cdr.detectChanges()

Here is how selectionModel object looks on page load. It shows that _selected has 23 rows, but does reflect on the UI. However the [disabled] constraint is working as all checkboxes are in disabled state

selectionModel

selection html




Why don't work Gravity center for Check Box

I have a checkBox and set gravity center but the box doesn't come center

this is my XML file

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="8dp"
    android:gravity="center"
    android:checked="false"
    android:clickable="false"
    app:buttonTint="@color/colorPrimary"
    android:scaleX="1.4"
    android:scaleY="1.4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

CheckBox image here




React Checkbox Form State is Delayed

I have a form I am mapping a list of checkbox inputs to using React. The mapping function receives a list of JSON objects and maps them to inputs as follows:

const listCustomBenefits = props.customBenefits.map(benefit => {
    return(
        <div className="flex">
            <input onChange={props.handleCustomBenefitsChange} id={benefit.id} key={benefit.id} 
               className="my-auto" type="checkbox" checked={benefit.included}></input>
            <p className="my-auto px-2">{benefit.benefit}</p>
        </div>
        )
})

props.customBenefit is formatted as followed:

const customBenefit = useState([{benefit: "first benefit description",
id: 1,
included: false,
name: "First Benefit"},
{benefit: "second benefit description",
id: 2,
included: false,
name: "Second Benefit"}])

listCustomBenefits is then returned in the component's return JSX. When a checkbox is clicked, handleCustomBenefitsChange updates the state of custom benefits as follows:

const handleCustomBenefitsChange = (event) =>{
    event.preventDefault()
    const newCustomBenefits = customBenefits.map(benefit =>{
        if(benefit.id == event.target.id){
            const newCheck = [event.target.checked][0]
            return({...benefit,  included: newCheck})
        }
        else{
            return benefit
        }
    })

    setCustomBenefits(newCustomBenefits)

 }

The function properly updates the state of customBenefits, but the checkbox display is always one event behind (i.e. you have to click the checkbox twice to see the desired change).

I have tried setting state with props on the local component as well (instead of using props directly) but can't seem to get the component to update on the initial click. Can anyone help me resolve this?




Filter newly selected check boxes and previous selected check boxes in adf

I am new in Oracle ADF. I have made an application in which I can filter all the selected check boxes by Code: getFilteredRows("SelectRow",true) Now, I have a requirement to get only those check boxes which are newly ticked/selected and not all of the ticked/selected. Please help Thanks in Advance




dimanche 21 juin 2020

How to prevent Checkboxes to call onChange too soon in Flutter?

Here's the code:

 Checkbox(
   value: value,
   onChanged: (newValue) {
         setState(() => value = newValue);
         
         // Restructure data based on new value
         _restructureData(newValue);
      }
   activeColor: Colors.orange,
   materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
   tristate: true,
 );

However, since tristate = true, so if you are in null position going to true you need to press twice (null => false => true). But this also means that _restructureData(newValue) is called twice.

So how do I call _restructureData(newValue) only once the user finish tapping the check box whether it is once, twice or how many times he/she wants to press it before he stops?