vendredi 30 septembre 2022

How to display partially selected list items in UI5?

Is there a way that I could partially select a list item with sap.m.ListBase mode set as MultiSelect?

Something like this for some of the entries in the list:
https://sdk.openui5.org/entity/sap.m.CheckBox/sample/sap.m.sample.CheckBoxTriState

SAPUI5 checkbox in tri-state

In the official UI5 API reference for sap.m.Checkbox, there's the property partiallySelected. But for the sap.m.ListBase, I couldn't find anything.




jeudi 29 septembre 2022

Hide/limit checkboxes based on their amount

Need some help with hiding checkboxes. I have a form that has around 12 labels (checkboxes). I need to only show around 5 in my div, how would I go about hiding the rest? It doesn't matter if they're checked or not or what value they have, just need to show any 5 in the form while hiding the others.

Having a "See more" instead of them might also be useful.

EDIT: Apologies, added code for clarity. I can't change much in the code itself, but I can manipulate it by adding CSS/javascript to the block builder platform I'm using.

    <form class="t-product__option-variants t-product__option-variants_custom t-product__option-variants_buttons t-product__option-variants_color">

    <label class="t-product__option-item t-product__option-item_active t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 1" checked=""></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 2"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 3"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 4"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 5"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 6"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 7"></label>

    <label class="t-product__option-item t-product__option-item_buttons t-product__option-item_color">
    <input class="t-product__option-input t-product__option-input_buttons t-product__option-input_color" type="radio" name="Color" value="Color 8"></label>

</form>



How to change the status of check boxes with key stroke in Visual Basic?

I am now trying to change the status of check boxes (checked or unchecked) by pressing the enter key from the keyboard. I searched through on the web, and I am not lucky enough to get what I want. Because I set up to go through all the fields by pressing the tab button on the keyboard, having to go for the mouse and move it and click on the check box seems a little irritating. So, there must be a way to change the status of the check box(es) just by pressing the enter key from the keyboard. Can anyone help me with this, please? Thanks in advance.




mercredi 28 septembre 2022

select multiple checkboses in matlab

I have a gui with nine checkbox in the following code i can select only one of each but what i wanted to add is if the NormeEm checkbox is selected i want to select another checkbox, which i tried to set up at the end of the code by using a switch and 2 cases so that only another one checkbox can be selected but it won't show and it doesn't give me an error code.

       function kgexec4n(Init)
        %KGEXEC4N boite de dialogue "norme" associée à kgexec4
        
        %CAVIAR2, © ALSTOM + OL 2000/04-2003/03
        error(nargchk(0,1,nargin));
        persistent blkParamNorm
        
        %%%% ouverture boite
        if nargin==1
         %"full block path name" du bloc ParamNorme
         blkParamNorm=gcb;
         if ~strcmp(get_param(blkParamNorm,'MaskType'),'ParamNor')
          errordlg(kverranorm(14),'Caviar3','modal')
          return
         end
         %création figure
         hf=kgui4n;
         %en cas de librairie verrouillée on interdit OK
         %x=get_param(get_param(gcs,'Parent'),'Lock');   %modif2.4 10/03/2006
         rep=findstr(gcs,'/');
         if isempty(rep)
            active_sys=gcs;
         else
            active_sys=gcs(1:rep-1)
         end
         x=get_param(active_sys,'Lock')
         set( findobj(hf,'Tag','NormeOK'), 'Enable', onoff(~onoff(x)) )
        else
         hf=gcbf;
        end
    
    %%%% handles des contrôles et dévalidation de tout
    hrb=[findobj(hf,'Tag','Norme0')
     findobj(hf,'Tag','Norme1022')
     findobj(hf,'Tag','NormeEm')
     findobj(hf,'Tag','NormeG53')
     findobj(hf,'Tag','NormeCh')
     findobj(hf,'Tag','NormeUsrV')
     findobj(hf,'Tag','NormeUsrI')
     findobj(hf,'Tag','Norme50160')
     findobj(hf,'Tag','Norme519')];
    hrbVal=get(hrb,'Value');
    set(hrb,'Value',0)
    hno=[findobj(hf,'Tag','Param0')
     findobj(hf,'Tag','Param1022')
     findobj(hf,'Tag','ParamEm')
     findobj(hf,'Tag','ParamG53')
     findobj(hf,'Tag','ParamCh')
     findobj(hf,'Tag','ParamUsrV')
     findobj(hf,'Tag','ParamUsrI')
     findobj(hf,'Tag','Param50160')
     findobj(hf,'Tag','Param519-1')
     findobj(hf,'Tag','Param519-2')
     findobj(hf,'Tag','Param519-3')
     findobj(hf,'Tag','Param519-4')];
    set(hno,'Enable','off')

%%%% gestion dynamique de la boite
switch get(gcbo,'Tag'); %l'objet ayant provoqué l'appel

%dialogue dynamique
case {'Norme0','Norme1022'}
 set(gcbo,'Value',1)
case 'NormeEm'
 set(gcbo,'Value',1),enable(hno(3))
    switch get(gcbo,'Tag');
        case 'Norme1022'
            set(findobj(hf,'Tag','Norme1022'),'Value',1)
        case 'NormeUsrV'
           set(findobj(hf,'Tag','NormeUsrV'),'Value',1),enable(hno(6))  
    end   
case 'NormeG53'
 set(gcbo,'Value',1),enable(hno(4))
case 'NormeCh'
 set(gcbo,'Value',1),enable(hno(5))
case 'NormeUsrV'
 set(gcbo,'Value',1),enable(hno(6))
case 'NormeUsrI'
 set(gcbo,'Value',1),enable(hno(7))
case 'Norme50160'
 set(gcbo,'Value',1),enable(hno(8))
case {'Norme519','Param519-1'}
 set(hrb(9),'Value',1),Scr519(hno(9:12))
end

If i could have some help to figure out what's wrong in my code it would help me a lot




Cypress: Click specific checkbox embedded in the AG-Grid table

I am having trouble clicking on targeted checkboxes from the AG grid table.

enter image description here

How would you implement the following checkbox based on the code with Cypress?

enter image description here

Thank you!




mardi 27 septembre 2022

Why I cant seem to center and get my radio buttons inline with the labels?

No matter what I look up online, anything I try doesn't seem to center these annoying radio buttons with the labels inline horizontally.

  • I have the labels to the left of the form, with the radio buttons inline on the right of the labels.
  • The radio buttons are a tad lower than the labels, and I am looking to center them evenly with the labels so it looks nicer and more professional.

I am very finicky with the smallest details, so getting this right is a huge thing for me!

Hoping someone can point out what I am missing or doing wrong.

P.S. I am brand new to this!

CSS code for radio buttons

What it looks like now




Scss change color of mat-checkbox if enabled

is there a way to change the color of mat-checkboxes if they're checked and enabled. I've tried something similiar to this question Scss change color of mat-checkbox if disabled and used enabled instead of disabled but it isn't working.

This is my css code for the checkboxes:

:host ::ng-deep .mat-checkbox-checked.mat-accent.mat-checkbox-enabled .mat-checkbox-background {
  background-color: red !important;
}

If I swap enabled with disabled it works fine, but it's not what I want. My goal is that only checkboxes which are enabled and checked are given a ceratin color of background and tick.




lundi 26 septembre 2022

Javascript html form text&email&checkbox

This question is mainly about Javascript.

The contents you want to move include Fill in all the text, email, and checkboxes (one checkbox can be checked). The content is as follows: "Disabled" of "Submit" will be removed.

Here's the programming. There are two bugs that stand out in no way.

1, Once filled in or checked, it does not return to disabled even if it is deleted.

2、If you choose checkbox first, you can, disabled is not removed by filling in text, email,.

Please help us with fixes to the buggy parts and other movable Javascript solutions.

<form action="" method="POST">
<input type="text" id="txt" name="aaa" required onchange="manage(this)" />
<input type="email" id="ama" name="email" required onchange="manage(this)"/><br>

<label><input type="checkbox" name="sample[]" value="1" onchange="manage(this)">aaa1</label><br>
<label><input type="checkbox" name="sample[]" value="2" onchange="manage(this)">bbb2</label><br>
<label><input type="checkbox" name="sample[]" value="3" onchange="manage(this)">ccc3</label><br>
<label><input type="checkbox" name="sample[]" value="4" onchange="manage(this)">eee4</label><br>

<input type="submit" id="sager" value="O.K." disabled>
<input type="reset" value="Reset"></input>
</form>

<script>
function manage() {
  const txtJAB = document.getElementById('txt');
  const amaJAB = document.getElementById('ama');
  const submJAB = document.getElementById('sager');
  const chareJAB = document.querySelectorAll('input[name="sample[]"]:checked');

  if (txtJAB.value != '')
  if (amaJAB.value != '')
  if (chareJAB.length === '') {
    submJAB.disabled = true;
  }
  else {
    submJAB.disabled = false;
  }
}
</script>



unable to get input value of a single checkbox in typescript

I have a single input checkbox, from which I need pass the checkbox status true or false to backend. I can see the value change from console when check and uncheck the box. however, failed to get it.

<div class="d-flex justify-content-center">
  <input type="checkbox" class="checkbox" id="color" [checked]="picture.isColor" #color="ngModel" [ngModel]="checked" (click)="setColor(picture.id, color)">&nbsp; <span style="color: #008CBE;">set color</span>
</div>
setColor(id, color) {
  console.log(id);
  console.log(color.control);
  console.log(color.value);
}

console results: the picture id is as expected. The console does contains the value as in below screenshot. however, I got undefined when try to log it as color.value.

Can anyone please help to get the value of the value, i.e., true?

enter image description here

Can anyone help to get the value of the value, i.e., true? What I got is undefined, why?




dimanche 25 septembre 2022

Increasing number in number input from checking a box in another?

I'm working on a DnD character creator and am trying to increase certain ability scores based on race. I have a checkbox input next to every race that looks like so:

          <td>
            <input
              type="checkbox"
              id="dragonbornRace"
              onchange="updateRace();"
            />
          </td>
          <td>Dragonborn</td>
        

I also already have a section for ability score that looks like this:

          <td>
            <input
              type="number"
              value="10"
              id="strScore"
              onchange="updateMods()"
            />
          </td>

My goal is to make it so that when dragonborn checkbox is checked, the strength increases by 2. So far I have this code, but it doesn't seem to work:

function updateRace() {
  var strScore = document.getElementById("strScore").value;
   if (document.getElementById("dragonbornRace").checked == true) {
strScore = strScore + 2;
 }
}

When I go to test, nothing occurs when I check the box. I am probably missing something obvious, but any help would be appreciated!




Google Sheets, pop up message based on cell value TRUE/FALSE

I am trying to get Google Sheets show a popup message whenever a cell changes from FALSE to TRUE. I have found a few ways of doing it using onEdit functions. The problem here is that the Cell in question does not really get edited, but rather changes value due to another set of cells meeting certain criteria. That means onEdit functions won't run when the value changes.

I tried this script, but it does nothing:

//popup message
function alertMessageYesNoButton() {
  var result = SpreadsheetApp.getUi().alert("Are you sure you want to send an alert about?", SpreadsheetApp.getUi().ButtonSet.YES_NO);
  SpreadsheetApp.getActive().toast(result);
}

function sendMessageYesNo(e){
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var cellValue = sheet.getRange(4, 17).getValue();

  if (cellValue == 'TRUE'){
    alertMessageYesNoButton();
  }else{}
}

If someone could come up with something that works, I would really appreciate it.




samedi 24 septembre 2022

Add a checkbox field in Woocommerce order products list

I have a shop that sells several products per order and I need to mark with a checkbox the products that have already been added to the basket that will be sent to the customer. It is a self verification that we have actually put the product in the basket, but I need it to be saved in the order as proof that the item has been shipped for possible future enquiries. Can somebody write this code for me? enter image description here




jQuery If checkbox in foreach loop is checked, include checkboxes and input values within that loop

I am creating a php form with a foreach loop which creates a checkbox with several other checkboxes and input fields within the foreach loop. The loop might repeat several times, creating several sets of checkboxes, however I only want to include the checked checkbox and associated fields, not all of those within every loop.

My code below is incorrect as it is gathering all of the data from every loop. I understand this is because the input fields are populated with data, so the data is added to the array.

I think I need to add an 'if' statement to my jQuery, but I'm not sure how? I have tried changing the jQuery line 'if (checkbox.is(":checked"))' with the below line of code without success.

if ($("input[data-name='servicetitle[]'").prop(":checked")) {

jQuery:

let values = [];
    
$("div[data-name='sup-checkbox-title[]'], div[data-name='sup-input[]'], div[data-name='sup-input-date[]'], div[data-name='sup-checkbox[]'], div[data-name='sup-input-costs[]']").each(function() {
            
const label = $(this).find('label');
const checkbox = $(this).find('input[type="checkbox"]');
const input = $(this).find('input[type="text"]');
const date = $(this).find('input[type="date"]');
            
if (checkbox.is(":checked")) {
   values.push(label.html(), checkbox.val());
}
            
if (input.val()) {
   values.push(label.html(), input.val());
}
                    
if (date.val()) {
   values.push(label.html(), date.val());
}
                    
});

PHP:

foreach ( $order->get_items() as $item_id => $item ) {

         // Main checkbox to check if selected
         echo '<div data-name="sup-checkbox-title[]">';
         echo '<label for="servicetitle">Service:</label><br>';
         echo '<input type="checkbox" id="servicetitle" data-name="servicetitle[]" value="' . $item->get_name() . '"><span>' . $item->get_name() .'</span><br>';
         echo '</div><br>';

         // Sub checkboxes and input fields to include in array if above checkbox checked
         echo '<div data-name="sup-input[]"><br>';
         echo '<label for="weightallowance">Weight Allowance Per Bin:</label><br>';
         echo '<input type="text" id="weightallowance" value="Weight1" ><br>';
         echo '</div><br>';

         echo '<div data-name="sup-input-date[]">';
         echo '<label for="servicestartdate">Service Start Date:</label><br>';
         echo '<input type="date" id="servicestartdate" class="sup-required"><br>';
         echo '</div><br>';

         echo '<div data-name="sup-checkbox[]">';
         echo '<label for="routenumberAln1">Route Number:</label><br>';
         echo '<input type="checkbox" id="routenumberAln1" value="Aln1" >Aln1<br>';
         echo '</div><br>';

         echo '<div data-name="sup-input-costs[]">';
         echo '<label for="supplierpriceperlift">Supplier Price Per Lift:</label><br>';
         echo '<input type="text" id="supplierpriceperlift" value="£16.75"><br>';
         echo '</div><br>';      

}



vendredi 23 septembre 2022

How to get value of checked children checkboxes from checked parent checkboxes in javascript

I have a list of dynamic checkboxes(parent checkboxes) that also have children checkboxes, i want to get only the selected children checkboxes of the selected parent checkboxes.

This is what i have tried:

i used document.querySelectorAll() to get all the checked parent checkboxes, i iterated through each of them using foreach loop, but for whatever reason, i can't seem to get array list of all the checked children checkboxes so i can iterate through them and get their values... this where am stuck. below is the code of what i have done

var test_names= document.querySelectorAll("input[class='g-t-l-p']:checked");

        test_names.forEach(function(test_name) {
            var testname = test_name.innerHTML;
            var parentdiv = test_name.parentElement.parentElement.parentElement;
            if(parentdiv != null || parentdiv != undefined) {
                console.log('parentdiv',parentdiv)
            var childtestbutton = parentdiv.lastElementChild;
            
                if(childtestbutton != null || childtestbutton != undefined) {
                    var childtestprof = parentdiv.lastElementChild.previousElementSibling.lastElementChild.lastElementChild.value;
                    var childtestchecked = parentdiv.lastElementChild.previousElementSibling.firstElementChild.firstElementChild;
                    
                    if(childtestchecked != null || childtestchecked != undefined) {
                        console.log(childtestchecked)
                        console.log(childtestchecked.checked)
                        if(childtestchecked.checked == true && childtestchecked.checked != null || childtestchecked.checked != undefined) {
                            console.log('lengtha',childtestchecked.nextElementSibling.innerHTML)
                            var nnc = document.querySelectorAll("input[class='c-g-t-l-p']:checked");
                            console.log('nnc',nnc)
                            // var array = []
                            // for (var i = 0; i < childtestchecked.length; i++) {
                            //   array.push(checkboxes[i].value)
                            // }
                            // console.log('button',childtestprof)
                            // console.log('childtestnames',childtestnames)   
                            
                        }
                    }else {
                        console.log('box not checked');
                    }
                    
                }
            }else {
                console.log('no parent div')
            }
        });

Below is an illustration and snippet; loop through checkboxes javascript

Thank you in anticipation of your response




How to validate at least one checkbox is checked in a loop in Laravel?

I'm trying to validate my checkbox from a loop, where at least one is checked and displays an error/alert or disable the submit button instead if there is no checkbox checked. I tried putting a required method inside my checkbox, but the checkbox is in a loop that's why it requires all to be checked. That's why I tried the script code below which I found on the internet but that doesn't seem to work for me.

Below is my code in blade form

      <form id="contact" action="" method="post" enctype="multipart/form-data">
      @csrf
<div class="row col-12">
        @foreach($data as $data)
                <div class="row sm-6 ml-4 mb-1" class="no-gutters" style="height:25px; width: auto;">
                    <p class='text-dark mr-2'><input type="checkbox" name="prod_name[]" value="" class="products product" onClick="checkTest()"/> </p>
                    <p class='text-dark'>Qty:</p><input style="width:80px; height:25px;" type="number" name="prod_qty[]" min="1" value="1" class="form-control ml-2">
                    <input type="hidden" name="product_fee[]" value="">
                    <input type="hidden" name="prod_id[]" value="">
            </div>
          @endforeach
        </div>
                <div class=" col-lg-12 mt-5">
                    <fieldset>
                    <button name="submit" type="submit" id="form-submit"  class="main-button-icon">Make A Reservation</button>
                    </fieldset>
                </div>
        </div>
</form>
<script>
    var minimumonechecked;
    var checkboxes = $('.products').lenght;
    function checkTest(xyz){
        minimumonechecked = false;
        for(i=0;i<checkboxes;i++){
            if($('product' + i).is(':checked')){
                minimumonechecked = true;
            }
        }
        console.log(minimumonechecked)

    };
</script>

This is also the code in my controller, other data such as names are also part of the form but I cut it out by focusing on the checkbox

 public function reservation(Request $request)
    {
        if(Auth::id()){
            $user_id=Auth::id();
            $products = '';
            $reserved_qty=0;
            $product_fee=0;
            $prod_id=0;
            $checked_array = $request->input('prod_name', []);
            $quantities = $request->input('prod_qty', []);
            $fees = $request->input('product_fee', []);
            $productid = $request->input('prod_id', []);
            foreach($checked_array as $value){
                $data = new reservation;
                $data->user_id=$user_id;
                $data->name=$request->name;
                $data->email=$request->email;
                $data->phone=$request->phone;
                $data->address=$request->address;
                $data->date=$request->date;
                $data->time=$request->time;
                $data->status="pending";

                $data->productz=$request->products="{$value}";
                $data->reserved_qty=$request->$reserved_qty="{$quantities[$value]}";
                $data->product_fee=$request->$product_fee=$fees[$value]*$quantities[$value];
                $data->prod_id=$request->$prod_id=$productid[$value];



                $data->save();

        }
                return redirect()->back();
        }else{
            return redirect('/login');
        }



jeudi 22 septembre 2022

Update user status to Active/Blocked from table in react

In the picture below, i wanted to select multiple or single users with checkbox and set their status to Active/Blocked but the code is not working properly.By selecteing multiple users with checkboxes i am able to delete but i have no idea how to push user status together with id inside array to change Active/Blocked status. If something not clear please ask. Can anyone help how to make request for BE and handle from BE to change status to Active/Blocked?
Here is my source code:

const Home = ({status, setStatus}) => {
  const token = localStorage.getItem("token");
  const [users, setUsers] = useState([]);
  const [isCheckAll, setIsCheckAll] = useState(false);
  const [isChecked, setisChecked] = useState([]);

  const handleDeleteUser = async () => {
    const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
      method: "DELETE",
      body: JSON.stringify(isChecked),
      headers: {
        "Content-Type": "application/json",
      },
    });
    if(response.status === 200){
      const data = await response.json()
      setUsers(users.filter(user => !data.find(row => row === user._id)))
    }
  };
 
 const handlecheckbox = (e) => {
    const { value, checked } = e.target;
    if (checked) {
      setisChecked([...isChecked, value]);
    } else {
      setisChecked(isChecked.filter((e) => e !== value));
    }
  }

  const handleSelectAll=()=> {
    setIsCheckAll(!isCheckAll);
    setisChecked(users.map(user => user._id));
    if (isCheckAll) {
      setisChecked([]);
    }
  }
}

isChecked is an array of selected user ids with checkbox. I dont know how to make request for BE to update user status.

return (
  <tbody>
              {users.map((user) => (
                <tr key={user._id}>
                  <td>
                    <Form.Group>
                      <Form.Check
                        type="checkbox"
                        value={user._id}
                        checked={isCheckAll ? isCheckAll : user.isChecked}
                        onChange={(e) => handlecheckbox(e)}
                      />
                    </Form.Group>
                  </td>
                  <td>{user._id}</td>
                  <td>{user.name}</td>
                  <td>{user.email}</td>
                  <td>{format(parseISO(user.lastLogin), 'EEEE, MMM. do - HH:mm')}</td>
                  <td>{format(parseISO(user.createdAt), 'EEEE, MMM. do - HH:mm')}</td>
                  <td>{isChecked.includes(user._id) ? status: "Active"}</td>
                </tr>
              ))}
            </tbody>
)

Here is schema of user in BE :

import mongoose from "mongoose";
const { Schema, model } = mongoose;
const userSchema = new Schema(
  {
    name: { type: String },
    email: { type: String, unique: true},
    password: { type: String },
    status: {type: String, enum:["Active", "Blocked"], default:"Active"},
    token: { type: String },
    lastLogin: { type: Date, default: Date.now},
  },
  { timestamps: true }
);
export default model("User", userSchema);

enter image description here




Deleted users disappearing after refreshing the page not real time in react

I wanted to select multiple users from table and delete them with real time . When i check db it is deleting selected users but from front end with react it is happening after refreshing the page. Can anyone help me? Here is my FE code:

const handleDeleteUser = async () => {
    const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
      method: "DELETE",
      body: JSON.stringify(isChecked),
      headers: {
        "Content-Type": "application/json",
      },
    });
    if(response.status === 200){
      const data = await response.json()
      for (let i = 0; i < data.length; i++) {
        const element = data[i];
        setUsers(users.filter((e) => e._id !== element))
        console.log("DELETED ELEMENT",element);
      }
    }
  };

BE code:

userRouter.delete("/deleteUsers", async (req, res, next) => {
  try {
    const selectedUsers = req.body;
    // HARD DELETE
    UsersModel.deleteMany(
      {
        _id: {
          $in: selectedUsers,
        },
      },
      function (err, result) {
        if (err) {
          res.status(404).send(err);
        } else {
          res.status(200).send(selectedUsers);
        }
      }
    );
  } catch (error) {
    next(error);
  }
});




mercredi 21 septembre 2022

How to Delete multiple user from table using checkbox in react and nodejs , mongoose

I am handling selected users id using checkbox in the table but when i send request to server to delete them all , i have no idea how to handle with nodejs using mongoose. Can anyone help me? Here is FE code:

const Home =()=> {
const [isChecked, setisChecked] = useState([]);
const handleDeleteUser = async () => {
    const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
      method: "DELETE",
      body: JSON.stringify(isChecked),
      headers: {
        "Content-Type": "application/json",
      },
    });
  };

  const handlecheckbox = (e) => {
    const { value, checked } = e.target;
    console.log(value);
    if (checked) {
      setisChecked([...isChecked, value]);
    } else {
      setisChecked(isChecked.filter((e) => e !== value));
    }
  };
 return (
           <tbody>
              {users.map((user) => (
                <tr key={user._id}>
                  <td>
                    <Form.Group>
                      <Form.Check
                        type="checkbox"
                        value={user._id}
                        checked={user.isChecked}
                        onChange={(e) => handlecheckbox(e)}
                      />
                    </Form.Group>
                  </td>
                  <td>{user._id}</td>
                  <td>{user.name}</td>
                  <td>{user.email}</td>
                  <td>{user.lastLogin}</td>
                  <td>{user.createdAt}</td>
                  <td>{user.status}</td>
                </tr>
              ))}
            </tbody>
 )
}

Here Nodejs code :

userRouter.delete('/deleteUsers', async(req,res,next)=> {
  try {
    const selectedUsers = req.body
   
  } catch (error) {
    next(error) 
  }
})




How can I achieve a checkbox, input text field, and extra-span label in the same field row

Hi everyone a newbie here, I'm trying to achieve the following effect but at instep, all I got is the following.

I'm trying to add some options we have a list of options where they can choose from the list they have a checkbox plus a name and input field for quantity text like 1,2,3 and so on, then there is a label for each price for the options they select but, here is where I got stuck! I'm a newbie trying to learn to code I'm using bootstrap and twig, I also try to get the text field active when the checkbox is selected but I couldn't do it.

Any help for a newbie is highly appreciated.

Source Code

.form-group,
.checkbox {
  display: inline-block;
}

.name {
  margin-bottom: 2px;
  background: #66bb6a !important;
  font-size: 1.2rem !important;
  color: #F7F5F5 !important;
  text-align: center;
  font-weight: 400;
  padding: 10px;
  border: 1px solid #ddd !important;
  text-shadow: 1px 0px 3px #6F6F6F;
}

.price {
  background: #66bb6a !important;
  font-weight: 400;
  padding: 10px;
  color: #fff !important;
  border-color: #66bb6a !important;
  transition-property: all;
  transition-duration: 0.3s;
  -webkit-transition-property: all;
  -webkit-transition-duration: 1s;
}
<form role="form">

  <div class="row">
    <div class="form-group">
      <div class="checkbox name">
        <label>
<input type="checkbox" value="closedqueue">Option 1</label>
      </div>
      <input type="text" class="form-control" id="queuename">
      <label for="queuename" class="price">$2.99</label>
    </div>
  </div>

  <div class="row">
    <div class="form-group">
      <div class="checkbox name">
        <label>
<input type="checkbox" value="closedqueue">Option 2</label>
      </div>
      <input type="text" class="form-control" id="queuename">
      <label for="queuename" class="price">$2.99</label>
    </div>
  </div>

  <div class="row">
    <div class="form-group">
      <div class="checkbox name">
        <label>
<input type="checkbox" value="closedqueue">Option 3</label>
      </div>
      <input type="text" class="form-control" id="queuename">
      <label for="queuename" class="price">$2.99</label>
    </div>
  </div>
</form>

Current Output: instep, all I got is the following

Expected Output:
I like to achieve the following




mardi 20 septembre 2022

Checkbox Issue in tableview cell

I have a multiple checkbox in tableview cell and total number of cell 4,i want to select one checkbox at one time and all check box is unselect if i select any one of check box and also one button in table view cell button are also disable of other cell so how i implement this logic.here i implement image check and uncheck logic

func setupData(plansModel: [Plans], mainRowIndex: Int, selctedPlan: Int, isAllUnselected: Bool){
    self.plansModel = plansModel
    indexMain = mainRowIndex
    selectedPlanId = selctedPlan
    self.isAllUnselected = isAllUnselected
    self.changePlanBtn.isHidden = isAllUnselected
    
    priceTableView.reloadData()
}

i take this variable for data and manage checkbox




Disabling a checkbox if a condition is met

I'm pretty new to Javascript and I have an exercise containing a form and some validation checks, I have a few inputs such as name, price, and a checkbox and I'm trying to disable the checkbox based on the price input (disable it if it's above 200 and re-enable it if it's less than 200), and at the moment it's not working, I'll really appreciate suggestions.

That's the Javascript code I've written:

document.addEventListener("DOMContentLoaded", function () {
  const price = document.querySelector("[name='purchasePrice']");
  price.addEventListener("change", checkPrice);
  function checkPrice() {
    if (price > 200) {
      document.querySelector("[name='chkBx']").disabled = true;
    } else {
      document.querySelector("[name='chkBx']").disabled = false;
    }
  }
});

and this is the HTML code:

<div class="item-div">
    <label>
      Purchase Price
      <input
        class="inputClass"
        type="number"
        name="purchasePrice"
        min="1"
        required
      />
    </label>
  </div>
  <div class="item-div">
    <label>
      Add Charge
      <input type="checkbox" name="chkBx" />
    </label>
  </div>



Need solution to avoid repeating very similar code 25 times

I have a useform with 6 questions where the user must select an option using a tickbox. The options available to users varies depending on the question so some questions have 5 options, others have less. Therefore the number of tickboxes varies. I've names the tickboxes CB1 to CB25 and currently I have a sub routine for every tickbox and I'm looking for a way of having one sub routine that covers all options. The existing code for each tickbox is as below.

Sub Cb1_Click()

If Range("d27").Value = 0 Then

If cb1 = True Then
cb2 = False
cb3 = False

Controls("F_selected").Value = Controls("F_prior").Value

    If Controls("F_selected").Value <> "" And Controls("F_selected").Value <> "n/a" And Controls("F_prior").Value <> "" And Controls("F_prior").Value <> 0 And Controls("F_prior").Value <> "0.00" And Controls("F_prior").Value <> "0.00%" Then
   
    Controls("F_change").Value = (Format(Controls("F_selected").Value, "standard") / Format(Controls("F_prior").Value, "standard") - 1)
    
    Else
    
    Controls("F_change").Value = ""

    End If

    Controls("F_change").Value = Format(Controls("F_change").Value, "percent")

    Range("L11") = Controls("F_selected").Value

update_form

End If

End If


End Sub

Note: the below example has 3 clickboxes but some of the questions have 5.

As a first port of call, I've tried to create a standard sub routine and a call to replicate the above code. This is what I have:

    Sub checkboxchg(var0 As Object, var1 As Object, var2 As Object, var3 As Object, var4 As String, var5 As String, var6 As String)
    
    Sub var1_Click()
    
    
    If Range("d27").Value = 0 Then
    
    If var1 = True Then
    var2 = False
    var3 = False
    
    Controls(var4).Value = Controls(var5).Value
    If Controls(var4).Value <> "" And Controls(var4).Value <> "n/a" And Controls(var5).Value <> "" And Controls(var5).Value <> 0 And Controls(var5).Value <> "0.00" And Controls(var5).Value <> "0.00%" Then
   
    Controls(var6).Value = (Format(Controls(var4).Value, "standard") / Format(Controls(var5).Value, "standard") - 1)
    
    Else
    
    Controls(var6).Value = ""

    End If

    Controls(var6).Value = Format(Controls(var6).Value, "percent")

    Range("L11") = Controls(var4).Value

update_form

End If

End If

End Sub

End Sub

I use the following Call to reproduce the original code but I'm getting errors.

Call checkboxchg(cb1, cb2, cb3, "ll_f_m_sel", "ll_f_m_prior", "ll_f_m_chg")

I think perhaps I'm defining the cb1_click() incorrectly but even when I change this I'm getting errors elsewhere so I'm not sure what's happing. Any help would be appreciated.




Mat-checkbox change event is not triggering function

I have this mat select with checkboxes. Inside, once I press the first checkbox I want the function timeSlotChecked() to be called, but it is not. What am I doing wrong?

<mat-select class="mat-select-height stop-settings" placeholder="Settings" name="orderStop">
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isTimeSlotRequired" [checked]="order.orderStops[index].isTimeSlotRequired" (change)="timeSlotChecked(order.orderStops[index])" name="isTimeSlot">Time slot required</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isOnSiteStop" name="isOnSiteStop">On site stop</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].autoGenerateFeedback" name="isAutoGenerated">Auto-generate feedback</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isNeutral" name="isNeutral">Is neutral</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isApproximationDate" name="isApproximationDate">Is approximation date</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isFridayLoadUnloadSurcharge" name="isFridayLoadUnloadSurcharge">Friday (un)load surcharge</mat-checkbox><br>
  <mat-checkbox [disabled]="isStopViewMode(stop) || disableSettings" class="mat-checbox-alignment" [(ngModel)]="order.orderStops[index].isMondayLoadUnloadSurcharge" name="isMondayLoadUnloadSurcharge">Monday (un)load surcharge</mat-checkbox>
</mat-select>``


public timeSlotChecked(stop: OrderStop) {
  if (stop.isTimeSlotRequired) {
    this.timeSlotChanged(stop);
  }
}



lundi 19 septembre 2022

Sort a whole row based on a checkbox on appscript

hope you are doing well.

I'm trying to sort a row that contains 18 cells based on checkboxes. Each checkbox assigns a task to each person and I basically would like to group people who are working on each task.

People with tasks

As you can see in the screenshot it's difficult to identify each task. I would like that all the people who are working on the "new" task to be together and not separated and People who are working on the "Open" task to be in a group below the "New" task

Another problem I have is that I'm getting these names (column A) from a formula based on another list.

Do you think is there a way to this action works? or it's not possible? I found this code based on other values but I'm not sure if I could modify it to achieve the action I want. This is the code:

function autoSort(e) {
  
  const row = e.range.getRow()
  const column = e.range.getColumn()
  const ss = e.source
  const currentSheet = ss.getActiveSheet()
  const currentSheetName = currentSheet.getSheetName()

  if(!(currentSheetName === "Assignation" && column === 2 && row >= 2)) return

  const ws = ss.getSheetByName("Assignation")

  const range = ws.getRange (2,2, ws.getLastRow()-1,7)

  range.sort({column: 1, ascending: false})
  
}

function onEdit(e){

  const row = e.range.getRow()
  const column = e.getRange.getColumn()

  if(!(column === 1 && row >= 2)) return

  autoSort()
}

Also, this is the sheet I'm using, it's a copy so you can modify it as you want.

https://docs.google.com/spreadsheets/d/1f5Mu2SKPAYKC9UcpDOkGdtS6JeFDHcsqPMmuZyz-zWA/edit?usp=sharing

I hope anyone can help me with this. Thank you!




Reactjs - Adding check all/uncheck all checkboxes

I'm new and learning ReactJS and I'm trying to add a checkbox that will check/uncheck all of my other checkboxes. When I click on the "All" checkbox, the screen for the GUI goes white. The other checkboxes work as normal and are generated and assigned to data that is read from a DB based on data name. The handleAllToggle code is based on one that I found else where on here: https://codesandbox.io/s/vvxpny4xq3?file=/src/index.js.

Please help.

import toggleItemLayer

this.state = {checkAll: true,
   itemList: [],
   fruitOrNot: new Map(),
   checkedItems: new Map()}

getItemList() {
   let url = myDbUrl;
   fetch(url)
      .then(resp => resp.json())
      .then(items => {
         this.setState({ itemList: items })
         for (let i = 0; i < this.state.itemList.length; i++) {
            if (this.state.itemList[i].name === 'Fruit') {
               this.setState({ fruitOrNot: this.state.fruitOrNot.set(this.state.itemList[i].name, 'Fruit') })
            } else {
               this.setState({ fruitOrNot: this.state.fruitOrNot.set(this.state.itemList[i].name, 'Not') })
            }
      })
      .catch(error => {
         console.log(error)
      });
}

handleItemToggle = async (event) => {
   let isChecked = event.target.checked;
   let item = event.target.value;
   this.setState({ checkedItems: this.state.checkedItem.set(item, isChecked) })
   
   let index = this.state.itemList.findIndex(element => element.name === item)
   await toggleItemLayer(this.sate.itemList[index], isChecked)
}

handleAllToggle = async (event) => {
   let isAllChecked = event.target.checked;
   let checkedItems = this.state.checkedItems;

   this.setState(prevState => {
      let list = prevState;
      this.state.checkAll = isAllChecked;
      list = list.map(checkedItems => ({ ...checkedItems, isChecked: isAllChecked}));
      this.state.checkAll = list.every(item = item.isChecked);
   })
}

render() {
   return (
      <tr>
         <td style=><input
         type="checkbox"
         value="checkAll"
         defaultChecked={this.state.checkAll}
         checked={this.state.checkedSource}
         onChange={this.handleAllToggle}
         /></td>
         All
      </tr>

      this.state.itemList.map((item, index) => (
         <tr key={item.name}>
            <td style=><input
               type="checkbox"
               id={index}
               value={item.name}
               onChange={this.handleItemToggle}
               checked={this.state.checkedItems.get(item.name) === undefined ? true : this.state.checkedItems.get(item.name)}
            /></td>

        {/*additional properties code*/}

         </tr>   
   )
}



samedi 17 septembre 2022

Checkboxes. Blazor. ArgumentException: The provided expression contains a SimpleBinaryExpression which is not supported

Continuation from previous question. The solution provided by Lex for previous question worked fine and I've used that format for this task. However, I wanted to take it slightly further - also obtain the results from the user clicking checkboxes but this time each checkbox result would be stored in an array declared within the class. So I guess one layer deeper as it were. I don't know why, but when I nest a loop to cycle through each checkbox, I get the below error. If I write each of them out it works but of course I want it to be for any size bool array so only a loop would work.

ArgumentException: The provided expression contains a SimpleBinaryExpression which is not supported. FieldIdentifier only supports simple member accessors (fields, properties) of an object.

So my questions are, why do I get this error and is there an obvious workaround?

@page "/counter"

<div>
<EditForm Model="this.e">
    @for (int i = 0; i < this.e.Questions.Count; i++)
    {
            {
                <div>
                    @for (int j = 0; j < 1; j++) @*so this should produce four 
 checkboxes*@
                    {
                        <label>
                        <InputCheckbox @bind-Value="this.e.Questions[i].Answers[j] " />
                           A question would go above and here would be 1+ answer.
                        </label>
                    }
                </div>
            }
        }
</EditForm>
</div>
<div>

 Gives access to results like:
@e.Questions[1].Answers[0] @*first checkBox ticked, true/false*@
@e.Questions[1].Answers[1]
@e.Questions[1].Answers[0]
@e.Questions[1].Answers[1]

</div>

@code
{
    public class EditFormModel
    {
    public List<Question> Questions { get; set; }
}

public class Question
{
    public string? checkBoxtext { get; set; }

    public bool[] Answers { get; set; }
}


public EditFormModel e = new()
{
        Questions = new List<Question>
    {
        new()
        {
            checkBoxtext = "What is the capital of France?", // Two answers could be London, Paris
            Answers = new bool[] {
                true, true
            }
        },
        new()
        {
            checkBoxtext = "What is the capital of Scotland?", // Answers could be Edinburgh, Paris, Sydney
            Answers = new bool[] {
                true, true, true
            }
        }
    }
};

}




vendredi 16 septembre 2022

Pass checkbox and text input to url for fetch for displaying data back to html

I need to pass text values and checkbox values to a URL for a fetch request when the button is pressed and then display it on my HTML using basic Javascript.

So far I have been able to pass on text values but not the checkboxes. They seem to always be "on"?

html
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="checkbox" class="form-check-input" id="number" value="True">Numbers
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="checkbox" class="form-check-input" id="character" value="ture"> Special characters
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="checkbox" class="form-check-input" id="uppercase" value="ture">Uppercase
      </label>
    </div>
    <div class="passwordbox">
      <input id="passlen" class="pass-len-box" placeholder="Enter password length">
      <button class="generatorPass" id="genratorPass">Generate</button>
      <br>
      <p id="dispPassword"></p>
    </div>
  </div>
JS
document.querySelector("#genratorPass").addEventListener("click", () => {
  const user_input_text = document.querySelector("#passlen");
  const user_input_number = (document.getElementById("number").value = "True");
  const user_input_character = (document.getElementById("character").value =
    "True");
  const user_input_uppercase = (document.getElementById("uppercase").value =
    "True");
  request(
    user_input_text,
    user_input_number,
    user_input_character,
    user_input_uppercase
  );
});
const passworldEl = document.getElementById("dispPassword");

request = (
  user_input_text,
  user_input_number,
  user_input_character,
  user_input_uppercase
) => {
  let url = `https://passwordinator.herokuapp.com?len=${user_input_text.value}&num=${user_input_number.value}&char=${user_input_character.value}&caps=${user_input_uppercase.value}`;
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data.data);
      document.querySelector("#dispPassword").innerHTML = data.data;
    });
};

Passing info to a password generator https://github.com/fawazsullia/password-generator

Code example fetch('https://ift.tt/rtodGKY) .then((res)=> res.json()) .then((data) => console.log(data))

fetch('https://ift.tt/uPq8McH) On resolving generates a 18 digit password with characters, alphabets, uppercase letters and numbers




jeudi 15 septembre 2022

In Google Sheets I am trying to put columns of text together into one cell, ignoring blank cells, with If statements

To begin, the spreadsheet is here.

I have "Sheet1" that has columns A-I titled with movie genres and descriptors below. On "Sheet2" I have each genre next to a checkbox. The end goal is to be able to select any and all of the genres that apply and have the descriptors put together into one cell (Sheet2!A5) separated by a comma. I want to include the entire column of each genre ignoring the blank cells so I can add and take away descriptors as needed without breaking anything.

Below is the expected result if all are selected enter image description here

I am very new to the world of functions and have spent hours at this point trying to browse all the forums and various how to videos, but I haven't been able to find anything close enough to work.

Below is what I tried. enter image description here

I have updated the permissions for anyone with the link to edit. Here is the link once more. Any help is GREATLY appreciated. Thank you in advance for your time and efforts. I know how important those are. : )




How can I retrieve multiple checkbox values from checkboxes added dynamically in Blazor when using EditForm and/or @bind-Value?

I am trying to find out how to get checkbox values when checked in a form in Blazor.

I can see from this post (.NET Core Blazor: How to get the Checkbox value if it is checked? ), how to do it for a single value:

a solution to the above post gave me something like this:

<InputCheckbox @bind-Value="@b.myBool" checked="@(@b.myBool?"checked":null)" />CheckMe

and that works ok. I just create a class with a boolean property (say myBool) and declare an instance of the class with that property set to false. Then when the form is submitted, I have access to b.myBool, it is changed by the user.

However, I need to do it for multiple Checkboxes that will be added dynamically (the text next to the checkbox, here CheckMe[z], would also change but that's not an issue).

So, I figured a for/foreach loop with something like:

<InputCheckbox @bind-Value="@b.myBool[i]" checked="@(@b.myBool[i]?"checked":null)" />CheckMe[z]

and in the class, I'd just need to replace with a list property e.g.: List myBools.

Unfortunately this and lots of other variations I've tried don't work, for many many different reasons.

Thanks in advance for advice/suggestions/links.




Checkbox and JSP

I am using two checkboxes in jsp named "physician" and "pharmacist". So, when user checks first one, the data should be inserted in physician table and when checks the second one, the data should be inserted in pharmacist table. I know how to write the query of insert. But, how do I use "if condition" for this?




mercredi 14 septembre 2022

Dropdown toggle is set to off when an select all option is clicked inside

As mentioned in the title, my drop down button renders a list of option that stays open when any of the options are clicked. Recently I added a select all option which now selects all the options available in the drop down button but now also toggles close for the option menu itself. I think it has to with the

  const handleClickOutside = e => {
    e.stopPropagation();
    if (!dropdownRef?.current?.contains(e.target)) setIsOpen(false);
  };

as if I comment out the if statement, the drop down menu stays open after clicking select all though I don't know why. Is it considering the fact that the menu disappears to be outside the drop down menu?

export const DropdownButton = ({ handleOnClick, count = '' }) => {
  return (
    <div className={styles.button} role="button" onClick={handleOnClick}>
      <div className={styles.buttonInner}>
        <span>
          <i className="material-icons icon-layers" />
        </span>
        <p>{count}</p>
      </div>
    </div>
  );
};

DropdownButton.propTypes = {
  handleOnClick: PropTypes.func.isRequired,
  count: PropTypes.string,
};

/**
 *
 * @param data {Array}
 * @param handleCheckboxOnChange {Function}
 * @param handleSetThisGroupOnly {Function}
 * @param handleSetLocalStorage
 * @param showRememberFilterButton
 * @returns {*}
 * @constructor
 */
const GroupQuickFilter = ({
  data = [],
  handleCheckboxOnChange,
  handleSetThisGroupOnly,
  handleSetLocalStorage,
  showRememberFilterButton,
  allSelected,
}) => {
  const dropdownRef = useRef(null);

  const [isOpen, setIsOpen] = useState(false);
  const [count, setCount] = useState('');
  const [isOnlyOneLeft, setIsOnlyOneLeft] = useState(false);

  // handles calculating count
  useEffect(() => {
    const total = data.length;
    const enabled = data.filter(d => d.enabled).length;

    if (enabled === 1) setIsOnlyOneLeft(true);
    else if (enabled > 1) setIsOnlyOneLeft(false);

    if (total) setCount(`${enabled} / ${total}`);
  }, [data]);

  // handles auto-closing
  useEffect(() => {
    window.addEventListener('click', handleClickOutside);
    return () => {
      window.removeEventListener('click', handleClickOutside);
    };
  }, []);

  const handleClickOutside = e => {
    e.stopPropagation();
    if (!dropdownRef?.current?.contains(e.target)) setIsOpen(false);
  };

  const toggleDropdown = e => {
    e.stopPropagation();
    setIsOpen(!isOpen);
  };

  //const open = () => {setIsOpen(isOpen)};
  
  // const checkChange = () => handleCheckboxOnChange('checkall');
  // const setDropOpenChange = (e) => toggleDropdown(e);

  // const changeFunction = (e) => {
  //   checkChange();
  //   setDropOpenChange(e);
  // }

  const enabledOptions = data.filter(group => group.enabled);

  return (
    <div className={styles.wrapper} ref={dropdownRef}>
      <DropdownButton handleOnClick={(e) => toggleDropdown(e)} count={count} />
      <ul className={styles.dropdownRow}>
        <div
          className={
            showRememberFilterButton ? styles.rememberFiltersOpen : null
          }
        >
          <AnimateHeight height={isOpen ? 'auto' : 0} duration={250}>
            <div className={styles.checkboxWrapper}>
              {(enabledOptions.length === data.length) ? null : (
                <Checkbox
                  color="primaryLight"
                  onChange={(isOpen) => handleCheckboxOnChange('checkall', setIsOpen(isOpen))}         
                  checked={allSelected}
                  label={<span className={styles.allSelected}>All Groups</span>}
                />
              )}
              {data.map(d => (
                <li key={d.id}>
                  <Checkbox
                    color="primaryLight"
                    onChange={() => handleCheckboxOnChange(d.id)}
                    checked={d.enabled || false}
                    disabled={d.enabled && isOnlyOneLeft}
                    label={
                      <span className={styles.checkboxLabel}>
                        {capitalizeFirstLetter(d.name)}
                      </span>
                    }
                  />

                  <span className={styles.spacer} />
                  <Anchor
                    tag="a"
                    role="button"
                    className={styles.thisGroupOnly}
                    onClick={() => handleSetThisGroupOnly(d.id)}
                  >
                    This Group Only
                  </Anchor>
                </li>
              ))}
            </div>
            {showRememberFilterButton && (
              <div className={styles.rememberContainer}>
                <span className={styles.border} />
                <div
                  className={styles.rememberButton}
                  role="button"
                  onClick={handleSetLocalStorage}
                >
                  Remember Groups Settings
                </div>
              </div>
            )}
          </AnimateHeight>
        </div>
      </ul>
    </div>
  );
};



How to adjust the size of checkboxes in treeview tkinter

I have been building a simple program where there is a number of tags on the right side of the window. I was wondering if there is a way that I can make my checkboxes a bit larger so that some of my users can tick those boxes more easily.

Here is my code.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()


class CbTreeview(ttk.Treeview):
    def __init__(self, master=None, **kw):
        kw.setdefault('style', 'cb.Treeview')
        kw.setdefault('show', 'headings')  # hide column #0
        ttk.Treeview.__init__(self, master, **kw)
        # create checheckbox images
        self._im_checked = tk.PhotoImage('checked',
                                         data=b'GIF89a\x0e\x00\x0e\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x0e\x00\x0e\x00\x00\x02#\x04\x82\xa9v\xc8\xef\xdc\x83k\x9ap\xe5\xc4\x99S\x96l^\x83qZ\xd7\x8d$\xa8\xae\x99\x15Zl#\xd3\xa9"\x15\x00;',
                                         master=self
                                         )
        self._im_unchecked = tk.PhotoImage('unchecked',
                                           data=b'GIF89a\x0e\x00\x0e\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x0e\x00\x0e\x00\x00\x02\x1e\x04\x82\xa9v\xc1\xdf"|i\xc2j\x19\xce\x06q\xed|\xd2\xe7\x89%yZ^J\x85\x8d\xb2\x00\x05\x00;',
                                           master=self)
        style = ttk.Style(self)
        style.configure("cb.Treeview.Heading", font=(None, 13))
        # put image on the right
        style.layout('cb.Treeview.Row',
                     [('Treeitem.row', {'sticky': 'nswe'}),
                      ('Treeitem.image', {'side': 'right', 'sticky': 'e'})])

        # use tags to set the checkbox state
        self.tag_configure('checked', image='checked')
        self.tag_configure('unchecked', image='unchecked')
        self.tag_configure('evenrow', background='lightblue')
        self.tag_configure('oddrow', background='gray')


    def tag_add(self, item, tags):
        new_tags = tuple(self.item(item, 'tags')) + tuple(tags)
        self.item(item, tags=new_tags)

    def tag_remove(self, item, tag):
        tags = list(self.item(item, 'tags'))
        tags.remove(tag)
        self.item(item, tags=tags)

    def insert(self, parent, index, iid=None, **kw):
        item = ttk.Treeview.insert(self, parent, index, iid, **kw)
        print(kw['values'][0])
        if kw['values'][0] % 2 == 0:
            self.tag_add(item, (item, 'evenrow'))
        else:
            self.tag_add(item, (item, 'oddrow'))
        if kw['values'][2] is True:
            self.tag_add(item, (item, 'checked'))
        else:
            self.tag_add(item, (item, 'unchecked'))


        self.tag_add(item, (item, 'unchecked'))
        self.tag_bind(item, '<ButtonRelease-1>',
                      lambda event: self._on_click(event, item))

    def _on_click(self, event, item):
        """Handle click on items."""
        if self.identify_row(event.y) == item:
            if self.identify_column(event.x) == '#4': # click in 'Is Lv 90' column
                # toggle checkbox image
                if self.tag_has('checked', item):
                    self.tag_remove(item, 'checked')
                    self.tag_add(item, ('unchecked',))
                else:
                    self.tag_remove(item, 'unchecked')
                    self.tag_add(item, ('checked',))



tree = CbTreeview(root, columns=("No.", "Character Name", "Leveled up to 90", "Is Lv 90"),
                  height=20, selectmode="extended")

tree.heading('No.', text="No.", anchor=tk.E)
tree.heading('Character Name', text="Character Name", anchor=tk.E)
tree.heading('Leveled up to 90', text="Leveled up to 90", anchor=tk.E)
tree.heading('Is Lv 90', text="Is Lv 90", anchor=tk.E)

tree.column('#1', stretch='no', minwidth=0, width=30, anchor=tk.E)
tree.column('#2', stretch='no', minwidth=0, width=150, anchor=tk.E)
tree.column('#3', stretch='no', minwidth=0, width=0, anchor=tk.E)
tree.column('#4', stretch='no', minwidth=0, width=100, anchor=tk.E)


tree.pack(fill='both')

tree.insert('', 'end', values=(0, 'Amber', True, ''))
tree.insert('', 'end', values=(1, 'Jean', False, ''))
tree.insert('', 'end', values=(2, 'Lisa', True, ''))
tree.insert('', 'end', values=(3, 'Keqing', True, ''))
tree.insert('', 'end', values=(4, 'Ganyu', True, ''))
tree.insert('', 'end', values=(5, 'Barbara', False, ''))
tree.insert('', 'end', values=(6, 'Paimon', True, ''))
tree.insert('', 'end', values=(7, 'Lumine', True, ''))
tree.insert('', 'end', values=(8, 'Noelle', True, ''))
tree.insert('', 'end', values=(9, 'Diluc', False, ''))
tree.insert('', 'end', values=(10, 'Ayaka', False, ''))
tree.insert('', 'end', values=(11, 'Yae Miko', True, ''))
tree.insert('', 'end', values=(12, 'Raiden Shogun', True, ''))
tree.insert('', 'end', values=(13, 'Ayato', True, ''))
tree.insert('', 'end', values=(14, 'Eula', True, ''))
tree.insert('', 'end', values=(15, 'Hu Tao', True, ''))
tree.insert('', 'end', values=(16, 'Yoimiya', True, ''))

root.mainloop()

Here is what I have got so far. Current size of checkboxes




angular material table post selected items to modal

How can I pass a list of selected items to dialog? When I pass 'selection.selected' I get [object Object]. I would like to display the selected items as a list in the dialog.

openDialog() {
this.dialog.open(DialogDataExampleDialog, {
  data: {
    selected: this.selection.selected,
  },
});

}




PHP loop over checkbox issue

I get information from the database. That I list using a while loop. With this while loop, I list diseases with checkboxes. Unable to select checkboxes.

Code:

<li class="form-line" data-type="control_checkbox" id="id_5">
        <label class="form-label form-label-top form-label-auto" id="label_5" for="input_5"> Do you have any of the followings? (select all that apply) </label>
        <div id="cid_5" class="form-input-wide" data-layout="full">
          <div class="form-single-column" role="group" aria-labelledby="label_5" data-component="checkbox">
            
   <?php 
// Create connection
$conn = mysqli_connect("localhost", "root", "", "covidtmsdb");
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
   
$sql7 = "SELECT * FROM tblhealth_issues WHERE Category='disease'";
$result7 = mysqli_query($conn, $sql7);

if (mysqli_num_rows($result7) > 0) {
    // output data of each row
    while($row7 = mysqli_fetch_assoc($result7)) {
                
                ?>
<span class="form-checkbox-item" style="clear:left">
              <span class="dragger-item">
              </span>
             <input type="checkbox" aria-describedby="label_5" class="form-checkbox" id="<?php  echo $row7['Question'];?>" name="ques[]" value="<?php  echo $row7['Symptoms'];?>" />
              <label id="label_input_5_0" for="input_5_0"> <?php  echo $row7['Symptoms'];?></label>
            </span>
        <?php             
    }
} else {
    echo "0 results for Q7";
}

mysqli_close($conn);
?>     
          </div>
        </div>
      </li>

Output: enter image description here




mardi 13 septembre 2022

Replace tick from mat-pseudo-checkbox with the mat-checkbox tick

If I want to create a list of checkboxe's in Material design I can use mat-list-option like so

<mat-selection-list>
  <mat-list-option
  *ngFor="let option of options"
  >
    
  </mat-list-option>
</mat-selection-list>

By default it seems to use the mat-pseudo-checkbox in this case. The tick from the mat-pseudo-checkbox looks different than from the mat-checkbox

Material Checkbox

Material Pseudo Checkbox

I need the inside of the mat-pseudo-checkbox to look like a "normal" mat-checkbox when checked.

I have tried using mat-pseudo-checkbox in the specific CSS file but haven't found a way to at least change the tick. It basically didn't change anything.

Could you please give me a hint or an example how I could archive this.




lundi 12 septembre 2022

Run a python function depends on the checkbox

I'm working on a python project and I want to call a function if a checkbox was checked. For expample if the yes checkbox was checked the first function will be called. I made this code, but it always calls the second function even if I checked the yes checkbox. I don't know what the issue. Any help is highly appreciated. this is my html :

<input type="checkbox" id="vehicle1" name="mycheckboxname" value="yes">
<label for="vehicle1"> Without comments</label><br>
<input type="checkbox" id="vehicle2" name="mycheckboxname" value="no">
<label for="vehicle2"> With comments</label><br>

And this is my view.py

def datatable_view(request):   
    if request.method =='POST':
        form = Scraping(request.POST)
        if form.is_valid():
            mylist=request.POST.getlist('mycheckboxname')
            if 'yes' in mylist: 
                subject=form.cleaned_data['subject'] 
                scrap(subject)
                client = pymongo.MongoClient("mongodb://localhost:27017/")
                db= client["db2"]
                col = db[subject]
                products = col.find()
                context = {'products' : products}
                return render(request,'datatable.html', context)
            else:
                subject=form.cleaned_data['subject']
                hello(subject)    
                client = pymongo.MongoClient("mongodb://localhost:27017/")
                # use variable names for db and collection reference
                db= client["db2"]
                col = db[subject]
                products = col.find()
                context = {'products' : products}
                #open datatable html and display all the data from database
                return render(request,'datatable.html', context)
    return



Javascript Checkbox - Pushing an Array to Empty Array through click event

I have this mini checkbox feature that I wanted to implement on a web app that I am developing.

The goal is once the user clicked the checkbox particular lesson, it will be added to the vocabulary array.

Here's the code:

const lessonOneEl = document.getElementById("lessonOne");


let vocabulary = [];
const lessonOne = [
    {"ἀγάπη, ἡ": "love"},
    {"γῆ ἡ": "earth, land, ground (geology)"},
    {"ζωή ἡ": "life (zoo, zoology)"},
    {"φωνή, ἡ ": "voice, sound (phonetics, phonograph, phone)"},
    {"ἀλήθεια, ἡ": "truth"},
    {"ἁμαρτία, ἡ":  "sin (hamartiology—the theological study of sin)"},
    {"βασιλεία, ἡ" : "kingdom, reign (basilica)"},
    {"δόξα, ἡ" : "glory, majesty (doxology)"},
    {"ἐκκλησία, ἡ" : "congregation, assembly, church (ecclesiastical)"},
    {"ἡμέρα, ἡ" : "day (ephemeral, “for a day”)"},
    {"καρδία, ἡ":  "heart (cardiologist)"},
    {"δέ" : "and, but, now"},
    {"καί" : "and, even, also"},
    {"μέν" : "on the one hand, indeed"},
    {"ὁ, ἡ, τό" : "the"}
]


const lessonOneEl = document.getElementById("lessonOne");

lessonOneEl.addEventListener('click', () => {
    if(lessonOneEl.checked) {
        console.log("lessons added");
        vocabulary.push(lessonOne);
    }
})
<input type="checkbox" name="lessons" id="lessonOne">
<label for="lessonOne">Lesson 1</label>

For some reason, upon testing, when I clicked on lessonOneEl, it logs "lessons added" but not pushing lessonOne to the vocabulary array.

I wonder what am I missing. I search the web, and I learned different ways to use Javascript checkbox but I can't seem to see what am I missing.

Note: When the code below is outside the event handler, it automatically pushes the lessonOne array to the vocabulary array (which is expected).

vocabulary.push(lessonOne);



dimanche 11 septembre 2022

PySide6 QTreeWidget Checkbox SingleSelection

have a PySide6 QTreeWidget with some Elements and Checkboxes, very simple. What i cannot getting to work is how can i make s Single Selection with the Checkboxes? What works is SingleSelection without the Checkboxes, but not when i only use the Checkboxes itself. I wann use only Checkboxes and not Mouseclicks on the row, i did that with

tv.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
tv.setFocusPolicy(QtCore.Qt.NoFocus)

My Idea was set a itemChanged handler function for it and when a checkbox is clicked i run through all items, set all item checkboxes to uncheck with

child.setCheckState(0, QtCore.Qt.Unchecked)

and after that set the item that is selected from the handler to checked.

def handle_statechange(item):
    selected_item = item.text(0)
    for i in range(tv.invisibleRootItem().childCount()):
        child = tv.invisibleRootItem().child(i)
        child.setCheckState(0, QtCore.Qt.Unchecked)
    item.setCheckState(0, QtCore.Qt.Checked)

But that doesnt work. How can i make this behavior? Thanks!




vendredi 9 septembre 2022

What is the most elegant way to check a large combination of inputs?

I have a webapp that displays 11 checkboxes. When checked, the application returns a graph of the data that corresponds to the selected box.

Because the end user can select any variation of these boxes and should expect to see only the graph of those selected, every possible combination must be declared.

Currently, my implementation is as follows. It is quite unsophisticated and will likely take hours, so you can see why I'm looking for something a bit more.. supple?

Discretionary = st.sidebar.checkbox(label = 'Consumer Discretionary', value = False)
Consumer_Staples = st.sidebar.checkbox(label = 'Consumer Staples', value = False)
Energy = st.sidebar.checkbox(label = 'Energy', value = False)
Financials = st.sidebar.checkbox(label = 'Financials', value = False)
Healthcare = st.sidebar.checkbox(label = 'Healthcare', value = False)
Industrials = st.sidebar.checkbox(label = 'Industrials', value = False)
Materials = st.sidebar.checkbox(label = 'Materials', value = False)
Real_Estate = st.sidebar.checkbox(label = 'Real Estate', value = False)
Technology = st.sidebar.checkbox(label = 'Technology', value = False)
Utilities = st.sidebar.checkbox(label = 'Utilities', value = False)


Placeholder = st.empty()

for a in range(0, 500):
    try:
        Data = pd.read_csv('Mydata')
        Data = Data.set_index('Time')
    except:
        pass    
    
    if Communications == True and Discretionary == True:
    
        with Placeholder.container():             
            st.line_chart(data = Data[['Communications','CD Consumer Discretionary']] * 100)
            
    elif Communications == True and Discretionary == False:
    
    
        with Placeholder.container():     
            st.line_chart(data = Data['Communications'] * 100)
            
    elif Discretionary == True and Communications == False:
    
        with Placeholder.container():
            st.line_chart(data = Data['CD Consumer Discretionary'] * 100)```



React Uncaught TypeError: Cannot set properties of null (setting 'checked')

I'm using checkbox in react and the theme I'm using provides a hook but when my page loads I get a problem error. I am using checkbox for multiple delete action of elements in the table. I do not have a problem with deletion, but it generates an error on page load due to the check value.

this is the structure i use

https://facit-modern.omtankestudio.com/components/table

enter image description here

the hook i use

import React, { useEffect, useRef } from 'react';
import { useFormik } from 'formik';
import { Checks } from '../components/theme';

const useSelectTable = (data) => {
    const selectTable = useFormik({
        initialValues: {
            selectAll: false,
            selectedList: [],
        },
    });

    // Update Select List
    useEffect(() => {
        if (selectTable.values.selectAll) {
            selectTable.setValues({
                ...selectTable.values,
                selectedList: data.map((d) => d?.id?.toString()),
            });
        } else {
            selectTable.setValues({
                ...selectTable.values,
                selectedList: [],
            });
        }
        return () => {};
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectTable.values.selectAll]);

    // Select All -- indeterminate
    const ref = useRef(null);
    useEffect(() => {
        if (
            !!selectTable.values.selectedList.length &&
            selectTable.values.selectedList.length !== data.map((d) => d?.id?.toString()).length
        ) {
            ref.current.checked = false;
            ref.current.indeterminate = true;
        } else if (
            selectTable.values.selectedList.length === data.map((d) => d?.id?.toString()).length
        ) {
            ref.current.checked = true;
            ref.current.indeterminate = false;
        } else if (selectTable.values.selectedList?.length === 0) {
            ref.current.checked = false;
            ref.current.indeterminate = false;
        }
    }, [selectTable.values.selectAll, selectTable.values.selectedList, data]);

    const SelectAllCheck = (
        <Checks
            ref={ref}
            id='selectAll'
            onChange={selectTable.handleChange}
            checked={selectTable?.values?.selectAll}
        />
    );

    const selectItemHandleChange = selectTable.handleChange;
    const selectedIdList = selectTable?.values?.selectedList;

    return { selectTable, selectItemHandleChange, selectedIdList, SelectAllCheck };
};
export default useSelectTable;

usage:

const { selectTable, SelectAllCheck } = useSelectTable(slotData);

<td>
                    <Checks
                        id={slotAreas?.slot_number?.toString()}
                        name='selectedList'
                        value={slotAreas?.slot_number?.toString()}
                        onChange={selectTable?.handleChange}
                        checked={selectTable?.values?.selectedList.includes(
                            slotAreas?.slot_number?.toString(),
                        )}
                    />
                </td>

error javascript is a common error but I couldn't find a solution in react

can you help to solve this problem




jeudi 8 septembre 2022

How to insert two different values together into database whereas checkbox value and another input value such as quantity

I'm trying to insert two different value one is from a checkbox and one from different value such as quantity of the checkbox value beside it. I'm using foreach below as I am retrieving the books name saved into the database into the checkbox.

        @foreach($data as $data)
        <form action="" method="post">
        @csrf
        <div class="row col-12">
                      <div>
                        <p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value=""/>
                    <input type="number" name="prod_qty[]" min="1" value="1"class="form-control">
                      </div>
          @endforeach
        </div>
</form>

When I use the code below it successfully inserts the data into my database, however it only saves the prod_name since that is the only thing I implode and inserted to my database.

public function bookreservation(Request $request)
{
            $data = new bookreservation;
            $data->name=$request->name;
            $data->email=$request->email;
            $data->phone=$request->phone;
            $data->address=$request->address;
            $data->date=$request->date;
            $data->time=$request->time;

            $prod_qty = $request->prod_qty;
            $selected_products = $request->prod_name;
            $products = implode(" ",$selected_products);
            $data->products=$products;

            $data->save();
            return  redirect()->back();

}

When I try to implode it together it gives me an error that "implode() expects at most 2 arguments, 3 given"

        $prod_qty = $request->prod_qty;
        $selected_products = $request->prod_name;
        $products = implode($prod_qty," ",$selected_products);
        $data->products=$products;

and if I remove " " inside the implode a different error is given "implode(): Argument #1 ($separator) must be of type string, array given" because I want to save both as one value and be inserted into the database as one as well and not separately.

What should I do to save two different values into one. Where prod_qty is beside or before the selected_products like 32 JasminBooks and if they insert/select another different value like 5 KnowHowBooks the result will be "32 JasminBooks, 5 KnowHowBooks," in the database and both are not separated.




Is there a method to turn on checkbox from another file?

I am trying to read the value of checkbox from a file. The file is updated if checkbox is turned "ON" or turned "OFF".




How to insert text from textview according to checkbox?

I am making shopping list app in Kotlin. Main screen has 4 tabs, each for one store. On page for inserting new items I have 2 textview's, for product name and quantity. Also, on that page I have 4 checkboxes for 4 stores. I want to insert texts from textviews on specific tab when checkbox with same name as tab is checked. Didn't find any examples online. I would much appreciate everyones help.

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

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="30sp"
        tools:context=".ItemInputActivity" >

    <EditText
            android:id="@+id/productId"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:visibility="gone"
            tools:ignore="MissingConstraints"
    />

    <EditText
            android:id="@+id/inputItem"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_marginStart="22dp"
            android:layout_marginTop="26dp"
            android:layout_marginEnd="22dp"
            android:ems="10"
            android:hint="@string/naziv_proizvoda"
            android:background="@drawable/bg_form"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:inputType="textPersonName"
            android:textSize="16sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:importantForAutofill="no" />

    <EditText
        android:id="@+id/inputNumber"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginStart="22dp"
        android:layout_marginTop="20sp"
        android:layout_marginEnd="22dp"
        android:background="@drawable/bg_form"
        android:ems="10"
        android:hint="@string/kolicina_proizvoda"
        android:importantForAutofill="no"
        android:inputType="number"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/inputItem" />

    <CheckBox
        android:id="@+id/konzumCheck"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="22sp"
        android:layout_marginEnd="22sp"
        android:minHeight="48dp"
        android:text="@string/konzum"
        app:layout_constraintBottom_toTopOf="@+id/lidlCheck"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/inputNumber" />

    <CheckBox
            android:id="@+id/lidlCheck"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="22sp"
            android:layout_marginEnd="22sp"
            android:text="@string/lidl"
            android:minHeight="48dp"
            app:layout_constraintTop_toBottomOf="@id/konzumCheck"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/kauflandCheck"

    />

    <CheckBox
            android:id="@+id/kauflandCheck"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="22sp"
            android:layout_marginEnd="22sp"
            android:text="@string/kaufland"
            android:minHeight="48dp"
            app:layout_constraintTop_toBottomOf="@id/lidlCheck"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/sparCheck"

    />

    <CheckBox
            android:id="@+id/sparCheck"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="22sp"
            android:layout_marginEnd="22sp"
            android:text="@string/spar"
            android:minHeight="48dp"
            app:layout_constraintTop_toBottomOf="@id/kauflandCheck"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/inputButton"

    />

    <Button
        android:id="@+id/inputButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35sp"
        android:text="@string/spremi"
        android:textSize="12sp"
        app:layout_constraintEnd_toStartOf="@id/itemListActivity"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/sparCheck" />

    <Button
        android:id="@+id/itemListActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35sp"
        android:text="@string/lista_proizvoda"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/inputButton"
        app:layout_constraintTop_toBottomOf="@id/sparCheck"

        />

</androidx.constraintlayout.widget.ConstraintLayout>



How to insert/save an array data into database as one value

I used checkbox to select multiple value and I was able to store it into one variable as string and display it without a problem. Unfortunately when I'm trying to save it into my database it gives me an error "Array to string conversion". What should I do to save/insert it into the database as one value. The variable that holds the array value is products.

public function mydatabase(Request $request)
{
    $data = new mydatabase;
    $data->name=$request->name;
    $data->email=$request->email;
    $data->phone=$request->phone;
    $data->address=$request->address;
    $data->date=$request->date;
    $data->time=$request->time;
    $data->products=$request->products;

    $data->save();
    return  redirect()->back();

}



mercredi 7 septembre 2022

ToDo Async app toggle complete/not complete not staying saved in async storage using hooks

It has been days of me on this error. I am relatively new to stackoverflow so my apologies if my question isn't clear or I am not asking it in the correct format. I am trying to create a to do app in react native that is using async storage. I created a toggle button that saves the toggle to a state

[checkboxChecked, setCheckboxChecked=useState(false)

 const toggleComplete = () => {

        setCheckBoxState(!checkBoxState)
        handleEdit();
        console.log(checkBoxState)

    }

When the user checks on it - seems to be showing up correctly as marked true and false in the console. Then, this is passed to an edit handler to update the array, again console shows it is the correct state:

  const handleEdit = () => {
        props.editHandler(props.todoKey, text, checkBoxState);
        console.log(text2, checkBoxState)
    };

Then it shows that it saved correctly:

 const [todos, setTodos] = React.useState([]);
 const handleEdit = (todoKey, text, newStatus) => {
        const newTodos = [...todos];
        const index = newTodos.findIndex(todos => todos.key === todoKey);
        newTodos[index] = Object.assign(newTodos[index], {title: text, status: newStatus});
        setTodos(newTodos);
    
        console.log(todos, newStatus)
    };

The async function to save to the device and load are as follows: To save:

const saveTodoToUserDevice = async (todos) => {
        try {
            const stringifyTodos = JSON.stringify(todos);
            await AsyncStorage.setItem('todos', stringifyTodos);
        } catch (error) {
            console.log(error);
        }
    };

To load from the device:

const getTodosFromUserDevice = async () => {
        try {
            const todos = await AsyncStorage.getItem('todos');
            if (todos != null) {
                setTodos(JSON.parse(todos));
                console.log("loaded successfully");
            }
        } catch (error) {
            console.log(error);
        }
    };

So here is the issue - I get the console log that says it is saved correctly and loaded. BUT, when I refresh, the checkbox state is not saved at all, just the title text (so it is saving but the checkbox would always be false (the initial state set). If I clicked on true, it would show as true and then when I refresh, it goes back to false.

I have spent days and days on this and can't figure it out. Any direction would be helpful Thank you!




Recycler View with Checkbox issue

Checkbox unchecked after scrolling down, also if i checked one item another item will be checked automatically in lower part of the page. someone please help me, i'm stuck with this problem so long. here is my adapter code.

public class Tasadapter extends RecyclerView.Adapter<Tasadapter.TasviewHolder> {

private Context mCtx;
private List<TasModel> tasList;

public Tasadapter(Context mCtx, List<TasModel> tasList) {
    this.mCtx = mCtx;
    this.tasList = tasList;
}

@NonNull
@Override
public TasviewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
    LayoutInflater inflater =LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.tas_list,null);
    TasviewHolder holder =new TasviewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull final TasviewHolder tasviewHolder, int position) {
    //tasviewHolder.setIsRecyclable(false);
    tasviewHolder.bind(position);


}

@Override
public int getItemCount() {
    return tasList.size();
}

class TasviewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    TextView name, roll;
    CheckBox tasPrst;
    String prst;
    public TasviewHolder(@NonNull View itemView) {
        super(itemView);
        name =itemView.findViewById(R.id.tasName);
        roll =itemView.findViewById(R.id.tasRoll);
        tasPrst =itemView.findViewById(R.id.tasBox);
    }
    void bind(int position) {
        tasPrst.setText(String.valueOf(tasList.get(position).getPosition()));

        if (tasList.get(position).getChecked()) {
            tasPrst.setChecked(true);
        }
        else {
            tasPrst.setChecked(false);
        }
        TasModel tasModel =tasList.get(position);
        name.setText(tasModel.getName());
        roll.setText(tasModel.getRoll());
    }

    @Override
    public void onClick(View v) {
        int adapterPosition = getAdapterPosition();
        if (tasList.get(adapterPosition).getChecked()) {
            tasPrst.setChecked(false);
            tasList.get(adapterPosition).setChecked(false);
        }
        else {
            tasPrst.setChecked(true);
            tasList.get(adapterPosition).setChecked(true);
        }
    }
}

}




React : How to delete multi selected check-boxes when a delete button is clicked in react

I am new to react . Trying to delete all the checkboxes which are checked with a delete button which is on the top of the page . I am using functional component approach .

Please help me with this.




mardi 6 septembre 2022

How to display value of multiple checkbox to another page

I'm having trouble where I can't seem to retrieve/display the value I selected to another page This is my route code

Route::post("/product",[HomeController::class,"product"]);
Route::get("/checkbox",[HomeController::class,"checkbox"]);

In my function in controller

    public function product(Request $request){
       return view('/product');
    }

   public function checkbox(){
       return view('/checkbox');
    }

The code from the first page where the checkbox are being displayed

<form action="" method="POST">
  @csrf
<div class="row">
              <div class="col-sm-3">
                <p class='mybox text-dark'><input type="checkbox" name="books[]" value="Chemistry"/>Chemistry
                <input type="hidden" name="books_name[]" value="Chemistry">

                <input type="number" name="books_qty[]" min="1" value="1"class="form-control">
            <div class="col-sm-3">
                <p class='mybox text-dark'><input type="checkbox" name="books[]" value="English"/>English
                <input type="hidden" name="books_name[]" value="Chemistry">

                <input type="number" name="books_qty[]" min="1" value="1"class="form-control">
            <div class="text-center m-2">
                <button class="btn btn-info btn-m text-center" type="submit">Submit</button>
            </div>
</form>

The code where the selected value should be displayed

<?php
if(isset($_POST['submit'])){
$checked_array = $_POST['books'];
foreach($_POST['books_name'] as $key => $value){
if(in_array($_POST['books_name'][$key], $checked_array)){
  echo $_POST['books_name'][$key];
  echo $_POST['books_qty'][$key];

}
}
}
?>

The first page it displays the form where the checkbox resides ok and when I click the the submit I will be directed to the next page but the value is not being displayed that's why the page is displaying empty but when I try inserting

Hello

It displays it that's why the page is working ok but it doesn't display the value I selected from the checkbox.


Nested Checkbox with 2 level using Chakra-ui (Reactjs)

I'm trying to build a nested checkbox with 2 levels using Chakra-UI.

  • Once clicked on parent checkbox, all children should be checked: (v)
  • if you click on one child, all parents should be on indeterminate state: (-)
  • if all children are checked, the parent of these children should be checked as well.

The first level is already done here:

Nested Checkbox with 2 level using Chakra-ui

import React from "react";
import { Checkbox, Stack, Box } from "@chakra-ui/react";

const data = {
users: [
{
  id: "user-1",
  name: "User 1",
  child: [{ name: "Salary1" }, { name: "Department1" }]
},
{
  id: "user-2",
  name: "User 2",
  child: [{ name: "Salary2" }, { name: "Department2" }]
},
{
  id: "user-3",
  name: "User 3",
  child: [{ name: "Salary3" }, { name: "Department3" }]
},
{
  id: "user-4",
  name: "User 4",
  child: [{ name: "Salary4" }, { name: "Department4" }]
},
{
  id: "user-5",
  name: "User 5",
  child: [{ name: "Salary5" }, { name: "Department5" }]
},
{
  id: "user-6",
  name: "User 6",
  child: [{ name: "Salary6" }, { name: "Department6" }]
},
{
  id: "user-7",
  name: "User 7",
  child: [{ name: "Salary7" }, { name: "Department7" }]
},
{
  id: "user-8",
  name: "User 8",
  child: [{ name: "Salary8" }, { name: "Department8" }]
}
 ]
};

export default function App() {
const [checkedItems, setCheckedItems] = React.useState(
  data.users.map(() => false)
 );

const allChecked = checkedItems.every(Boolean);
const isIndeterminate = checkedItems.some(Boolean) && !allChecked;

return (
  <Stack pt={3} pl={3}>
  <Checkbox
    isChecked={allChecked}
    isIndeterminate={isIndeterminate}
    onChange={(e) =>
      setCheckedItems(data.users.map(() => e.target.checked))
    }
  >
    Parent Checkbox
  </Checkbox>

  <Stack pl={6} mt={2} spacing={2}>
    {data.users.map((user, index) => (
      <Box key={user.id}>
        <Checkbox
          key={user.id}
          isChecked={checkedItems[index]}
          onChange={(e) =>
            setCheckedItems([
              ...checkedItems.slice(0, index),
              e.target.checked,
              ...checkedItems.slice(index + 1)
            ])
          }
        >
          {user.name}
        </Checkbox>
        <Stack pl={6} spacing={2}>
          {user.child.map((category) => (
            <Checkbox key={category.name}>{category.name}</Checkbox>
          ))}
        </Stack>
      </Box>
    ))}
  </Stack>
</Stack>
);

How could the level 2 be achieved using the starter code above? Any help would be greatly appreciated. Thanks in advance.

Here is the CodeSanbox link: https://codesandbox.io/s/peaceful-rosalind-741e5c?file=/src/App.js:0-2336