mardi 31 octobre 2023

Checkbox created inside php foreach loop are unable to be selected

I have created a foreach loop. Everything is displayed correctly as it should. However, the issue is that the only checkbox I can select is the first row. Clicking any other check box will also select the first checkbox from the loop. I can also select a check box outside of the loop which selects all the checkboxes inside the loop.

<?php 
$count = 0;
foreach($invoiceItems as $invoiceItem){
    $count++;
    echo '
    <tr>
        <td><div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input itemRow" id="itemRow">
        <label class="custom-control-label" for="itemRow"></label>
        </div></td>
        <td><input type="text" value="'.$invoiceItem["item_code"].'" name="productCode[]" id="productCode_'.$count.'" class="form-control" autocomplete="off"></td>
        <td><input type="text" value="'.$invoiceItem["item_name"].'" name="productName[]" id="productName_'.$count.'" class="form-control" autocomplete="off"></td>         
        <td><input type="number" value="'.$invoiceItem["order_item_quantity"].'" name="quantity[]" id="quantity_'.$count.'" class="form-control quantity" autocomplete="off"></td>
        <td><input type="number" value="'.$invoiceItem["order_item_price"].'" name="price[]" id="price_'.$count.'" class="form-control price" autocomplete="off"></td>
        <td><input type="number" value="'.$invoiceItem["order_item_final_amount"].'" name="total[]" id="total_'.$count.'" class="form-control total" autocomplete="off"></td>
    </tr>
    ';
}
?>



problème avec checkbox materiel [closed]

Comment puis-je concevoir un formulaire permettant d'attribuer un ou plusieurs identifiants de badges à une parking à partir d'une liste de badges représentée par des cases à cocher ?

<div *ngFor="let res of badges"> <mat-checkbox formControlName="efccm" [value]="res._id"></mat-checkbox> <span style="margin-left: 50px;"></span> <span style="margin-left: 50px;"></span> </div>

Le problème avec ce code, c'est qu'il affiche "true" ou "false.

Comment puis-je obtenir les identifiants des badges sélectionnés dans un formulaire au lieu de valeurs booléennes (true ou false)?

this.parkingForm = new FormGroup({ nom: new FormControl(), efccm: new FormControl([]),

})

Le problème avec ce code, c'est qu'il affiche "true" ou "false.

Comment puis-je obtenir les identifiants des badges sélectionnés dans un formulaire au lieu de valeurs booléennes (true ou false)?




How to change "-1" and "0" in checkbox field filter dialog in Spreadsheet View when it's based on a calculated field (MS Access)?

In my MS Access table I have a Calculated field that returns True or False. Then I use it in my form in Spreadsheet View as a Checkbox. The filter dialog for this field shows "-1" and "0" as filtering options. It's not friendly for the user. How to change it?

Checkbox filter dialog for a Calculated field in Spreadsheet View

I tried to use a calculated field right in the Spreadsheet Form, but filtering of Calculated Fields is not supported in Spreadsheet Forms.

Thank you for your support.




When asp.net CheckBox control is changed, how to fire client side AND server side events

I have an asp.net Checkbox inside a gridview. It has some javascript in OnClick to confirm that the operator wishes to proceed. It also has some server side code on the OnCheckedChanged event.

The client side code is being executed, but the server side code is not being triggered, irrespective of whether the operator elects to proceed or not. I have confirmed this by adding some breakpoints.

If I remove the OnClick client side code, the server side code is executed correctly.

Any suggestions on what I'm doing wrong would be very much appreciated.

Code below:

 <asp:CheckBox ID="InclSectionCB" OnClick="return ProceedYN();" OnCheckedChanged="InclSectionCBChanged" runat="server" AutoPostBack="True" />
    <script type="text/javascript">
        function ProceedYN() {
            return confirm('Proceed?');
        }
    </script>

I expected that upon checking/unchecking the checkBox that the steps would be:

  1. Client side javascript prompts the operator if they would like to proceed. 2a) If operator selects 'Ok', then Checkbox would be changed and the server side code in InclSectionCBChanged would be executed. 2b) If operator selects 'Cancel', then Checkbox would not be changed and the server side code in InclSectionCBChanged would not be executed.

What is happening is:

  1. Client side javascript prompts the operator if they would like to proceed. (correct) 2a) If operator selects 'Ok', then Checkbox is changed but the server side code in InclSectionCBChanged is not executed. 2b) If operator selects 'Cancel', then Checkbox is not changed and the server side code in InclSectionCBChanged is not executed.



lundi 30 octobre 2023

Html form returns Model with null attribute ins asp.net core

I'm currently developing an html asp.net core web app that requires a huge form. This form is basically a large treeview with selectable items inside which are not hardcoded but retrieved form a .db file.

To clarify things, the "treeView" looks like this: Treeview capture

And the html code that creates it is the following one:

<form method="post" action="/Launch/Home/retrieveSelection">
    <input type="number" name="Id" value="1234" style="display:none" />
    @*MIRAR PERQUE tvList SEMPRE ESTA A NULL*@
    <ul>
        @foreach (TVStandard tvstandard in Model.tvList.StandardsList) {
            int i = 0;
            <li>
                <span class="caret"></span>
                <input type="checkbox" class="checker" id="@tvstandard.Name" name="tvList.StandardsList[@i].IsSelected" value="true">
                <label for="@tvstandard.Name">@tvstandard.Name</label>
                <ul class="nested">
                    @foreach (TVSection tvsection in tvstandard.Children) {
                        int j = 0;
                        <li>
                            <span class="caret"></span>
                            <input type="checkbox" class="checker" id="@tvsection.Name" name="tvList.StandardsList[@i].Children[@j].IsSelected" value="true">
                            <label for="@tvsection.Name">@tvsection.Name</label>
                            <ul class="nested">
                                @foreach (TVMode tvmode in tvsection.Children) {
                                    int k = 0;
                                    <li>
                                        <span class="caret"></span>
                                        <input type="checkbox" class="checker" id="@tvmode.Name" name="tvList.StandardsList[@i].Children[@j].Children[@k].IsSelected" value="true">
                                        <label for="@tvmode.Name">@tvmode.Name</label>
                                        <ul class="nested">
                                            @foreach (TVFreq tvfreq in tvmode.Children) {
                                                int l = 0;
                                                <li>
                                                    <ul class="nested" style="display:block">
                                                        <input type="checkbox" class="checker" id="@tvfreq.Name" name="tvList.StandardsList[@i].Children[@j].Children[@k].Children[@l].IsSelected" value="true">
                                                        <label for="@tvfreq.Name">@tvfreq.Name</label>
                                                    </ul>
                                                </li>
                                                l++;
                                            }
                                        </ul>
                                    </li>
                                    k++;
                                }
                            </ul>
                        </li>
                        j++;
                    }
                </ul>
            </li>
            i++;
        }
    </ul>
    <br />
    <input type="submit" />
</form>

Warning: I've only shown the form itself, the page also has its css and javascript to make the treeview work as I like to.

Also, here it is the Model:

public class MeasureModel
{

    public int Id { get; set; }
    public TVList? tvList { get; set; }
}

Also, it is worth mentioning that this list is made of classes that themselves contain more classes. All of them inherit from:

public class TVItem
{
    public string Name;
    public TVItem Parent;
    public List<TVItem> Children;
    public bool IsSelected = false;

    public TVItem()
    {
        Children = new List<TVItem>();
    }

    public TVItem(string name, TVItem parent)
    {
        Children = new List<TVItem>();
        this.Name = name;
        this.Parent = parent;
    }
    public TVItem(TVItem item)
    {
        this.Children = new();
        Name = item.Name;
        Parent = item.Parent;
        IsSelected = item.IsSelected;
    }
}

Finally, as you may see the model that I use to create this treeview is already initialized with its values and the only thing that I want is to SELECT or UNSELECT them, nothing else. I assumed that the model submitted by the form would be the same than the one used to build the form itself.

So my questions are:

  1. Is the submitted form the same as the page one?
  2. In case 1 is false, do I need to fill every attribute of it in order to make the tvList not NULL?
  3. Which are the ways to do it? (I find using the hidden attribute very ugly but if it is the way I don't ming using it)

Thanks for your help in advance.




samedi 28 octobre 2023

How to select all checkboxes in a Flutter PopupMenu when selecting one checkbox?

A similar question has been asked before for Flutter see question. However no valid answer was given, so it may be worth reopening.

Here is a complete code example.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

const cities = <String>{
  'Atlanta',
  'Baltimore',
  'Boston',
  'Chicago',
  'Denver',
  'Houston',
  'Los Angeles',
  'Philadelphia',
  'San Francisco',
  'Washington, DC',
};

enum SelectionState {
  all('(All)'),
  none('(None)'),
  some('(Some)');

  const SelectionState(this._value);
  final String _value;

  @override
  String toString() => _value;
}

class SelectionModel {
  SelectionModel({required this.selection, required this.choices});

  late final Set<String> selection;
  final Set<String> choices;

  SelectionState get selectionState {
    if (selection.isEmpty) return SelectionState.none;
    if (choices.difference(selection).isNotEmpty) {
      return SelectionState.some;
    } else {
      return SelectionState.all;
    }
  }

  SelectionModel add(String value) {
    if (value == '(All)') {
      return SelectionModel(selection: {...choices}, choices: choices);
    } else {
      return SelectionModel(selection: selection..add(value), choices: choices);
    }
  }

  SelectionModel remove(String value) {
    if (value == '(All)') {
      return SelectionModel(selection: <String>{}, choices: choices);
    } else {
      selection.remove(value);
      return SelectionModel(selection: selection, choices: choices);
    }
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dropdown with Select (All)',
      theme: ThemeData(
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  SelectionModel model =
      SelectionModel(selection: {...cities}, choices: {...cities});

  List<PopupMenuItem<String>> getCheckboxList() {
    var out = <PopupMenuItem<String>>[];
    out.add(PopupMenuItem<String>(
        padding: EdgeInsets.zero,
        value: '(All)',
        child: StatefulBuilder(builder: (context, setState) {
          return CheckboxListTile(
            value: model.selectionState == SelectionState.all,
            controlAffinity: ListTileControlAffinity.leading,
            title: const Text('(All)'),
            onChanged: (bool? checked) {
              setState(() {
                if (checked!) {
                  model = model.add('(All)');
                } else {
                  model = model.remove('(All)');
                }
              });
            },
          );
        })));

    for (final value in model.choices) {
      out.add(PopupMenuItem<String>(
          padding: EdgeInsets.zero,
          value: value,
          child: StatefulBuilder(builder: (context, setState) {
            return CheckboxListTile(
              value: model.selection.contains(value),
              controlAffinity: ListTileControlAffinity.leading,
              title: Text(value),
              onChanged: (bool? checked) {
                setState(() {
                  if (checked!) {
                    model = model.add(value);
                  } else {
                    model = model.remove(value);
                  }
                });
              },
            );
          })));
    }
    return out;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Container(
                width: 250,
                color: Colors.orangeAccent,
                child: PopupMenuButton<String>(
                  constraints: const BoxConstraints(maxHeight: 400),
                  position: PopupMenuPosition.under,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Text(model.selectionState.toString()),
                        const Spacer(),
                        const Icon(Icons.keyboard_arrow_down_outlined),
                      ],
                    ),
                  ),
                  itemBuilder: (context) {
                    return getCheckboxList();
                  },
                  onCanceled: () {
                    setState(() {
                      model = SelectionModel(
                          selection: model.selection, choices: model.choices);
                    });
                  },
                ),
              ),
            ),
            const Spacer(),
            Text('Selected cities: ${model.selection.join(', ')}'),
          ],
        ),
      ),
    );
  }
}

See screeenshot. base1

If I click individual cities, everything is fine. If I click the (All) checkbox, I would like all the checkboxes to turn false (which does not happen unless I close the menu.)

How can I do this? If I just have a list of CheckboxListTiles in the main app, the logic works fine, and the checkboxes update as I want. However, once they are part of the menu, it doesn't work properly anymore.

Thank you for any help with this! Tony




Checkbox required in form. React using EmailJS

I have a React project where I am using EmailJS, and I need the checkbox to be required before sending the form, or register the value of the checkbox in the email template. It's value is currently not being registered.

This is some of the code:

const ApplyForm = (props) => {
  const [formData, setFormData] = useState({
    student_name: "",
    adress: "",
    postnr: "",
    city: "",
    birthday: "",
    otherschool: "",
    startdate: "",
    firstgrade: "",
    secondgrade: "",
    thirdgrade: "",
    fourthgrade: "",
    fifthgrade: "",
    sixthgrade: "",
    seventhgrade: "",
    mom_name: "",
    mom_adress: "",
    mom_postnr: "",
    mom_city: "",
    mom_phone: "",
    mom_email: "",
    children_age: "",
    other: "",
    why: "",
  });

  const [formError, setFormError] = useState();
  const [formSuccess, setFormSuccess] = useState();

  function validateEmail(email) {
    const regEX = /\S+@\S+\.\S+/;
    const patternMatches = regEX.test(email);
    return patternMatches;
  }

  const validateForm = () => {
    if (formData.student_name.length < 3) {
      setFormError("ERROR! Navn må inneholde minst 3 karakterer");
      setTimeout(() => {
        setFormError(null);
      }, 5000);
      return false;
    } else if (!validateEmail(formData.mom_email)) {
      setFormError("ERROR! Fyll inn en gyldig e-postadresse");
      setTimeout(() => {
        setFormError(null);
      }, 5000);
      return false;
    } else if (formData.adress.length < 3) {
      setFormError("ERROR! Adressen må inneholde minst 3 karakterer");
      setTimeout(() => {
        setFormError(null);
      }, 5000);
      return false;
    } else if (formData.postnr.length < 4) {
      setFormError("ERROR! Fyll inn et gyldig postnummer");
      setTimeout(() => {
        setFormError(null);
      }, 5000);
      return false;
    } else if (formData.city.length < 2) {
      setFormError("ERROR! Fyll inn poststed");
      setTimeout(() => {
        setFormError(null);
      }, 5000);
      return false;
    } else {
      return true;
    }
  };
  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (validateForm()) {
      send("service_loremipsum", "template_loremipsum", formData, "loremipsum")
        .then((response) => {
          console.log("SUCCESS!", response.status, response.text);
          setFormSuccess("Søknaden har blitt sendt!");
          setFormData({
            student_name: "",
            adress: "",
            postnr: "",
            city: "",
            birthday: "",
            otherschool: "",
            startdate: "",
            mom_name: "",
            mom_adress: "",
            mom_postnr: "",
            mom_city: "",
            mom_phone: "",
            mom_email: "",
            children_age: "",
            other: "",
            why: "",
            consent: "",
          });
          setTimeout(() => {
            setFormSuccess(null);
          }, 5000);
        })
        .catch((err) => {
          console.log("FAILED...", err);
        });
    }
  };

  return (
    <>
      <h1>Søk skoleplass</h1>
      <Container fluid>
        <Row className="justify-content-center align-items-center">
          <Col md={6}>
            <h2 className="form_h2">Opplysninger om eleven</h2>
            {formError && <p className="setFormError">{formError}</p>}
            {formSuccess && <p className="setFormSuccess">{formSuccess}</p>}
            <form className="apply_form" onSubmit={onSubmit}>
              <fieldset>
                <label htmlFor="student_name" id="student_name">
                  Fullt navn
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="student_name"
                  name="student_name"
                  value={formData.student_name}
                  onChange={handleChange}
                />
                <label htmlFor="adress" id="adress">
                  Adresse
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="adress"
                  name="adress"
                  value={formData.adress}
                  onChange={handleChange}
                />
                <div className="post_group">
                  <label htmlFor="postnr" id="postnr">
                    Postnummer
                  </label>
                  <input
                    className="apply_input"
                    type="text"
                    id="postnr"
                    name="postnr"
                    value={formData.postnr}
                    onChange={handleChange}
                  />{" "}
                </div>
                <div className="post_group">
                  <label htmlFor="city" id="city">
                    Poststed
                  </label>
                  <input
                    className="apply_input"
                    type="text"
                    id="city"
                    name="city"
                    value={formData.city}
                    onChange={handleChange}
                  />
                </div>
                <label htmlFor="birthday" id="birthday">
                  Fødselsdag
                </label>
                <input
                  className="apply_input"
                  type="date"
                  id="birthday"
                  name="birthday"
                  value={formData.birthday}
                  onChange={handleChange}
                />
                <label htmlFor="otherschool" id="otherschool">
                  Skal barnet meldes ut av en annen skole? Hvilken?
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="otherschool"
                  name="otherschool"
                  value={formData.otherschool}
                  onChange={handleChange}
                />
                <label htmlFor="startdate" id="startdate">
                  Dato for ønsket oppstart
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="startdate"
                  name="startdate"
                  value={formData.startdate}
                  onChange={handleChange}
                />
                <label className="class_section">Søker til klassetrinn:</label>
                <section className="grade">
                  {" "}
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="firstgrade"
                      name="firstgrade"
                      value={formData.firstgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="firstgrade"
                      id="firstgrade"
                    >
                      1. klasse
                    </label>
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="secondgrade"
                      name="secondgrade"
                      value={formData.secondgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="secondgrade"
                      id="secondgrade"
                    >
                      2. klasse
                    </label>
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="thirdgrade"
                      name="thirdgrade"
                      value={formData.thirdgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="thirdgrade"
                      id="thirdgrade"
                    >
                      3. klasse
                    </label>
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="fourthgrade"
                      name="fourthgrade"
                      value={formData.fourthgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="fourthgrade"
                      id="fourthgrade"
                    >
                      4. klasse
                    </label>{" "}
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="fifthgrade"
                      name="fifthgrade"
                      value={formData.fifthgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="fifthgrade"
                      id="fifthgrade"
                    >
                      5. klasse
                    </label>
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="sixthgrade"
                      name="sixthgrade"
                      value={formData.sixthgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="sixthgrade"
                      id="sixthgrade"
                    >
                      6. klasse
                    </label>{" "}
                  </section>
                  <section className="class">
                    {" "}
                    <input
                      type="checkbox"
                      id="seventhgrade"
                      name="seventhgrade"
                      value={formData.seventhgrade}
                      onChange={handleChange}
                    />
                    <label
                      className="inline_label"
                      htmlFor="seventhgrade"
                      id="seventhgrade"
                    >
                      7. klasse
                    </label>
                  </section>
                </section>
                <h2 className="form_h2">Opplysninger om foresatte - mor</h2>
                <label htmlFor="mom_name" id="mom_name">
                  Fullt navn
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="mom_name"
                  name="mom_name"
                  value={formData.mom_name}
                  onChange={handleChange}
                />
                <label htmlFor="mom_adress" id="mom_adress">
                  Evt annen adresse
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="mom_adress"
                  name="mom_adress"
                  value={formData.mom_adress}
                  onChange={handleChange}
                />
                <div className="post_group">
                  <label htmlFor="mom_postnr" id="mom_postnr">
                    Postnummer
                  </label>
                  <input
                    className="apply_input"
                    type="text"
                    id="mom_postnr"
                    name="mom_postnr"
                    value={formData.mom_postnr}
                    onChange={handleChange}
                  />{" "}
                </div>
                <div className="post_group">
                  <label htmlFor="mom_city" id="mom_city">
                    Poststed
                  </label>
                  <input
                    className="apply_input"
                    type="text"
                    id="mom_city"
                    name="mom_city"
                    value={formData.mom_city}
                    onChange={handleChange}
                  />
                </div>
                <label htmlFor="mom_phone" id="mom_phone">
                  Telefon
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="mom_phone"
                  name="mom_phone"
                  value={formData.mom_phone}
                  onChange={handleChange}
                />
                <label htmlFor="mom_email" id="mom_email">
                  Epost
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="mom_email"
                  name="mom_email"
                  value={formData.mom_email}
                  onChange={handleChange}
                />
                <h2 className="form_h2">Andre opplysninger</h2>
                <label htmlFor="children_age" id="children_age">
                  Alder på andre barn i familien
                </label>
                <input
                  className="apply_input"
                  type="text"
                  id="children_age"
                  name="children_age"
                  value={formData.children_age}
                  onChange={handleChange}
                />
                <label htmlFor="other" id="other">
                  Andre opplysninger som er relevante for søknaden:
                </label>
                <textarea
                  className="apply_textarea"
                  id="other"
                  name="other"
                  value={formData.other}
                  onChange={handleChange}
                />
                <label htmlFor="why" id="why">
                  Hvorfor ønsker dere plass hos oss?{" "}
                </label>
                <textarea
                  className="apply_textarea"
                  id="why"
                  name="why"
                  value={formData.why}
                  onChange={handleChange}
                />{" "}
                <legend>Samtykke</legend>
                <section className="class">
                  <input
                    className="checkbox"
                    type="checkbox"
                    id="consent"
                    name="consent"
                    value={formData.consent}
                    onChange={handleChange}
                  />
                  <label className="inline_consent">
                    lorem ipsum
                  </label>
                </section>
                <button
                  className="apply_btn"
                  type="submit"
                  id="button"
                  value="Submit"
                >
                  Send søknad
                </button>
              </fieldset>
            </form>
            {formError && <p className="setFormError">{formError}</p>}
            {formSuccess && <p className="setFormSuccess">{formSuccess}</p>}
          </Col>
        </Row>
      </Container>
    </>
  );
};

Do I need to set a State for the checkbox or is it another way to register the value? The value is not being registered so the output doesn't show up in the Emailjs template, even tho I used the id.




Room Database Update a column (CHeckbox)

I recently started programming apps and don't have that much experience yet. Especially not with database programming.

I have a shoppinglist and want to check items.

I still can't manage to update the column. I found a few things on the internet but can't put it all together. For example, I don't know how to get the id from the item. Or do I need the ID at all?

I ask for help. Thanks!

Entity:

@Entity
data class ShoppingList(
    val Name: String,
    val Einheit: String,
    val Menge: String,
    @ColumnInfo(name = "isChecked", defaultValue = "0")
    val isChecked: Boolean,
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0

Dao:

@Dao
interface ShoppingListDao {

    @Upsert
    suspend fun upsertItem(items: ShoppingList)

    @Query("UPDATE ShoppingList SET isChecked = :isChecked WHERE id = :id")
    suspend fun updateItem(isChecked: Boolean, id: Int)

    @Delete
    suspend fun deleteItem(items: ShoppingList)

    @Query("SELECT * FROM ShoppingList ORDER BY Name ASC")
    fun getItemsOrderByName(): Flow<List<ShoppingList>>

}

Event:

sealed interface ShoppingListEvent{
    object SaveItem: ShoppingListEvent
    data class SetName(val Name: String): ShoppingListEvent
    data class SetEinheit(val Einheit: String): ShoppingListEvent
    data class SetMenge(val Menge: String): ShoppingListEvent
    data class SetCheckbox(val isChecked: Boolean): ShoppingListEvent
    object ShowDialog: ShoppingListEvent
    object HideDialog: ShoppingListEvent
    data class SortItems(val sortType: SortType): ShoppingListEvent
    data class DeleteItem(val items: ShoppingList): ShoppingListEvent
}

State:

data class ShoppingListState (
    val items: List<ShoppingList> = emptyList(),
    val Name: String = "",
    val Einheit: String = "",
    val Menge: String = "",
    val isChecked: Boolean = false,
    val isAddingItem: Boolean = false,
    val sortType: SortType = SortType.Name
)

Viewmodel:

class ShoppingListViewModel(
    private val  dao: ShoppingListDao
): ViewModel() {

    private val _sortType = MutableStateFlow(SortType.Name)
    private val _items = _sortType
        .flatMapLatest { sortType ->
            when(sortType) {
                SortType.Name -> dao.getItemsOrderByName()
            }
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())

    private val _state = MutableStateFlow(ShoppingListState())
    val state = combine(_state, _sortType, _items) { state, sortType, items ->
        state.copy(
            items = items,
            sortType = sortType
        )
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), ShoppingListState())


    fun onEvent(event: ShoppingListEvent){
        when(event){

            ....

            is ShoppingListEvent.SetCheckbox -> {
                
                //I don't know what to do here. 
                
                val isChecked = state.value.isChecked

                viewModelScope.launch {
                    dao.updateItem(isChecked)
                }

            ...

            }

            
        }
    }
}

And the Checkbox:

Checkbox(
    checked = state.isChecked,
    onCheckedChange ={
          onEvent(ShoppingListEvent.SetCheckbox(it))
    }
)

I tried a few things. Sometimes nothing happens and sometimes all Items got checked.




jeudi 26 octobre 2023

Angular filter selection of Grid data by checkmarks

I am programming a page in PowerSchool using Angular that displays a set of grid data, and a button that selects all of the grid data within the page. The button successfully selects all of the data on the page, but what I want it to do is to select only those students who have a checkmark checked.

The JS file looks like this:

define(['angular', 'components/shared/index'], function (angularjs) {

    // create the angular app and include this module and the powerschool module
    var at2App = angularjs.module('at2App', ['powerSchoolModule']);

// create a service to hold values that are used across multiple controllers, directives, and other services.
    at2App.factory('myService', function() {
        return {
            ctrlData: {},
            selectedMonth: undefined,
            id: 0,
            dcid: 0,
            spinner: {wait: true},
            gwScope: undefined
        };
    });
    // creates the controller for the bug_birthday_simple.html page
    at2App.controller('at2Controller', function($scope, $http, myService) {

        // initial values of variable used in this controller

        $scope.gridData = [];
        $scope.dialog = {};
        $scope.spinner = myService.spinner;
        $scope.makeCurrentSelection = function() {
            
            myService.spinner.wait = true;
            var studentList = "0";
            $scope.gridData.forEach(function(row){
                studentList = studentList + "," + row.dcid;
            });
            
            var url = """"
            var payload = """"
            $http.post(url, $j.param(payload), {headers: {'Content-Type':'application/x-www-form-urlencoded'}}).then(function(){
                myService.spinner.wait = false;

            });
      $scope.toggleCheck = function(tof) {
          console.log($scope.gridDataFilter); 
            $scope.gridDataFilter.forEach(function(row){
                row.isselected = tof;
            });
        };  

    
        };
        // get the data from the JSON source file
        $http.get('attendance_letters2.json').then( function (response) {
            
            // the response should include a 'data' array
            var gridData = response.data;
            
            // remove the empty row at the end of the array
            gridData.pop();
            
            // convert birthdates from text strings to javascript dates for each row
            gridData.forEach(row => row.dob = new Date(row.dob));

            // put the grid data into the $scope variable which is bound to the grid widget
            $scope.gridData = gridData;

        });
    
    });

});

My html page has this within its grid table which connects it to the JS script:

    <table class="grid">
                <thead>
                    <tr>
<th><input type="checkbox" ng-click="toggleCheck(toggle)" ng-model="toggle"></th>
                <th data-pss-sort-fields="DCID">DCID</th>
                    <th data-pss-sort-fields="Student_number">Student Number</th>
                        <th data-pss-sort-fields="last_name">Last Name</th>
                        <th data-pss-sort-fields="first_name">First Name</th>
                        <th data-pss-sort-fields="latest_truancy_count">Latest Truancy Count</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="item in gridDataFiltered">
                         <td><center><input type="checkbox" ng-model="item.checkbox"></center></td>
                        <td></td>
                       <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <!-- end of PS Grid Widget --> 
    </div>

Th HTML page should be filtering based on the toggleCheck function shouldn't it? Any help on this would be greatly appreciated.




how to display checkbox data and delete sql row after unchecking it? [closed]

I have 2 tables and would like to know how to: 1)display using checkbox by product_id with it checked if there color_id is in the product_attributes table 2)delete the relative row in product_attributes table after I uncheck the box and submit the form

table 1: product_attributes

id product_id color_id
1 2 1
2 2 3

table 2: color_master

id color status
1 Red 1
2 Green 1
3 Blue 1

enter image description here

I tried setting all color check box input with name="color_id[]", also added the hidden input when displaying the colors that are in table 1

<input type="hidden" name="attr_id[]" value='<?php echo $list['id']?>'/>

and then if(isset($_POST['submit'])), I tried

if(isset($_POST['color_id'])){
foreach($_POST['color_id'] as $val){
 $color_id=get_safe_value($con,$_POST['color_id'][$key]);
 $attr_id=get_safe_value($con,$_POST['attr_id'][$key]);
                
if($attr_id>0){
mysqli_query($con,"DELETE from product_attributes WHERE product_id='$id' AND color_id NOT IN('$color_id')");
}else{
mysqli_query($con,"insert into product_attributes(product_id,color_id) values('$id','$color_id')");
}
                
}
} ```



mercredi 25 octobre 2023

Using checkbox to determine next step in flutter app

I am using a checkbox to determine if a new user will be associated to an existing company or if they will need to add a company to be associated with.

This is the checkbox code:

Checkbox(
                  value: _chkbxValue,
                  onChanged: (bool? value) {
                    setState(() {
                      ref
                          .read(globalsNotifierProvider.notifier)
                          .updateAddCompany(value!);
                    });
                  },
                ),

In the onChanged: I set a global notifierprovider to the state of the checkbox which would be "true".

However, when I get down to the navigation code, the notifierprovider is back to "false" but I don't have any code that changes the notifierprovider.

Here is the navigation code. This code only gets executed when the "Save" button is pressed:

if (ref.read(globalsNotifierProvider).addCompany!) {
                        ref
                            .read(globalsNotifierProvider.notifier)
                            .updateAddCompany(false);
                        Navigator.of(context).pushReplacement(MaterialPageRoute(
                            builder: (context) => const CompanyScreen()));
                      } else {
                        Navigator.of(context).pushReplacement(MaterialPageRoute(
                            builder: (context) => MainScreen()));
                      }

I am thinking I am not understanding the execution flow of the code. This code is all in a ConsumerStatefulWidget class.

When I press the "Save" button some how the value of the notifierprovider gets changed to "false". How can I do this the right way?

Thanks.




Checkbox Multiline Label Alignment

https://codepen.io/antonyx-6/pen/qBgdKQr

    <div class="checkbox">
        <input type="checkbox" id="cb02" value="second_checkbox"/>
        <label for="cb02" class="strikethrough">Lorem ipsum dolor sit.</label>
    </div>

I have tried various combinations from floating the checkbox to the left, to displaying the label as an inline-block. Just want the simplest and best solution to acheive the following:

enter image description here




invalid datetime format 1366 incorrect integer value symfony 1.4

so if i check that checkbox admin will be nonactive, but i need t use active admin hostenter image description here

I want to debug the issue in here symfony 1.4 here is form

<?php

/**
 * User form.
 *
 * @package    now
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class UserForm extends BaseUserForm {

    public function configure() {
        $this->disableCSRFProtection();

        unset($this['created_by'], $this['created_at'], $this['updated_at'], $this['updated_by'], $this['phone_number'], $this['position'], $this['group_id']);
        $userId=$this->getObject()->getId();
        $this->setWidgets(array(
            'id' => new sfWidgetFormInputHidden(),
            'username' => new sfWidgetFormInputText(),
            'password' => new sfWidgetFormInputPassword(),
            'again_password' => new sfWidgetFormInputPassword(),
            'firstname' => new sfWidgetFormInputText(),
            'lastname' => new sfWidgetFormInputText(),
            'mobile' => new sfWidgetFormInputText(),
            'email' => new sfWidgetFormInputText(),
            'user_groups_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'UserGroup', 'expanded' => true)),
            'status'           => new sfWidgetFormInputCheckbox(array(), array('value' => 1)),

//            'status'           => new sfWidgetFormInputCheckbox(array(), array('value' => 1)),
//            $this->widgetSchema->setDefaults(array(
//                'status' => 1,  ))
        ));


        $required_array = array('required' => true);

        $this->setValidators(array(
            'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
            'username' => new sfValidatorString($required_array, array('required' => 'Нэвтрэх нэрийг заавал оруулна уу')),
            'password' => new sfValidatorString(array('max_length' => 100, 'required' => false)),
            'again_password' => new sfValidatorString(array('required' => false)),
            'firstname' => new sfValidatorString(array('max_length' => 50, 'required' => true)),
            'lastname' => new sfValidatorString(array('max_length' => 50)),
            'mobile' => new sfValidatorString(array('max_length' => 255)),
            'email' => new sfValidatorEmail(array(), array('invalid' => 'Та имэйл хаягийг зөв оруулна уу', 'required' => 'Та имэйлийг заавал оруулна уу')),
            'user_groups_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'UserGroup', 'required' => false)),
            'status'           => new sfValidatorBoolean(array('required' => false)),
        ));
//        11f3d53bd59be0c5a1ea7e354516528c
//        5ef0c862efa8ced872fa54c4e9453276
        $this->widgetSchema->setNameFormat('user[%s]');

        $this->validatorSchema->setPostValidator(new sfValidatorAnd(array(
            new sfValidatorDoctrineUnique(array('model' => 'User', 'column' => array('username')), array('invalid' => 'Нэвтрэх нэртэй хэрэглэгч бүртгэгдсэн байна')),
            new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'again_password', array(), array('invalid' => 'Нууц үгүүд ижилхэн байх ёстой!'))
        )));

//        $this->validatorSchema->setPostValidator(
//                new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'again_password', array(), array('invalid' => 'Нууц үгүүд ижилхэн байх ёстой!'))
//        );
        $this->widgetSchema['username']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['password']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['again_password']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['firstname']->setAttributes(array('class' => 'form-control'));
//        $this->widgetSchema['status']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['lastname']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['email']->setAttributes(array('class' => 'form-control'));
        $this->widgetSchema['mobile']->setAttributes(array('class' => 'form-control'));

        $this->widgetSchema->setLabels(
            array(
                'username' => 'Нэвтрэх нэр:',
                'password' => 'Нууц үг:',
                'again_password' => 'Нууц үг давтах:',
                'firstname' => 'Өөрийн нэр:',
                'lastname' => 'Эцгийн нэр:',
                'mobile' => 'утас:',
                'email' => 'Имэйл:',
                'status' => 'Идэвхгүй болгох эсэх:',
                'user_groups_list' => 'Хандах эрх:',
            ));
    }

}

i want to know about how to fix the checkbox when i using local server i need to change my admin level and choose active checkbox but it doesn't work eventhough error was called in the status section will need datetime.




Accessibility: Pressing "space" on checkbox is not registered correctly by screen reader

We are working on upgrading our app to vue 3, but in the meantime, one of our users has problems with their screen reader which we have to fix within vue 2.

Problem: Given a vuetify checkbox, when you press space, the screen reader doesn't notice that the checkbox has been unchecked.

Here is a small code pen: https://codepen.io/jkarczm/pen/LYbYmxz?editors=1010

If you try it without a screen reader, pressing with the mouse or the space - it all looks good, but the screen reader won't pick up that the checkbox changed when you press space (it does pick up when you use the mouse). Screen readers tested and affected: Orca, JAWS, NVDA.

Analysis so far:

In that code pen, if you use the developer tools, you can go to the input element for the checkbox and remove the "role: 'checkbox'" property from the HTML. This will result in the underlying input element to be rendered also next to the icon which replaces the natural rendering. Now, if you use mouse clicks, the two checkboxes change accordingly, while if you use the space key, the native checkbox DOES NOT change its value.

I believe that the html here is actually not good: The checkbox should just have a type: "checkbox" property, all the rest is unnecessary. It seems that most modern versions of screen readers just ignore the other properties such as aria-checked and read out the value of the input and that this is CORRECT behaviour - they didn't do that in the past though, which is why the problem is biting us now.

However, that doesn't tell me why the "native" checkbox doesn't pick up the change - to me it seems that the signals are propagated to the same functions and result in the same changes in JavaScript apart from the value of the input element.

Question: Does anyone have an idea or pointers as to how I could fix it? Vuetify 3 behaves correctly in that regard, but there were a lot of changes so I can't quite put a finger on where the relevant change is coming from.




mardi 24 octobre 2023

How to break checkbox selection into multiple section with select all function on each section

I have more than 60 customer need to select using checkbox, I have done this so I can select individual 1 or more customer and also select all function to select all the customers.

Now I want to to break this customer selection into 3 parts, every part has the select all function, but I am facing problem for doing that. Here is my code :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Checkbox and Select All</title>
</head>
<body>
  <h1>Checkbox and Select All</h1>

  <div id="section-1">
    <h2>Section 1</h2>
    <input type="checkbox" id="select-all-section-1">
    <label for="select-all-section-1">Select All</label>
    <ul id="customer-codes-section-1">
     <li><input type="checkbox" name="customer-code" value="HAN01">HAN01</li>
    <li><input type="checkbox" name="customer-code" value="HAN02">HAN02</li>
    <li><input type="checkbox" name="customer-code" value="HAN03">HAN03</li>
    <li><input type="checkbox" name="customer-code" value="HAN04">HAN04</li>
    </ul>
  </div>

  <div id="section-2">
    <h2>Section 2</h2>
    <input type="checkbox" id="select-all-section-2">
    <label for="select-all-section-2">Select All</label>
    <ul id="customer-codes-section-2">
     <li><input type="checkbox" name="customer-code" value="ABC01">ABC01</li>
    <li><input type="checkbox" name="customer-code" value="ABC02">ABC02</li>
    <li><input type="checkbox" name="customer-code" value="ABC03">ABC03</li>
    <li><input type="checkbox" name="customer-code" value="ABC04">ABC04</li>    
    <li><input type="checkbox" name="customer-code" value="ABC05">ABC05</li>
    </ul>
  </div>

  <button type="button" id="submit-button">Submit</button>

    <script>
const selectAllCheckboxes = document.querySelectorAll('input[id^="select-all-section-"]');
const customerCodeCheckboxes = document.querySelectorAll('input[name^="customer-code-section-"]');
const submitButton = document.querySelector('#submit-button');

// Add a click event listener to each select all checkbox
selectAllCheckboxes.forEach(checkbox => {
  checkbox.addEventListener('click', () => {
    // Get the corresponding section element
    const sectionElement = document.querySelector(`#${checkbox.id.split('-')[2]}`);

    // Get all of the customer code checkboxes in the section
    const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('input[type="checkbox"]');

    // Select or deselect all of the customer code checkboxes in the section, depending on the state of the select all checkbox
    sectionCustomerCodeCheckboxes.forEach(checkbox => {
      checkbox.checked = selectAllCheckbox.checked;
    });
  });
});

// Add a click event listener to the submit button
submitButton.addEventListener('click', () => {
  // Get the selected customer code IDs
  const selectedCustomerCodeIds = customerCodeCheckboxes.filter(checkbox => checkbox.checked).map(checkbox => checkbox.value);

  // Log the selected customer code IDs to the console
  console.log('Selected customer code IDs:', selectedCustomerCodeIds);
});

  </script>
</body>
</html>

What am I doing wrong?

I tried many times, and it wont select all in every part. I need any suggestion please




Select the passing data types with checkbook

How to select the passing data with checkbook types would you like to enter image description hereallow in this app?

How to select online or offline the passing data types would you like to allow in this app?I want to know how we to select the passing data types would you like to allow in Android application




lundi 23 octobre 2023

Javascript Firefox checkbox issue

I have a web application that accesses a database to return a list of filenames for the user to select for download.

It used to be that this was just a confirmation of the files (and number/size of files) that would be downloaded based on the users filters. The users requested that this list have checkboxes so they could check/uncheck any files freely. Some of their filtered results produce more than 100k+ files. This was not an issue until checkboxes were added and some users reported that their browser was hanging while waiting for the result list.

It seems the issue lies with Firefox and checkboxes. Chrome and Edge return any list size immediately after the fetch. Firefox completes the fetch POST, then hangs. If I remove the checkboxes, Firefox has no issue.

I have investigated the issue to the string line below. Anyone know how Firefox deals with checkboxes and why this may be happening? Is there something wrong with that ?

function calculateResultsText() {
  let text = document.getElementById('resultsProductContent');
  text.innerHTML = '';
  let string ='';
  let id_num = 1;
  let x = 0
  filesize_total = 0
  while ( x < result_filenames.length) {
    string_filename = result_filenames[x]
    string_filesize = result_filenames[x+1]
    filesize_total = filesize_total + parseInt(string_filesize)
    if (string_filesize > 1000000){
        string_filesize = (string_filesize/1000000).toFixed(2) + "GB"
    }
    else if (string_filesize > 1000){
        string_filesize = (string_filesize/1000).toFixed(2) + "MB"
    }
    else {
        string_filesize = string_filesize + "KB"
    }
    string += `<div class="form-check"><label class="form-check-label" label id="form-check-id" for="check${id_num}"> <input type="checkbox" class="form-check-input" id="check${id_num}" name="vehicle${id_num}" checked=""> ${string_filename} &emsp; ${string_filesize} </label></div>`
    //string += `${string_filename} &emsp; ${string_filesize} <br>`
    id_num+=1
    x+=2
  }



VBA Custom Ribbon - Checkbox Error when enabling editbox

I've put in a custom checkbox and a custom editbox in my ribbonUI where the checkbox enables the editbox when pressed. However, when I press the checkbox is returns with the error 'type mismatch' and the checkbox does not remain clicked. What is also weird is that the editbox does enable even though the error fires.

My XML for the custom ribbon UI is as per below -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customUI onLoad="RibbonOnLoad" xmlns="http://schemas.microsoft.com/office/2009/07/customui">
 
   <ribbon> 
     <tabs> 
 <group id="Process">
            <checkBox id="ProcessVariable"
                      label = "Send Email?"
                      onAction = "ExportRun.CheckBox_OnAction"
                      getPressed="ExportRun.CheckBox_OnAction"/>
                      
            <editBox id="ConsignmentNumber"
                     label="Consignment Number"
                     tag="textbox1"
                     getEnabled ="GetEnabledMacro"
                     onChange="EditBox_OnChange"/>
         
         </group>
       </tab> 
     </tabs> 
   </ribbon> 
 </customUI> 

My VBA code is as follows -

Dim Rib As IRibbonUI
Public MyTag As String

Sub RibbonOnLoad(ribbon As IRibbonUI)
    Set Rib = ribbon
End Sub

Sub GetEnabledMacro(control As IRibbonControl, ByRef Enabled)
    If MyTag = "Enable" Then
        Enabled = True
    Else
        If control.Tag Like MyTag Then
            Enabled = True
        Else
            Enabled = False
        End If
    End If
End Sub

Sub RefreshRibbon(Tag As String)
    MyTag = Tag
    If Rib Is Nothing Then
        MsgBox "Error, Save/Restart your workbook" & vbNewLine

    Else
    
        Rib.Invalidate
        
    End If
End Sub

Public Sub Checkbox_OnAction(ByVal control As IRibbonControl, pressed As Boolean)

If pressed Then

        Call EnableTextBoxControl

    Else

        Call DisableTextBoxControl

End If



End Sub

Sub EnableTextBoxControl()

Call RefreshRibbon(Tag:="textbox1")

End Sub

Sub DisableTextBoxControl()

Call RefreshRibbon(Tag:="")

End Sub

How do I avoid this error?




How to add enable checkbox selection on pinned rows in MUI Datatable?

Hi Im looking for a solution to enable checkbox selection on pinned rows. For unpinned rows its totally normal as the documentation says but I cant figure a solution to show for pinned rows. my rows are taking up space for checkbox but its not rendering it.

I tried using the the way mentioned in documentation but it only works for unpinned rows




dimanche 22 octobre 2023

How to make sure checkbox was checked when we want to edit it

I am currently doing a website with PHP and HTML with connecting with mysql. I am struggling with the checked of the checkbox. The website is file management system where we can make a certain files be public and certain to be confidential. I have found some good answers in here but Idk why it could not work when I want to insert a new files and not the edited one.

my html

<div class="form-group">
  <label for="is_public" class="control-label"><input type="checkbox" name="is_public" id="is_public"><i>Make this file accesible to all users</i></label>
</div>

is_public is a data from mysql where 1 means it is public and 0 is confidential. this checkbox is the same when you want to upload a new file.

this is how the data is inserted into mysql

if(isset($is_public) && $is_public == 'on')
 $data .= ", is_public = 1";
else
$data .= ", is_public = 0";

anyone can help?

I have put php <?php if(isset($meta['is_public'], '1') !== false) echo 'checked="checked"';?>after the id, it works for uploaded file when I want to edit it but it didnt work when i want to upload new file bcs they will appear error message.




samedi 21 octobre 2023

How to change **tick** color in a bootstrap checkbox?

I have the following html code styled with bootstrap:

<div class="col-lg-4 col-12 text-center">
  <div style="width: 80%; margin: auto">
    <ul class="list-group">
      
    </ul>
  </div>
</div>

And I'm trying to change the checkbox ticks button. I also defined some style for my checkboxes:

@keyframes shadowAnimation {
  0% {
    box-shadow: 0 0 0 0.25rem rgba(255, 152, 0, 0.9);
  }
  100% {
    box-shadow: 0 0 0 0.25rem rgba(255, 152, 0, 0.1);
  }
}

.animate-checkbox {
  animation: shadowAnimation 1s ease-in-out;
}

input[type="checkbox"].form-check-input:focus-visible,
input[type="checkbox"].form-check-input:focus {
  border-color: #212529;
  border: var(--bs-border-width) solid #ff9800 !important;
}

And animation is controlled by javascript. I don't want these option are overwritten, but i can achieve to have the tick colored.
Any suggestion? Thanks in advance.




protect and unprotect a checkbox with a warning give me a erroneous behavior

Checking an unchecking a checkbox creates a protection "edit with warning", but unchecking does not erase this protection, as stated in the AppsScript code.

I reduced the problem to a minimum Sheet, with a minimum code. how to send this sheet? easier to see than to explain. or how to post images?

I suspect erroneous behaviour of cell protection of sheet data.

thanks for any help.




vendredi 20 octobre 2023

How do I control input checkbox "checked" state with React?

I am working on an application that has a form and radio buttons.

For one of the radio buttons, it has an option that can be toggled on/off with a checkbox.

I want the checkbox to be disabled if the respective radio button is NOT selected, its default behavior to work when is it active, and for it to be disabled AND unchecked if a different radio button is then selected.

I have gotten all of those behaviors to work, but React is throwing an exception that says,

app-index.js:31 Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

My "working" solution:

 const [checkboxActive, setCheckboxActive] = useState<boolean | undefined>(false);

 const handleOptionClick = (option?: string) => {
    setSelected(true);
    if (option) {
      setEveryOtherLetterSelected(true);
      setCheckboxActive(undefined);
    } else {
      setEveryOtherLetterSelected(false);
      setCheckboxActive(false);
    }
  }

<input type="checkbox" name="first" disabled={everyOtherLetterSelected ? false : true} checked={checkboxActive} />

From this thread (Setting a checkbox "check" property in React), I see that this is a weird thing with React and checkbox type inputs where its "checked" value is either a boolean or undefined. I have tried putting the "!!" in front of the condition (!!checkboxActive), but that changes the behavior.

Is there a more acceptable way to do this where React won't yell at me?




jeudi 19 octobre 2023

Changes in checkbox statut are lost on new entry in a datatable reactive and editable?

I am working on a shiny app made for data recording. Each time the observers see a new occurence of an event, a new entry must be recorded. This is translate in the app by adding a line in a reactive and editable dataframe. When the field work is over, data must be checked for potential entry mistake. Most of the time this is done by another people. Sometimes, data can be interpreted as an error and deleted because out of the box. Yet,I would like to let observers confirmed out of the box data to make sure it is not deleted. To do so i would like a checkbox available in the dataframe. If i change manually data into the table (text or numeric), changes are saved through the function editable (see code) but if i toggle a checkbox, it is reintialised into untoggled when i add a new entry. Here an exemple:

library(shiny)
library(tidyverse)
library(DT)
library(shinyjs)

shinyApp(
ui <- fluidPage(
  titlePanel("Reactive table with checkbox editable"),
  selectInput("photo","Photo", c("choose"="","Dog", "Shovel", "Cat", "Desk")),
  selectInput("description", "Description", c("choose"="","object", "animal")),
  actionButton("add_line", "Add a line"),
  dataTableOutput("table")
),

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

# Function to manage cell changes
  
  editable<- function(input,data) {
   observeEvent(input$table_cell_edit, {
      info <- input$table_cell_edit
      row <- info$row
      col <- info$col
      value <- info$value
      
      dat <- data()
      if (col == 3) {  
        dat[row, col] <- as.logical(value) 
      } else {
        dat[row, col] <- value
      }
      data(dat)
      
    })} 
    

# Creating an empty frame
  
  myinitialframe <- data.frame(
    Photo = character(),
    Description = character(),
    Confirmed = character(),
    stringsAsFactors = FALSE
  )
  
# Get my empty frame reactive
  mydata <- reactiveVal(myinitialframe) 
  
  # ajout de ligne
  observeEvent(input$add_line, {
    new_row <- data.frame(
      Photo = input$photo,
      Description = input$description,
      Confirmed = FALSE
      )
    newdata <- rbind(new_row,mydata())
    mydata(newdata)
  })
  
# Display the table with checkbox in column "Confirmed"

    output$table <- DT::renderDataTable({
    mydata <- as.data.frame (mydata ())
    
    mydata <- datatable(
      mydata,
      editable = "cell",
      options = list(
        columnDefs = list(
          list(
            targets = c(3),
            render = JS(
              "function(data, type, row, meta) {",
              "  if (type === 'display') {",
              "    return '<input type=\"checkbox\" ' + (data === 'TRUE' ? 'checked' : '') + '/>';", 
              "  }",
              "  return data;",
              "}"
            )
          )
        )
      )
    )
    
})
    editable(input,mydata)


  }
)

I have tried :

  • shinyInput such as proposed in the forum but haven't been able to make it work when there is new lines to enter as assumed because it is not working with a reactive table?
  • Callback and JS :
         callback = JS(
        "table.on('click', 'input[type=checkbox]', function() {",
        "  var data = table.cell(this).data();",
        "  data = !data;",
        "  table.cell(this).data(data).draw(false);",
        "});"
      ),
shinyjs::runjs(
      "shinyjs.toggleCheckbox = function(checkbox) {
        var row = checkbox.closest('tr');
        var rowIndex = mytable.row(row).index();
        var newValue = !mytable.cell(rowIndex, 3).data();
        mytable.cell(rowIndex, 3).data(newValue).draw();
      };"
    ) 



mercredi 18 octobre 2023

How to make each component shared state multiple controlled checkbox selection unique in react?

i have several components on the left side. I am running map on them. Each component has a switch.so on the basis of component id after clicking on switch a list of checkboxes open at right side. then again i am also running map on checkboxes because this data is coming from backend. for example component-1 have list of checkboxes with the following name. checkbox-1 checkbox-2 if i select the checkbox-1 and then click on component-2 switch, so by this component-2 list of checkboxes will show. the issue is component-2 checkbox name also will be checked if component-2 have checkbox name same like component-1. how to keep them unique? i want each component checkbox selection to be unique. this is one i did so far. (1) i am passing key to components.so whenever id change react rerender the ui.but its not working. (2) currently my checkbox state is in parent component,i looked into react documentation, according to it the state should be local to component.i move the checkbox state into checkbox component then my issue was fixed. But i need checkbox selection in parent because i am sharing this with other components. (3) then i implement the redux-saga. but still same issue, then i implemented context api, this also didn't resolve my issue.

i am sharing my handlechange code. this is how managing them.

  const handleChange = event => {
    const { name, checked } = event.target;
    if (checked) {
      setCheckedItems({ ...checkedItems, [name]: true });
    } else {
      const { [name]: deletedItem, ...updatedCheckedItems } = checkedItems;
      setCheckedItems(updatedCheckedItems);
    }
  };

(4) then i thought maybe i should make a data structure like so, each component unique id should have its own checkbox selection when user checked any checkbox. this is that code.

  const handleChange = (event, componentId, index) => {
    const { name, checked } = event.target;

    setCheckboxIndex(index);

    // Update the state using the componentId to ensure uniqueness
    setCheckedItems(prevItems => {
      // Get the previous state for the component or initialize it
      const componentState = prevItems[componentId] || { checkboxes: {} };
      // Clone the previous component state
      const updatedComponentState = { ...componentState };

      if (checked) {
        updatedComponentState.checkboxes = {
          ...updatedComponentState.checkboxes,
          [name]: true,
        };
      } else {
        // Remove the checkbox from the component's state
        const {
          [name]: deletedItem,
          ...updatedCheckboxes
        } = updatedComponentState.checkboxes;
        updatedComponentState.checkboxes = updatedCheckboxes;
      }

      // Update the overall state with the new component state
      return {
        ...prevItems,
        [componentId]: updatedComponentState,
      };
    });
  };

but this one also didn't resolve my issue. this also code currently in context.js now i am sharing my how my component looks alike.

 (toggleMenu === 'feedback' &&
              Object.keys(feedback).includes(String(q.id))) ||
            (q.question.question_type === 'assignment' &&
              toggleAll === 'auto') ? (
              <Grid item xs={5} className={classes.questionWrapper} key={q.id}>
                <NewFeedback
                  key={q.id}
                  assignmentIndex={qidx}
                  markingData={automatedMarkingData}
                  questionId={q.question.id}
                  qId={qId}
                  fetchMarkingData={fetchMarkingData}
                  status={assignmentStatus}
                />
              </Grid>

whenever user click on component switch i am updating this state. feedback then on the basis of id inside feedback i am opening checkbox component.

the component NewFeedback is the component where checkbox component is, with name of sidebar.js

<SideBar
        bow={bow}
        checkedItems={checkedItems}
        handleSelectAll={handleSelectAll}
        handleChange={handleChange}
        allSelected={allSelected}
        assignmentId={markingData.question_submission}
        assignmentIndex={assignmentIndex}
        checkboxIndex={checkboxIndex}
      />

this is my sidebar.js code

import React, { useContext } from 'react';
import {
  Box,
  Checkbox,
  Divider,
  FormControlLabel,
  FormGroup,
  LinearProgress,
  Paper,
  Typography,
} from '@material-ui/core';
import styles from './styles.css';
import { LessonContext } from '../../LessonViewer/GoProgressQuizResult/Context';

export const SideBar = ({
  bow,
  checkedItems,
  handleSelectAll,
  handleChange,
  allSelected,
  assignmentId,
  assignmentIndex,
  checkboxIndex,
}) => {
  return (
    <Paper elevation={0} className={`${styles.FeedbackSideMenu}`}>
      <Box p={1}>
        <Typography align="center">
          <b>All BOW</b>
        </Typography>
      </Box>
      <Divider style= />
      <Box style=>
        <FormGroup>
          <FormControlLabel
            style=
            control={
              <Checkbox
                checked={allSelected}
                onChange={handleSelectAll}
                name="selectAll"
                color="primary"
              />
            }
            label="Select All"
          />
        </FormGroup>
        {bow.map((v, index) => {
          // const isChecked =
          //   (checkedItems[assignmentId] &&
          //     checkedItems[assignmentId].checkboxes[v.bow_name]) ||
          //   false;

          // console.log('isChecked', isChecked);
          return (
            <div key={v.id}>
              <Box className={`${styles.FeedbackOption}`}>
                <Box
                  display={'flex'}
                  justifyContent="space-between"
                  alignItems="center"
                >
                  <Checkbox
                    id={v.id}
                    // checked={checkedItems[`${v.bow_name}_${v.id}`] || false}
                    checked={checkedItems[v.bow_name] || false}
                    // checked={label === v.bow_name ? true : false}
                    // checked={isChecked}
                    onChange={e => handleChange(e, assignmentId, index)}
                    name={v.bow_name}
                    color="primary"
                  />
                  <Typography>
                    <b>{v.bow_name}</b>
                  </Typography>
                  <Box bgcolor={`${v.color}`} width={20} height={20} />
                </Box>

                <Typography>
                  <small>{v.sum_count} count</small>
                </Typography>
                <LinearProgress
                  variant="determinate"
                  value={v.sum_count ? v.sum_count : 0}
                />
              </Box>
              <Divider style= />
            </div>
          );
        })}
      </Box>
    </Paper>
  );
};

sorry i cant make sandbox because my actualy codebase is pretty big. here's my ui images for better understanding. enter image description here




Ajax to make line-through when checkbox checked with php&mysql

Trying to learn some php and mysql, so I'm working on a todo list where I want the todo tasks get a line-through when a checkbox that each task has is checked and removed again if unchecked.

like i have here:

enter image description here

I have made so i can make the line-through from a variable in database like this:

<input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-<?= $todoTask_Data['task_id'] ?>" <?php if($todoTask_Data['task_checked'] == 'true') {echo 'checked';} ; ?> />

Now I need to find out how i add the "true" variable to the task_checked column in mysqli when the checkboxes are clicked.

Not really worked with ajax/js much before, so its been very confusing figuring out how to do this. But I think i got the idea now, but still cant get this to work.

This is the script I got so fare

  $(document).ready(function() {
$('.checkbox-todo').on('change', function() {
  if (this.checked) {
    var checkboxID = $(this).attr('id');


    $.ajax({
      url: "update_TodoTask.php",
      method: "POST",
      data: { checkboxID: checkboxID },
      success: function(response) {

      }
    });
  }
});
});

And inside update_TodoTask.php i got something like this:

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['checkboxID'])) {
 $checkboxID = $_POST['checkboxID'];


header('Location: test.php');
}

Here is the html code: https://pastecode.io/s/zw4thpoe

But I don't even think it is communication with update_TodoTask.php when pressed. should it not be triggering the header location when i press a checkbox?

I'm not sure im telling the ajax script which checkbox in the todo list is pressed correctly?

Can anyone tell me what I'm doing wrong here?




mardi 17 octobre 2023

Maui syntax to use converter inside of a C# method

What I'm trying to accomplish

In a CollectionView, I display a list of objects. In each display there's a checkbox next to it.

Ideally, when the user checks or un-checks the checkbox I go into a method where I can do stuff with the object:

enter image description here

The above is fantasy code.

The actual code

In reality, when the user checks/unchecks the box the code goes into a method, only I'm passing this object CheckedChangedEventArgs into the method.

I need to convert that object ChcekedChangedEventArgs into a bool. (Note that I'm using the MvvM pattern, so I'm not working with code-behind.)
enter image description here

A kind soul gave me some code that will probably do the converting:

public class CheckedChangedArgsConverter : BaseConverterOneWay<CheckedChangedEventArgs, bool>
{
    public override bool DefaultConvertReturnValue { get; set; } = false;

    public override bool ConvertFrom(CheckedChangedEventArgs value, CultureInfo culture)
    {
        return value.Value;
    }
}

However, I don't know how to use the converter. It seems like I have two options here:

  1. Run the converter from the Xaml and have it run before the command AddRemoveFromList is called so I can pass in the converted Boolean, or
  2. Run the converter code from the C# class, something like this:
    enter image description here

The fact is, I have no idea how to do either. Can anyone help?

====================================================================

EDIT: the object CheckedChangedEventArgs getting passed into the C# method is ALWAYS null.

Here's my Checkbox code. I'm using the EventToCommandBehavior because it's the only thing I can think of to call a command from inside the Checkbox:

<CheckBox x:Name="checkBox"
          ScaleX="1.5"
          ScaleY="1.5"
          Color="#000063"
          HorizontalOptions="End">
    <CheckBox.Behaviors>
        <toolkit:EventToCommandBehavior EventName="CheckedChanged"
                                        Command="{Binding Source={x:Reference this}, 
                                                  Path=BindingContext.AddRemoveFromListCommand}"/>                                       
    </CheckBox.Behaviors>
</CheckBox>

I added x:TypeArguments to the Checkbox:

<CheckBox x:Name="checkBox"
          ScaleX="1.5"
          ScaleY="1.5"
          Color="#000063"
          HorizontalOptions="End">
    <CheckBox.Behaviors>
        <toolkit:EventToCommandBehavior
                x:TypeArguments="CheckedChangedEventArgs"
                                        EventName="CheckedChanged"
                                        Command="{Binding Source={x:Reference this}, Path=BindingContext.AddRemoveFromListCommand}" />
    </CheckBox.Behaviors>
</CheckBox>

And that did the trick.




Python RPA Automation - how to check toggle status of checkbox under the mouse cursor

is there any way hot to check/detect toggle status of checkbox under the mouse cursor ? I move the mouse cursor to the specific area and then I need to check the toggle state, if it is ON or OFF.

For example this one : [Exapmle][1] [1]: https://ift.tt/qzEWVsy

Thank you




lundi 16 octobre 2023

R Shiny script, checkbox and save

I have a problem with my script below, in fact when recording the status of checkboxes, I would like to have True if the checkbox is checked otherwise False, because for now I just have or . This is my script on R :

library(shiny)
library(shinythemes)
library(leaflet)
library(DT)
library(leaflet.extras)
library(readxl)
library(purrr) 
library(htmlwidgets)
library(magrittr)
library(rgdal)
library(sf)
library(htmltools)

Boccurrence <- read.csv("data1", sep = ",")
Boccurrence2 <- read.csv("data2", sep = ",")
Boccurrence$etape_suppression <- NA
Boccurrence1 <- rbind(Boccurrence, Boccurrence2)


lng1 <- -12
lat1 <- 39
lng2 <- 13
lat2 <- 52

taxon_data <- read_excel("species.xlsx")
species_names <- taxon_data$species

output_directory <- "map"


zee <- st_read("zee.shp")

zee <- st_transform(zee, crs = st_crs("+proj=longlat +datum=WGS84"))


ui <- fluidPage(
  titlePanel("Map"),
  sidebarLayout(
    sidebarPanel(
      selectInput("species_name", "Species", choices = unique(c(Boccurrence1$scientificname, Boccurrence2$scientificname))),
    ),
    mainPanel(
      leafletOutput("map"),
      verbatimTextOutput("selected_marker_id"), 
      DTOutput("table"),
      actionButton("save_button", "save"),
      downloadButton("download_button", "download")
    )
  )
)

server <- function(input, output, session) {
  
  filtered_occurrences1 <- reactiveVal(NULL)
  
  observe({
    species_name <- input$species_name
    
   
    filtered_data <- subset(Boccurrence1, scientificname == species_name)
    
    filtered_data$Longitude <- as.numeric(filtered_data$Longitude)
    filtered_data$Latitude <- as.numeric(filtered_data$Latitude)
    
    
    if (nrow(filtered_data) == 0) {
      filtered_occurrences1(NULL)  
    } else {
      filtered_occurrences1(filtered_data)  
    }
  })
  

  selected_rows <- reactiveVal(list())
  
  
  observeEvent(input$map_marker_click, {
    event <- input$map_marker_click
    if (!is.null(event$id)) {
      selected_row <- filtered_occurrences1()[filtered_occurrences1()$id == event$id,]
      complete_cases <- complete.cases(selected_row$id)
      selected_row <- selected_row[complete_cases,]
      
      selected_row <- cbind(Suppression = paste0('<input type="checkbox" id="suppression_', selected_row$id, '">'),
                            Inversion = paste0('<input type="checkbox" id="inversion_', selected_row$id, '">'),
                            selected_row)
      
      output$table <- renderDataTable({
        datatable(
          selected_row,
          escape = FALSE, 
          options = list(rowId = "id")
        )
      })
    }
  })
  
  
  observeEvent(input$save_button, {
    event <- input$map_marker_click
    if (!is.null(event$id)) {
      selected_row <- filtered_occurrences1()[filtered_occurrences1()$id == event$id,]
      complete_cases <- complete.cases(selected_row$id)
      selected_row <- selected_row[complete_cases,]
      
      selected_row$Suppression <- paste0('<input type="checkbox" id="suppression_', selected_row$id, '">')
      selected_row$Inversion <- paste0('<input type="checkbox" id="inversion_', selected_row$id, '">')
      
  
      current_selected_rows <- selected_rows()
      current_selected_rows[[length(current_selected_rows) + 1]] <- selected_row
      selected_rows(current_selected_rows)
    }
  })
  

  output$download_button <- downloadHandler(
    filename = function() {
      "data.csv"
    },
    content = function(file) {
      all_selected_rows <- do.call(rbind, selected_rows())
      write.csv(all_selected_rows, file, row.names = FALSE)
    }
  )
  
  # Leaflet map
  output$map <- renderLeaflet({
    m <- leaflet() %>%
      addTiles() %>%
      addProviderTiles("Esri.OceanBasemap", group = "Esri Ocean Basemap") %>%
      addPolygons(
        data = zee,
        weight = 1,
        color = "#0000FF",
        opacity = 1,
        fill = TRUE,
        fillOpacity = 0
      ) %>%
      addRectangles(
        lng1 = lng1, lat1 = lat1,
        lng2 = lng2, lat2 = lat2,
        weight = 2,
        color = "black",
        opacity = 1,
        fillOpacity = 0
      )
    
    if (!is.null(filtered_occurrences1())) {
      m <- m %>%
        addCircleMarkers(
          data = filtered_occurrences1(),
          lng = ~Longitude, lat = ~Latitude,
          color = "#34C924", radius = 4, stroke = FALSE,
          fillOpacity = 1,
          group = "markers",
          layerId = ~id 
        )
      
      if (!is.null(input$map_marker_click)) {
        clicked_id <- input$map_marker_click$id
        if (!is.null(clicked_id)) {
          m <- m %>%
            addCircleMarkers(
              data = filtered_occurrences1()[filtered_occurrences1()$id == clicked_id, ],
              lng = ~Longitude, lat = ~Latitude,
              color = "#FFA500", radius = 4, stroke = FALSE,
              fillOpacity = 1,
              group = "selected_marker",
              layerId = ~id
            )
        }
      }
    }
    
    m %>%
      addCircleMarkers(
        lng = 13, lat = 52,
        options = markerOptions(clickable = TRUE, opacity = 0),
        popup = "Zone : 39-52 °N; -12-13 °E"
      )
  })
  
}


shinyApp(ui = ui, server = server)

I tried this code but as soon as I save the page it closes and doesn't work anymore.

observeEvent(input$save_button, {
  event <- input$map_marker_click
  if (!is.null(event$id)) {
    selected_row <- filtered_occurrences1()[filtered_occurrences1()$id == event$id,]
    complete_cases <- complete.cases(selected_row$id)
    selected_row <- selected_row[complete_cases,]

    if (input[[paste0("suppression_", selected_row$id)]] == "on") {
      selected_row$Suppression <- "Suppression"
    } else {
      selected_row$Suppression <- ""
    }

    if (input[[paste0("inversion_", selected_row$id)]] == "on") {
      selected_row$Inversion <- "Inversion"
    } else {
      selected_row$Inversion <- ""
    }

    current_selected_rows <- selected_rows()
    current_selected_rows[[length(current_selected_rows) + 1]] <- selected_row
    selected_rows(current_selected_rows)
  }
})

I've also tried this, but it gives me the same error and I don't understand.


selected_rows <- reactiveVal(list())

observeEvent(input$map_marker_click, {
  event <- input$map_marker_click
  if (!is.null(event$id)) {
    selected_row <- filtered_occurrences1()[filtered_occurrences1()$id == event$id,]
    complete_cases <- complete.cases(selected_row$lat, selected_row$lng)
    selected_row <- selected_row[complete_cases,]

    selected_row$Suppression <- paste0(
      '<input type="checkbox" id="suppression_', selected_row$id, '" name="suppression_', selected_row$id, '">'
    )
    selected_row$Inversion <- paste0(
      '<input type="checkbox" id="inversion_', selected_row$id, '" name="inversion_', selected_row$id, '">'
    )

    current_selected_rows <- selected_rows()
    current_selected_rows[[length(current_selected_rows) + 1]] <- selected_row
    selected_rows(current_selected_rows)

    output$table <- renderDataTable({
      datatable(
        selected_row,
        escape = FALSE,
        options = list(rowId = "id")
      )
    })
  }
})

observeEvent(input$save_button, {
  event <- input$map_marker_click
  if (!is.null(event$id)) {
    selected_row <- filtered_occurrences1()[filtered_occurrences1()$id == event$id,]
    complete_cases <- complete.cases(selected_row$lat, selected_row$lng)
    selected_row <- selected_row[complete_cases,]

    selected_row$Suppression <- ifelse(
      input[[paste0("suppression_", selected_row$id)]] == "on",
      "TRUE",
      ""
    )
    selected_row$Inversion <- ifelse(
      input[[paste0("inversion_", selected_row$id)]] == "on",
      "TRUE",
      ""
    )

    current_selected_rows <- selected_rows()
    current_selected_rows[[length(current_selected_rows) + 1]] <- selected_row
    selected_rows(current_selected_rows)
  }
})





dimanche 15 octobre 2023

on checkbox select dynamically display checkboxes in codeigniter php

i have a form where there are few checkboxes and when the user selects the checkboxes, some other checkboxes should display according to the selection,

$(document).ready(function() {
  // Handle branch checkbox change event
  $('.branch-checkbox').change(function() {
    var selectedBranches = [];

    // Get all selected branch values
    $('.branch-checkbox:checked').each(function() {
      selectedBranches.push($(this).val());

    });

    if (selectedBranches.length > 0) {
      // Send an AJAX request to fetch students based on selected branches
      $.ajax({
        url: "<?php echo base_url(); ?>index.php/homecontroller/fetchstudents",
        method: "POST",
        data: {
          selectedBranches: selectedBranches
        },
        success: function(data) {
          // Display the fetched students
          $('#student-container').html(data);
        }
      });
    } else {
      // Clear the student container if no branches are selected
      $('#student-container').empty();
    }
  });
});
<div class="col-md-12">
  <div class="form-group">
    <label style="border-bottom: 1px solid">Branch</label>
    <div class="row" id="branch-checkboxes"><input type="checkbox" class="branch-checkbox" value="5" name="branches[]"><label for="md_checkbox_5" style="margin-bottom:0px">Banjara Hills</label><br>
    </div>
  </div>
</div>


<div class="col-md-12">
  <div class="form-group">
    <label style="border-bottom: 1px solid">Students</label>
    <div class="row" id="student-container">
      <!-- Student checkboxes will be inserted here dynamically -->
    </div>
  </div>
</div>

below is my controller:

public function fetchstudents()
{
    if ($this->input->post('selectedBranches')) {
        $selectedBranches = $this->input->post('selectedBranches');
        $student_checkboxes = $this->category->fetch_student_checkboxes($selectedBranches);
        echo $student_checkboxes;
    }
}

and my model:

public function fetch_student_checkboxes($selectedBranches)
{
    $this->db->where_in('branch', $selectedBranches);
    $this->db->where('status', 'Active');
    $query = $this->db->get('register');

    $output = '';
    foreach ($query->result() as $row) {
        $output .= '<input type="checkbox" class="student-checkbox" value="' . $row->id . '" name="students[]">';
        $output .= '<label for="md_checkbox_' . $row->id . '" style="margin-bottom:0px">' . $row->name . '</label><br>';
    }

    return $output;
}

however this doesnt work and i dont get any error also, can anyone please tell me what could be wrong in here , thanks in advance




How to use one checkbox (IsChecked) to control another checkbox (IsEnabled) by binding function?

I use Visual Studio 2022 to create a WPF application. I have two checkboxes, grade_4_CB and grade_4_centered_CB in a Windows frame like this:

<Window>
    <Grid>
        <Viewbox Stretch=" fill">
            <Canvas Width=" 1100" Height=" 620">
                <CheckBox x:Name="grade_4_CB" Content="Grade 4" />
                <CheckBox x:Name="grade_4_centered_CB" Content="Grade 4 Centered"/> 
            </Canvas>
        </Viewbox>
    </Grid>
</Window>

Now, when I click grade_4_CB (IsChecked="True"), the grade_4_centered_CB's IsEnabled="True".

While not clicking of grade_4_CB (IsChecked="False"), the grade_4_centered_CB's IsEnabled="False"

I tried to add behind grade_4_centered_CB like,

<CheckBox x:Name="grade_4_centered_CB" Content="Grade 4 Centered">
    <CheckBox.Style>
        <Style TargetType="CheckBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=grade_4_CB, Path=IsChecked}" Value="True">
                    <Setter Property="IsEnabled" Value="True" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=grade_4_CB, Path=IsChecked}" Value="False">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

However, I get an error,

Error XLS0415: No attachable property 'Style' found on type 'CheckBox'

Another method is replacing <CheckBox.Style> to <CheckBox.Resources> but I get a similar error.

Besides, I also tried to modify directly the property of grade_4_centered_CB in right column (common-IsEnable-data bindingdialog), find and add grade_4_CB -path(IsChecked), but no matter False string or True string, there is no change in grade_4_centered_CB




samedi 14 octobre 2023

Java Table doesn't get rendered as expected

I did some attempts with a JTable. I want the table to contain some checkboxes and having certain background colors.

Everything is working fine from row 2 towards the end of the table. But unfortunately row 1 gets not rendered as expected. I’m wondering because row 1 is fine, as soon, as I resize the whole JDialog, which contains my table.

Adding data and the renderer to the table:

databaseTable.setModel(new DefaultTableModel(data, head));
databaseTable.getColumnModel().getColumn(0).setMinWidth(0);
databaseTable.getColumnModel().getColumn(0).setMaxWidth(0);
databaseTable.getColumnModel().getColumn(0).setWidth(0);
databaseTable.setDefaultRenderer(Object.class, new MyTableCellRenderer());

The Class MyTableCellRenderer

public class MyTableCellRenderer extends DefaultTableCellRenderer {

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
                                                   int row, int col) {

        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);


        if (isSelected)
        {
            c.setBackground(RowColors.selectedRow.getColor());
        }
        else
        {
            c.setBackground(row % 2 == 0 ? RowColors.evenRow.getColor() : RowColors.oddRow.getColor());
        }

        List<Integer> values = Lists.newList(2, 3,4,6,8);
        if (values.contains(col))
        {
            MyBooleanRenderer br = new MyBooleanRenderer();
            table.getColumnModel().getColumn(col).setCellRenderer(br);
            table.getColumnModel().getColumn(col).setCellEditor(table.getDefaultEditor(Boolean.class));
            c.setBackground(row % 2 == 0 ? RowColors.evenRow.getColor() : RowColors.oddRow.getColor());
        }

        return c;
    }

and finally the Class MyBooleanRenderer:

public  class MyBooleanRenderer extends JCheckBox implements TableCellRenderer, UIResource {

        private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);

        public MyBooleanRenderer() {
            super();
            setHorizontalAlignment(JLabel.CENTER);
            setBorderPainted(true);
            setOpaque(true);

        }

        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {

                super.setBackground(table.getSelectionBackground());
            } else {
                setBackground(row % 2 == 0 ? RowColors.evenRow.getColor() : RowColors.oddRow.getColor());
            }
            setSelected((value != null && ((Boolean) value).booleanValue()));

            if (hasFocus) {
                setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
            } else {
                setBorder(noFocusBorder);
            }

            return this;
        }
    }

Table with incorrect rendering in row 1