lundi 28 février 2022

How do I delete the cell content in front of cell that have not been checked?

I have cell range. First column have content. Second column have check box. See first picture.first picture I try to clear content infront of unchecked boxes.

    function clearCon() {
var ss = SpreadsheetApp;
var sheet=ss.getActiveSpreadsheet().getSheetByName ("AddData");
var chkval = sheet.getRange("A29:B33").getValues();
Logger.log(chkVal);
Logger.log( chkval.length);
for(var i=0; i<=chkVal.length; i++) { if (chkval[1][1] == false) { sheet.getRange (28, 1, 1+1,1).clearContent(); return;
Logger.log(1);
}
}
}

See this picture code it's not correctly work. How to do this?




dimanche 27 février 2022

How to handle multiple checkboxes in React form?

I have a form that loads preset checkbox selections from the backend. I query the checkbox menu and iterate over it in JSX. Now I want to be able to select/deselect. To handle this, I start out by creating an array of objects matching the size of menu checkbox items like so:

useEffect(() => {
  if (!profile) { // this checks if the reusable form is a create or update. If this is an update, I need to prefill an existing array of objects with added key/value pair of checked: true
    setConcerns(Array(menuItems.length).fill({ checked: false }))
  } 
}, [menuItems]) // this happens first 

// if it's an update form 


useEffect(() => {
  if (profile) { 
    const updatedConcerns = existingConcerns.map((c, i) => ({
        ...concerns,
        c.id: c.id,
        checked: true,
      }))
  } 
}, [existingConcerns]) // this happens second

This sets up the concerns array for toggle.

In my JSX I have a Checkbox component:


 {menuItems &&
     menuItems.map((item: CheckboxProps, index: number) => (
       <Checkbox
         testID={item?.title}
         label={item?.title}
         checked={concerns && !!concerns[index]?.checked}
         onValueChange={() => handleConcerns(index)}
       />
  ))}

And the handleConcerns method so far:

  const handleConcerns = (index: number) => {
    const concernsCopy = [...concerns]
    concernsCopy[index].checked = !concernsCopy[index].checked
    setConcerns(concernsCopy)
     // the rest will determine how to add selected items to concerns 
     array for submit
  }

This causes all of the checkboxes to toggle. This is just the start of pushing menu data into each index of concerns array but first need to get the checkboxes working and be able to have an array of chosen indices to submit to backend.




samedi 26 février 2022

Select All checkboxes by default in inner mat table not working

I have a nested mat table with expandable rows . The inner table has checkbox and by default all the checkbox has to be checked in the nested tables on load. Here is the stackblitz with issue . Can someone help to resolve

https://stackblitz.com/edit/angular-nested-mat-table-triplenested-iavs62?file=app%2Ftable-expandable-rows-example.ts




vendredi 25 février 2022

Show a specific data from jinja2 according to a checkbox is checked or not

I have a specific select that I would change the options according to with a checkbox that is either checked or not. This select is inside another Jinja2 loop, like below:

    

So far, I've created a variable called variable_to_check in the javascript, but the jinja2 does not seem to get the value of this variable:

variable_to_check == 0
function libera() {
    let check = document.getElementById('libera_check')

    
    if (check.checked) {

    var_libera_todas_agencias = 1
    
 
    
} else {
            
    var_libera_todas_agencias = 0
    
}


}



Select All checkboxes by default in nested mat table not working as expected

I have a nested mat table with expandable rows . Only the inner table has checkbox and by default all the checkbox has to be checked in all the nested tables . Here is the working stackblitz

https://stackblitz.com/edit/angular-nested-mat-table-triplenested-iavs62?file=app%2Ftable-expandable-rows-example.ts

    getProjectDetails(element: any) {
    console.log(element.Id);
    this.tableService.getInnerData(element.Id).subscribe((res) => {
      if (res.length == 0) {
        element['usersdataSource'] = new MatTableDataSource();
      } else {
        element['usersdataSource'] = new MatTableDataSource(res);
        this.userSelectionMap.set(
          element.Id,
          new SelectionModel<any>(true, [element['usersdataSource']])
        ); // provided datasource of the current inner table for default sselection
      }
    });
  }

I have provided the value of datasource for default selection while defining the selection model but it is not working as expected . I dont want to iterate over each table and do the selection as the data of inner table can be huge . What could be the best way to implement this ?




mercredi 23 février 2022

sum checkbox and javascript

I m realy new to javascript and html. In a problem i got asked to create a function to show an alert if the player checks more or less than 3 checkboxes and also and also calculates his score in the game and show an alert if he has more than 15 points or less here is the html

    <form name="form">
        <input type="checkbox" name="choix" value="-8" /> Case 1 <br/>
        <input type="checkbox" name="choix" value="5" /> Case 2 <br/>
        <input type="checkbox" name="choix" value="3" /> Case 3 <br/>
        <input type="checkbox" name="choix" value="10" /> Case 4 <br/>
        <input type="checkbox" name="choix" value="0" /> Case 5 <br/>
        <input type="checkbox" name="choix" value="-1" /> Case 6 <br/>
        <input type="checkbox" name="choix" value="-7" /> Case 7 <br/>
        <input type="checkbox" name="choix" value="15" /> Case 8 <br/>
        <input type="checkbox" name="choix" value="8" /> Case 9 <br/>
        <input type="checkbox" name="choix" value="3" /> Case 10 <br/>
        <input type="button" value="Calculer le score du jeu" onClick="CalculScore()"/>
    </form>
    <input type="text" value="" name="resultat" disabled/>  



How can I use checkbox inside the modal in dittofi?

I have been trying to use the checkbox in the dittofi modal but it's not working inside a modal. On the simple page, it is working fine but not on modal.




mardi 22 février 2022

Grid with LitTemplate not updating checkbox consistently

We are updating our Grid forms to use LitTemplates for rendering. However we have run into an issue with a checkbox state not being updated even though the underlying data for the state has been updated. The following code demonstrates the issue:

        HorizontalLayout hlTest = new HorizontalLayout();
        List<String> selected = new ArrayList<>();
        Grid<String> testGrid =new Grid<>();
        testGrid.setWidth("250px");
        testGrid.setHeight("250px");
        List<String> dataList = new ArrayList<>(List.of("AAAAA", "BBBBB", "CCCCC", "DDDDD", "EEEEE"));
        ListDataProvider<String> dataProvider = new ListDataProvider<>(dataList);
        testGrid.setItems(dataProvider);

        String template = """
                    <vaadin-checkbox @click="${handleCheckClick}" ?checked="${item.rowSelected}"></vaadin-checkbox>
                    <div>${item.text}</div>
                """;

        LitRenderer<String> lit = LitRenderer.of(template);
        lit.withProperty("rowSelected", item -> {
            boolean rc = selected.contains(item);
            System.out.println("Item selected: " + item + " => " + rc);
            return rc;
        });
        lit.withProperty("text",item -> item);
        lit.withFunction("handleCheckClick", (item) -> {
            if(selected.contains(item))
                selected.remove(item);
            else
                selected.add(item);
        });
        testGrid.addColumn(lit);
        Button bSelect = new Button("Select");
        bSelect.addClickListener(buttonClickEvent -> {
            if(selected.size() > 0)
            {
                dataList.clear();
                dataList.addAll(selected);
                selected.clear();
                dataProvider.refreshAll();
            }
        });
        hlTest.add(testGrid, bSelect);

With the given grid, click a few checkboxes and click 'Select'. The list is reduced to the selected rows, but the checkboxes are still ticked even though 'selected' is empty. The logging within 'rowSelected' is correctly returning the state.

If I remove the column and re-add to grid, then all is displayed correctly. Also, if I select all items in the grid then the select also works correctly.

Currently using Java17 and Vaadin 22.0.6 (have also tried 23.0.0 beta3).

Thanks.




Drag Select Checkboxes in Kotlin

Is there a way of creating a drag select with checkboxes in Android Studio using Kotlin? If you know the game Rainbow Six Siege, there is a character that hacks phones and in that animation you see her drag select multiple checkboxes while swiping. Anyone have a clue how I can implement that?

See the first 3 seconds of this video: https://www.youtube.com/watch?v=NP6C2mOCe6A
The rest of the video is irrelevant btw




For problem solvers: CSS Pseudo Element Checkbox not changing on "checked" state [duplicate]

For everyone who loves solving problems: here is one.

I tried to customize a checkbox with a pseudo element. But the checkbox won't change after it's checked.

<div class="c-form-check">
  <label>
    <input type="checkbox">Test
  </label>
</div>
.c-form-check input[type=checkbox] {
  opacity: 0.2;
}

.c-form-check label::before{
  content: '';
  display: inline-block;
  font-weight: normal !important;
  border: 1px solid #676767;
  min-height: 1.375rem;
  min-width: 1.375rem;
  max-height: 1.375rem;
  max-width: 1.375rem;
  margin-top: 0;
  z-index: 1;
  margin-right: .5rem;
  box-shadow: none;
}

.c-form-check:hover label::before {
  border: 1px solid #888888;
}

.c-form-check input[type=checkbox]:checked + label::before {
  background-image: none;
  border: 1px solid @grau6;
  box-shadow: inset 0 0 0 2px #fff, inset 0 0 0 10px green;
}

Do you see the problem? Help me to solve it! https://jsfiddle.net/9d3czhor/9/




How to divide an SVG circle, depending of an external input?

I have a progress ring where if I have 5 checkboxes to click, so the conditions I created in JS are involving this number 5, as you can see the in the var percent the number 20 was calculated by me cause I knew I had 5 checkboxes.

//There are 5 checkboxes to interact with, so 100/5=20.
    var percent = (checked) * 20;

    myProgress.style.strokeDashoffset = 100 - percent;

Now I'm trying to do something similar, but this time the number of checkboxes to fill is unknown, it'll depend of the number of checkboxes that the user wants. So I decided to update my logic to something like this:

function update() {

var myProgress = document.getElementById("myProgress");
//Reference the Form.
var toDo = document.getElementById("toDo");

//Reference all the CheckBoxes in Table.
boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
checked = boxes.length

//Since in this case I don't know the number of checkboxes, I can't simply add the number 20, so I thought I could get that "20" by doing the following division.

var division= [(100/checked.toFixed(4))];
console.log("this is division:"+ division);

//and then with this division variable, replace the 20 from the previous code. But here is where I have the main problem, because as result of every click I do in a checkbox the var percent always get 100 and as result the ring is already fully colored.
var percent = (checked) * (division);
console.log("this is the percent:"+percent);

myProgress.style.strokeDashoffset = 100 - percent;
if (checked === 5) {
    myProgress.style.stroke= "#1DEBA1";
}else if(checked < 5){
    myProgress.style.stroke= "purple"
}
return true;
}
checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
box.addEventListener("change", function() {
    update()
});
});
#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}
<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent"/>
</svg>
<br>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" /><label for="FirstToDo">First</label>
  <input id="SecondToDo" type="checkbox" value="2" /><label for="SecondToDo">Second</label>
  <input id="ThirdToDo" type="checkbox" value="3" /><label for="ThirdToDo">Third</label>
  <input id="FourthToDo" type="checkbox" value="4" /><label for="FourthToDo">Fourth</label>
  <input id="FifthToDo" type="checkbox" value="5" /><label for="FifthToDo">Fifth</label>
</form>
<script src="Circle.js"></script>

Since in this case I don't know the number of checkboxes, I can't simply add the number 20, so I thought I could get that "20" by doing the following division.

    var division= [(100/checked.toFixed(4))];
    console.log("this is division:"+ division);

and then with this division variable, replace the 20 from the previous code. But here is where I have the main problem, as result of every click I do in a checkbox the var percent always returns 100 and as result the ring is already fully colored.

    var percent = (checked) * (division);
    console.log("this is the percent:"+percent);

    myProgress.style.strokeDashoffset = 100 - percent;

Result in the console Result I want to achieve with not unknown value of inputs

Can somebody help me understand how can I made the var percent more precise, I know I'm mixing different types to get the result I want and most probably that is where my error is , but my problem is that I can't identify this mix of types interacting to each other, I'm not sure if the result I get from var division is considered a number, array or percent?

Thank you all for your help.




lundi 21 février 2022

reload recyclerview adapter in android

i make some checkbox and radiobutton programically in my recyclerview and when i use notifydatasetchanged all of them are replaced with items in mylist what should i do?

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    public MyRecyclerViewAdapter(Context context, ArrayList<HashMap<String, Object>> hash_all) {

    }

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

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        hash_all.size();

       hash_get = hash_all.get(position);



        Log.d("_hdev",hash_all.get(position) + " ::::::::: " + hash_get+"");

        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(
                LinearLayoutCompat.LayoutParams.MATCH_PARENT,
                LinearLayoutCompat.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 0, 0, 0);




        String s = hash_get.get("ModelShowOption").toString();
        String toggle = "";
        String direc = "";
        String type = "";
        String model = "";
        String rows = "";
        String resize = "";
        String[] split = s.split("\\|");

        // = new String[0];
        String[] split2 = new String[0];
        for (int i = 0; i < split.length; i++) {
            String s2 = split[i];
            split2 = s2.split(":");
            if (split2[0].equals("isToggleButton")){
                toggle=split2[1];
            }else if (split2[0].equals("type")){
                type=split2[1];
            }else if (split2[0].equals("direction")){
                direc=split2[1];
            }else if (split2[0].equals("model")){
                model=split2[1];
            }else if (split2[0].equals("rows")){
                rows=split2[1];
            }else if (split2[0].equals("resize")){
                resize=split2[1];
            }


        }



        String title = hash_get.get("title").toString();

        String myValue =hash_get.get("MyValue").toString();
        String[] splitValue = myValue.split("\\|");

        RadioGroup[] rg;
        RadioButton[] rb;



        if (toggle.equals("true") && holder.row_list_title.getText().equals("")){
            holder.row_list_placeholder.setVisibility(View.GONE);

            String multiValue = hash_get.get("MultiValue").toString();
            String[] splitMultiValue = multiValue.split(":");
            if (splitMultiValue[1].equals("1")){




            int p = 0;
            rg = new RadioGroup[1];
            rb = new RadioButton[splitValue.length];
            rg[0] = new RadioGroup(holder.row_list_placeholder.getContext());
            rg[0].setOrientation(RadioGroup.VERTICAL);
            for (int j = 0; j < splitValue.length; j++) {


                    String myValue2 = splitValue[j];
                    String[] splitValue2 = myValue2.split("=");
                    rb[j] = new RadioButton(getApplicationContext());
                    rg[p].addView(rb[j]);
                    rb[j].setId(j);
                    rb[j].setText(splitValue2[0]);

            }

            holder.linearLayoutCheckBox.addView(rg[p]);

            p++;


            holder.row_list_title.setText(title);
            if (rg[0].getCheckedRadioButtonId() == -1) {
                Log.d("RadioString", "Nothing selected");
            } else {
                for (int r = 0; r < splitValue.length; r++) {
                    if (rb[r].isChecked()) {
                        RadioButton id = (RadioButton) findViewById(rb[r].getId());
                        String radioText = id.getText().toString();
                        Log.d("RadioString", radioText);
                    } else {
                        Log.d("RadioString", "nothing");
                    }
                }
            }

            }else{

                //splitMultiValue[1]
                holder.row_list_title.setText(title);
                CheckBox[] ch;
                final int[] checkd = {0};
                ch = new CheckBox[splitValue.length];

                    for (int j = 0; j < splitValue.length; j++) {


                        String myValue2 = splitValue[j];
                        String[] splitValue2 = myValue2.split("=");
                        ch[j] = new CheckBox(getApplicationContext());
                        holder.linearLayoutCheckBox.addView(ch[j]);
                        ch[j].setId(j);
                        ch[j].setText(splitValue2[0]);

                    }


                for (int r = 0; r < splitValue.length; r++) {
                    int finalR = r;
                    ch[r].setOnCheckedChangeListener((buttonView, isChecked) -> {
                        if (isChecked) {
                            Log.d("_hdev", checkd[0] +"");
                            Log.d("_hdev",Integer.parseInt(splitMultiValue[1])+"");
                            if (checkd[0] < Integer.parseInt(splitMultiValue[1])){

                                //CheckBox id = findViewById(ch[finalR].getId());
                                //String CheckBoxText = id.getText().toString();
                                //Log.e("CheckBoxString", CheckBoxText);
                                checkd[0] = checkd[0] +1;
                                Log.d("_hdevn", "1");
                            }else{
                                //CheckBox id = (CheckBox) findViewById(ch[finalR].getId());
                                ch[finalR].setChecked(false);
                                //checkd[0] = checkd[0] -1 ;
                                Log.d("_hdevn", "2");
                            }

                        } else {
                            ch[finalR].setChecked(false);
                            checkd[0] = checkd[0] -1;
                            Log.d("_hdevn", "3");

                    }
                    });
                }




            }

        }else{
            if (myValue.equals("NULL")){
                holder.row_list_title.setText(title);
                holder.row_list_placeholder.setVisibility(View.VISIBLE);
                holder.row_list_placeholder.setHint(hash_get.get("placeholder").toString());
                if (type.equals("Text")){
                    holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_TEXT);
                }else if(type.equals("Int")){
                    holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER);
                }else if(type.equals("Float")){
                    holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                }
            }else {



                    holder.row_list_placeholder.setVisibility(View.GONE);
                   /*

                    TextView[] tv;
                    final int[] checkd = {0};
                    tv = new TextView[splitValue.length];

                    for (int j = 0; j < hash_all2.size(); j++) {


                        Log.d("_hdev", hash_all2.get(j).get("selected"));
                        if (hash_all2.get(j).get("selected").equals("true")) {
                            String myValue2 = splitValue[j];
                            String[] splitValue2 = myValue2.split("=");
                            tv[j] = new TextView(getApplicationContext());
                            holder.linearLayoutCheckBox.addView(tv[j]);
                            tv[j].setId(j);
                            tv[j].setText(hash_all2.get(j).get("name"));
                        }


                    }*/

                    //list popup
                    holder.row_list_title.setText(title);
                    holder.row_list_title.setOnClickListener(v -> {




                        profileadapter.notifyDataSetChanged();
                        //get_profiles();

                        /*if (hash_all2.size() == 0) {
                            for (int j = 0; j < splitValue.length; j++) {
                                HashMap<String, String> hash_add2 = new HashMap<>();

                                String myValue2 = splitValue[j];
                                String[] splitValue2 = myValue2.split("=");

                                hash_add2.put("Id", String.valueOf(j));
                                hash_add2.put("name", String.valueOf(splitValue2[0]));
                                hash_add2.put("value", String.valueOf(splitValue2[1]));
                                hash_add2.put("selected", "false");

                                hash_all2.add(hash_add2);

                            }
                            adapt.notifyDataSetChanged();
                        }

                        alertDialogSelect();*/
                    });
                
            }
        }




    }



    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row_form, parent, false);
        return new ViewHolder(view);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView row_list_title;
        EditText row_list_placeholder;
        LinearLayout linearLayoutCheckBox;
        CardView cardrow;


        ViewHolder(View itemView) {
            super(itemView);

            row_list_title = itemView.findViewById(R.id.row_list_title);
            row_list_placeholder = itemView.findViewById(R.id.row_list_placeholder);
            linearLayoutCheckBox = itemView.findViewById(R.id.mainrow);

        }
    }
}

this is what i tryed in many days.




Vue 3 unchecking custom checkbox component

Hey guys I have the following problem: I want to uncheck the custom checkbox components after I submit the form. I set the v-model to an empty object after submitting (account.value = {}) but the box still stays checked even though the value is empty.

Child Checkbox.vue:

<template>
  <div class="checkboxContainer">
    <label :for="id"></label>
    <input
      :id="id"
      type="checkbox"
      @change="$emit('update:modelValue', $event.target.checked)"
    />
  </div>
</template>

<script setup>
import { defineProps } from 'vue'

defineProps({
  text: {
    default: '',
    type: String
  },
  id: {
    default: '',
    type: String
  }
})
</script>

Parent.vue:

<template>
  <form @submit.prevent>
    <div class="formWrapper">
      <Checkbox
        id="changeEmail"
        v-model="account.changeEmail"
        text="Can Change Email: "
      />
      <Checkbox
        id="changeUser"
        v-model="account.changeUser"
        text="Can Change User: "
      />
      <button type="submit" @click="createAccount()">Create</button>
    </div>
  </form>
</template>

<script setup>
import { ref } from 'vue'
import Checkbox from '@/components/helpers/Checkbox.vue'
import axios from 'axios'

const account = ref({})

const createAccount = () => {
  axios
    .post('/api/account-management/accounts', {
      can_change_own_email: account.value.changeEmail,
      can_change_own_user: account.value.changeUser
    })
    .then(() => {
      account.value = {}
    })
}
</script>




dimanche 20 février 2022

send multiply email for each selected checkbox

<input type="checkbox" value="company1" id="benefit1" name="benefit1">
<input type="checkbox" value="company2" id="benefit2" name="benefit1">
<input type="checkbox" value="company3" id="benefit3" name="benefit1">

How to send with php code to different email each selected checkbox? if checked company1 - send to email1 (as cc email) if checked company2 - send to email2 (as cc email) if checked company3 - send to email3 (as cc email)




How to exclusively set the value of a DataGridViewCheckBoxCell?

I have a List<Car> objects that have a bool property named Marked.
I want to check / uncheck the Cell corresponding to this property, in a way that only one Car can be selected at the same time.
I want that the value of this property is updated in the bank.

Sample table:

Car Name Marked
a  
b  

The problem is I can't check the state of CheckBox Cells.
This is what I tried, but it's not working:

Example 1:

DataGridViewCheckBoxCell dataGridViewCheckBoxCell = DataGridView1.Rows[e.RowIndex].Cells["Marked"] as DataGridViewCheckBoxCell;

if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == true)
{
        //some code
}
else if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == false)
{
        //some code
}

Example 2:

foreach (DataGridViewRow row in DataGridView1.Rows)
{
    DataGridViewCheckBoxCell chk =(DataGridViewCheckBoxCell)row.Cells["Marked"];

    if (chk.Value == chk.TrueValue)
    {
        chk.Value = chk.FalseValue;
    }
    else
    {
        chk.Value = chk.TrueValue;
    }
}

how can I do it?




samedi 19 février 2022

Google Sheets consecutive rows when multiple checkboxes are ticked

I am looking for help with this sheet. I have some item names and images next to those. They belong together.

Whenever I tick the first checkbox in the item sheet, I want the item name and the image to be displayed in Sheet 2. I have managed to do that with the formula in A1 for the image

=Iferror(VLOOKUP(B1,Items!B4:F15,2,FALSE),"")

and for the item name formula in B1 I used

=iferror(QUERY(Items!B4:F15,"select B where D=True"),"") .

My problem is:

When I tick the first checkbox of any item, the item gets normally displayed in Sheet2 with the belonging image. When I tick the second checkbox for that same item (x2), I want the same item to be displayed right again in the second row in Sheet2 with the belonging image again. If I tick the third checkbox, I want it to be displayed three times basically below each other with the belonging image.

Is that possible without scripts?

https://docs.google.com/spreadsheets/d/1tjyBIMDWbM4AxuQby4vmEUeFgqLbxN1EPk1pGqEX_64/edit?usp=sharing




How To Set DataGridViewCheckBoxColumn/Cell

I have a list of car objects that have a property called "Marked" that it's type is boolean. I want to check / uncheck this property, select only one of them, ie only one car can be selected from this list and at the same time I want the value true or The false of this property should be update in the bank.

exmple table:

Car Name Marked
a  
b  

problem is i can't check state of datagridviewcheckboxcolumn/cell.for example i try blow codes but they don't working.

examlpe 1 :

DataGridViewCheckBoxCell dataGridViewCheckBoxCell = DataGridView1.Rows[e.RowIndex].Cells["Marked"] as DataGridViewCheckBoxCell;

if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == true)
{
        //some code
}
else if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == false)
{
        //some code
}

exmple 2 :

foreach (DataGridViewRow row in DataGridView1.Rows)
{
    DataGridViewCheckBoxCell chk =(DataGridViewCheckBoxCell)row.Cells["Marked"];

    if (chk.Value == chk.TrueValue)
    {
        chk.Value = chk.FalseValue;
    }
    else
    {
        chk.Value = chk.TrueValue;
    }
}

how can i do it?




How To Set DataGridViewCheckBoxColumn

I have a list of car objects that have a property called "Marked" that it's type is boolean. I want to check / uncheck this property, select only one of them, ie only one car can be selected from this list and at the same time I want the value true or The false of this property should be update in the bank.

exmple table:

Car Name Marked
a  
b  

problem is i can't check state of datagridviewcheckboxcolumn/cell.for example i try blow codes but they don't working.

examlpe 1 :

DataGridViewCheckBoxCell dataGridViewCheckBoxCell = DataGridView1.Rows[e.RowIndex].Cells["Marked"] as DataGridViewCheckBoxCell;

if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == true)
{
        //some code
}
else if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == false)
{
        //some code
}

exmple 2 :

foreach (DataGridViewRow row in DataGridView1.Rows)
{
    DataGridViewCheckBoxCell chk =(DataGridViewCheckBoxCell)row.Cells["Marked"];

    if (chk.Value == chk.TrueValue)
    {
        chk.Value = chk.FalseValue;
    }
    else
    {
        chk.Value = chk.TrueValue;
    }
}

how can i do it?




vendredi 18 février 2022

Create a checkbox in a cell when a other cell contains a date

I'm a noob to scripting and i have a spreadsheet that contains dates in some cells in row 0. Now i like te automatically create a checkbox in row 5 if row 0 contains a date. I use the checkbox to create or delete a event in the spreadsheet to a calendar. Now a need to put the check boxes in manually when i put in a new date.The script i'm using you can see down here.

spreadsheet i'm using

//**
// * Adds a custom menu to the active spreadsheet, containing a single menu item
// * for invoking the exportEvents() function.
// * The onOpen() function, when defined, is automatically invoked whenever the
// * spreadsheet is opened.
// * For more information on using the Spreadsheet API, see
// * https://developers.google.com/apps-script/service_spreadsheet
//*/
function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Export Events",
    functionName : "exportEvents"
  }];
  sheet.addMenu("Calendar Actions", entries);
  
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Delete Events",
    functionName : "deleteAllDayEvents"
  }];
  sheet.addMenu("Delete events", entries);


};

/**
 * Export events from spreadsheet to calendar
 */
function exportEvents() {
  var space = " - "
  var sheet = SpreadsheetApp.getActiveSheet();
        //var sheetName = sheet.getName() als je een tweede sheet gebruikt
        //if(sheetName != "Events"){
           //return
        
  var headerRows = 1;  // Number of rows of header info (to skip)
  var range = sheet.getDataRange();
  var data = range.getValues();
  var calId = "stichtingmotardstein@gmail.com";
  var cal = CalendarApp.getCalendarById(calId);
  for (i=0; i<data.length; i++) {
    if (i < headerRows) continue; // Skip header row(s)
    var row = data[i];
    var date = new Date(row[0]);  // First column
    if(isNaN(date.valueOf()))
      continue;                // skip row, go to the next row 
    var numb = row[3];
    var title = numb.substring(11,6) +space+ row[2];
    var loc = row[1];
    var id = row[4];              // Sixth column == eventId
    // Check if event already exists, update it if it does
    try {
      var event = cal.getEventSeriesById(id);
    }
    catch (e) {
      // do nothing - we just want to avoid the exception when event doesn't exist
    }
    if (!event) {
      //cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
      var newEvent = cal.createAllDayEvent(title, date, {location:loc}).getId();
      row[4] = newEvent;  // Update the data array with event ID 4
    }
    else {
      event.setTitle(title);
      event.setLocation(loc);
      // event.setTime(tstart, tstop); // cannot setTime on eventSeries.
      // ... but we CAN set recurrence!
      var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
      event.setRecurrence(recurrence, date);
    }
    debugger;
  }
  // Record all event IDs to spreadsheet
  range.setValues(data);
}

function deleteAllDayEvents() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
  var vA=rg.getValues();
  var cal=CalendarApp.getCalendarById("stichtingmotardstein@gmail.com");
  vA.forEach(function(r,i){
    var id=r[4];
    if(id && r[5]) {
      cal.getEventById(id).deleteEvent();
      sh.getRange(i+2,5).setValue("");
      sh.getRange(i+2,6).setValue("TRUE");//just to reset the checkbox
    }
  })  
}



Android checkbox.isChecked is not working

I am trying to create a like and dislike button. I use Checkboxes to do so.

In the XML code I have two checkboxes one called like and the other dislike

I'm trying to toggle between the like and dislike buttons. Such that they both cannot be switched on at the same time.

public void onLike(View view) {
        if (dislike.isChecked()) {
            dislike.setChecked(false);
        }
        Toast.makeText(this,"liked",Toast.LENGTH_SHORT).show();
    }

The issue that I am having is that set setChecked(true) is not doing anything.

For more context, the XML for the checkbox is defined inside a fragment that has a cardview. Each item in the card view has the checkboxes.

the way I initialized the checkbox in the main activity is as follows: -

View cardViewLayout = getLayoutInflater().inflate(R.layout.text_row_item,null);
        like = (CheckBox) cardViewLayout.findViewById(R.id.like);
        dislike = (CheckBox) cardViewLayout.findViewById(R.id.dislike);

any ideas what's going on?




Why doesn't the checkbox saving the values?

Previously I had a checkbox whose default value was checked automatically.

Then I want the checkbox to appear based on certain conditions as described below.

 function action_woocommerce_product_options_inventory_product_data($product) {

 if (is_product()){
 return;
 }
 $product = wc_get_product();
 $id = $product->get_id();

//calculating the active period of the product by attribute
$package =  $product->get_attribute( 'pa_package' );
//echo $package;
    switch($package){
            case 'Silver':
            $var = 1*24*60*60;
            break;              
            case 'Gold':
            $var = 60*24*60*60;
            break;
            case 'Platinum':
            $var = 90*24*60*60;
            break;      
            default:
            $var = 1*24*60*60;
            break;
            }

    // Get the date for the product published and current date
    $datetime_created  = $product->get_date_created(); // Get product created datetime
    $timestamp_created = $datetime_created->getTimestamp(); // product created timestamp

    $datetime_now      = new WC_DateTime(); // Get now datetime (from Woocommerce datetime object)
    $timestamp_now     = $datetime_now->getTimestamp(); // Get now timestamp

    $time_delta        = $timestamp_now - $timestamp_created; // Difference in seconds

    if( $time_delta > $var ){
                
 add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data', 10 );                   
global $product_object;
// Get meta
$value = $product_object->get_meta( '_ads_expired' );
// Checkbox
woocommerce_wp_checkbox( array( 
    'id'            => '_ads_expired', // Required, it's the meta_key for storing the value (is checked or not)
    'label'         => __( 'Ads Expired', 'woocommerce' ), // Text in the editor label
    'desc_tip'      => false, // true or false, show description directly or as tooltip
    'description'   => __( 'Check if product expired', 'woocommerce' ), // Provide something useful here
    'value'         => empty( $value ) ? 'yes' : $value // Checked by default
        
) );

 add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );        
 // Save Field
 function action_woocommerce_admin_process_product_object( $product ) {
 // Update meta
 $product->update_meta_data( '_ads_expired', isset( $_POST['_ads_expired'] ) ? 'yes' : 'no' );

 }

 }else{
                
            }
 }

The check box correctly showing on each product (Example is here > the check box has showing on the product that has a packages attribute with a silver value with the default check box display / has been checked).

But in reality it doesn't store value.

What am I missing here?

Essentially I want the product to have a checkbox which is auto-checked based on the time of product creation.

Please help me,

Thank You




jeudi 17 février 2022

Print result displayed in a textbox of an external window, inside the textobox of the main window (using the button of the main window)

In connection with this question solved by the kind acw1668, I place an executable code because I would simply like to display in the main window the result of a textbox that is generated in another external window. enter image description here

Basically there is the main file main.py that opens the file page1.py inside it. Inside page1 there is a label on which you click on and a new window opens called windows_option.py where the checkboxes, functions and buttons of the aforementioned question are present. Everything ok, no problem. Works well. If you click the Print button, things print correctly.

WHAT AM I TRYING TO DO? What I am trying to do, however, is not to print the results in the windows_option.py textbox, but simply print them in the page1.py textbox. Consequently I would like to delete the Print button in windows_option.py and use only the Print button of page1.py using it when I close the windows_option.py window. For the rest, I would like to keep the windows_option.py file as it is, with functions inside, etc. etc.

Of course, vote and answer accepted with a green tick for those who help me :)

Main.py

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk
from page1 import Page1

root = tk.Tk()
root.geometry('480x320')

topbar = tk.Frame(root, bg='#e10a0a', height=43)
topbar.pack(fill='x')

style = ttk.Style()
style.theme_use('default') # select a theme that allows configuration of ttk.Notebook
# put the tabs at the left with white background
style.configure('TNotebook', tabposition='wn', background='white', tabmargins=0)
# configure tab with white background initially, yellow background when selected
style.configure('TNotebook.Tab', background='white', width=10, focuscolor='yellow', borderwidth=0)
style.map('TNotebook.Tab', background=[('selected', 'yellow')])

nb = ttk.Notebook(root)
nb.pack(fill='both', expand=1)


page1 = Page1(nb)

nb.add(page1, text='aaaaa', compound='left')

root.mainloop()

Page1.py

import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import ttk
import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk

from Folder1.Folder2 import namefile

import windows_option
from windows_option import form


class Page1(tk.Frame):
    def __init__(self, master, **kw):
        super().__init__(master, **kw)


        #TEXTOBOX
        textbox = tk.Text(self, width=33, height=10, font=('helvetic', 12))
        textbox.place(x=30, y=40)

        #BUTTON
        button = tk.Button(self, text="Print", command= lambda: [aaa()])
        button.place(x=10, y=10)
        
        option= Label(self, text="Option", bg="#960000", foreground='white', font='Ubuntu 10')
        option.place(x=100, y=10)
        option.bind("<Button-1>", lambda event: windows_option.form(self))

windows_option.py

import sqlite3

from tkinter import *
from tkinter import ttk
import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk
from PIL import ImageTk


import tkinter.messagebox
from tkinter import messagebox


def form(parent):
    opz = tk.Toplevel(parent)
    opz.title("Option")
    opz.geometry("500x400")
    opz.config(bg="white")
    opz.state("normal")
    opz.transient(parent)



    class Option1(tk.Frame):
        def __init__(self, master, **kw):
            super().__init__(master, **kw)
            self.configure(bg='white')



            chk_lst = []
            fn_lst = [] 
            funclist = set() 

            Checkbutton1 = tk.IntVar()
            Checkbutton2 = tk.IntVar()
            Checkbutton3 = tk.IntVar()

            #CHECKBOX'S FUNCTIONS
            def Button1_func():
                if 5 + 3 == 8:
                    return True
                else:
                    return False

            def Button2_func():
                if 5 + 3 == 7:
                    return True
                else:
                    return False

            def Button3_func():
                if 5 + 3 == 8:
                    return True
                else:
                    return False

            def clicked(flag, func):
                if flag:
                    funclist.add(func)
                else:
                    funclist.remove(func)


            #CHECKBOX
            Button1 = tk.Checkbutton(self, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                                     bg="white", foreground='black', activebackground="white",
                                     command=lambda: clicked(Checkbutton1.get(), Button1_func))
            Button1.place(x=10, y=36)

            Button2 = tk.Checkbutton(self, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                                     bg="white", foreground='black', activebackground="white",
                                     command=lambda: clicked(Checkbutton2.get(), Button2_func))
            Button2.place(x=10, y=66)

            Button3 = tk.Checkbutton(self, text = "Checkbox 3", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                                     bg="white", foreground='black', activebackground="white",
                                     command=lambda: clicked(Checkbutton3.get(), Button3_func))
            Button3.place(x=10, y=146)

            chk_lst.extend([Checkbutton1, Checkbutton2, Checkbutton3])
            fn_lst.extend([Button1_func, Button2_func, Button3_func])


            #SAVE IN DATABASE
            def save():
                c.execute('INSERT INTO table1 VALUES (?, ?)', (idx, chk_btn.get()))
                c = conn.cursor()

                for idx,chk_btn in enumerate(chk_lst,start=1):
                    c.execute('UPDATE table1 SET Button1 = ? WHERE id = ?', (chk_btn.get(), idx))
                    rec = c.fetchall()

                    if rec:
                        c.execute("UPDATE table1 SET Button1=? WHERE id=?;", (chk_btn.get(),idx))
                    else:
                        c.execute("INSERT INTO table1 VALUES (?,?,?);", (idx,chk_btn.get()))
                    
                conn.commit()
                conn.close()

                messagebox.showinfo('SAVE', 'Saved successfully')


            #LOAD WHEN OPEN WINDOWS
            def load():
                conn = sqlite3.connect("value.db")
                c = conn.cursor()
                c.execute("SELECT * FROM table1")
                vals = c.fetchall()

                for val, chk_btn, func in zip(vals, chk_lst, fn_lst):
                    chk_btn.set(val[1])
                    
                    if val[1] == '1': 
                        funclist.add(func)

                conn.close()


            #BUTTON FUNCTION

            def aaa():
                # if need to clear the text box, uncomment below line
                #textbox.delete("1.0", "end")
                if funclist and all(func() for func in funclist): 
                    textbox.insert("end", "Ok")


            #SAVE BUTTON
            save = tk.Button(self, text="Save", bg='#b40909', foreground='white', command= save)
            save.place(x=10, y=10)

            #TEXTOBOX
            textbox = tk.Text(self, width=33, height=10, font=('helvetic', 12))
            textbox.place(x=10, y=220)

            #PRINT BUTTON
            button = tk.Button(self, text="Print", command= lambda: [aaa()])
            button.place(x=100, y=10)

            load()

    topbar = tk.Frame(opz, bg='#e10a0a', height=50)
    topbar.pack(fill='x')

    style = ttk.Style()
    #style.theme_use('clam') # select a theme that allows configuration of ttk.Notebook
    # put the tabs at the left with white background
    style.configure('TNotebook', tabposition='wn', background='#e10a0a', tabmargins=0)
    # configure tab with white background initially, yellow background when selected
    style.configure('TNotebook.Tab', background='#e10a0a', width=25, focuscolor='#e10a0a',  foreground='white', borderwidth=1)
    style.map('TNotebook.Tab', background=[('selected', '#b40909')])


    nb = ttk.Notebook(opz_gol)
    nb.pack(fill='both', expand=1)

    img = ImageTk.PhotoImage(file='/img/.....')
    img2 = ImageTk.PhotoImage(file='/img/.....')
    img3 = ImageTk.PhotoImage(file='/img/.....')
    img4 = ImageTk.PhotoImage(file='/img/.....')
    img5 = ImageTk.PhotoImage(file='/img/.....')

    page1 = Option1(nb)

    nb.add(page1, text='Option 1', image=img, compound='left')

    opz.mainloop()

Simple database:

CREATE TABLE "table1" (
    "id"    INTEGER,
    "Button1"   TEXT,
    PRIMARY KEY("id" AUTOINCREMENT)
);



Push only checked and not duplicated checkbox values to an array in Angular?

I have three checkboxes and I want to create an array which should have the values of the checked checkboxes values and should avoid pushing duplicating values.

This is what I have tried but values are pushing even though it is checked or not.

Can someone let me know what is the issue here?

.ts

dataSourceChange(event:any){

    var name = event.target.name;
    var isChecked = event.target.checked;
    const index = this.dataSource.findIndex((el) => el.id === name);

    if (index > -1) {
      this.dataSource[index].isChecked = isChecked;
    } else {
      this.dataSource.push(name);
    }
    this.dataSource = [...this.dataSource];
    console.log(this.dataSource);
  }

.html

 <input type="checkbox" name="om" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> OM</span>
 <input type="checkbox" name="fe" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> FE</span>
 <input type="checkbox" name="be" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> BE </span>



Ant Design How can I change Checkbox's Icon?

As you can see, I have a Checkbox element, I have an svg file and I want to place it in this checkbox. I don't know how to do this, I searched the internet but couldn't find it. It is not mentioned in the document, unfortunately, can you help?

https://codesandbox.io/s/h4eb1

As an example, I can show the required field at the bottom.




how to get the check box value in rails

im having a form check box, and i need to do some calculations before submiting the form based on the check box checked but im not sure how to fetch the check box value in rails

this is my code

<%= form.check_box 'active', :class => "icheck", :"data-checkbox" => "icheckbox_square-blue" %>

<%= form.label 'active', 'library_books' %>

before submitting the form i need to do some calculations based on the form checkbox value

so how to check whether the form is checked or not in rails




mercredi 16 février 2022

Apply multiple selection functions to checkboxes (they are saved and loaded from the database)

I have an executable code that saves and loads checked or unchecked checkboxes in a database. This works correctly.

Each checkbox has functions that I talked about in this question by kind user acw1668 (read the solution). I would like to apply the solution to my code of this question. You can take a cue from the response code of the user who solved the problem of multiple selection of checkboxes based on True or False. I would like to apply the solution of the other question of the link, to this complete code of mine that I report in this new question, because in addition the code of this new question has the saving and loading of checkboxes.

What I want? I would like that when you click on the Print button, "Ok" is printed in the textbox based on the multiple selection of the checkboxes and their function. If a checkbox returns False based on the function, then it does not print "ok". If a checkbox returns True based on the function, then it prints "ok" in the textbox. If all 3 checkboxes are selected, nothing is printed because among them there is checkbox2 which resist False. If, for example, checkboxes 1 and 3 are selected which are True, then "ok" is printed.

The code I want to add (that of the other question of link) whose purpose is to recognize the plurality of the multiple checkboxes selected is:

def clicked(flag, func):
    if flag:
        funclist.add(func)
    else:
        funclist.remove(func)

funclist = set()

def aaa():
    # if need to clear the text box, uncomment below line
    #textbox.delete("1.0", "end")
    if funclist and all(func() for func in funclist):
        textbox.insert("end", "Ok")

My code that saves and loads checkboxes, including GUI, is:

import sqlite3
from tkinter import *
from tkinter import ttk
import tkinter as tk
import tkinter.messagebox
from tkinter import messagebox

root = tk.Tk()
root.geometry("400x500")
root.configure(bg='white')

chk_lst = []

#CHECKBOX
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar() 

#CHECKBOX FUNCTION

def Button1_func():
    if 5 + 3 == 8:
        return True
    else:
        return False

def Button2_func():
    if 5 + 3 == 7:
        return True
    else:
        return False

def Button3_func():
    if 5 + 3 == 8:
        return True
    else:
        return False
    
Button1 = Checkbutton(root, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white", command=Button1_func)
Button1.place(x=10, y=60)

Button2 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white", command=Button2_func)
Button2.place(x=10, y=100)

Button3 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                      bg="white", foreground='black', activebackground="white", command=Button3_func)
Button3.place(x=10, y=140)

chk_lst.extend([Checkbutton1,Checkbutton2,Checkbutton3])


#SAVE IN DATABASE
def save():
    conn = sqlite3.connect("value.db")
    c = conn.cursor()
    
    for idx,chk_btn in enumerate(chk_lst,start=1):
        c.execute(f'SELECT button1 FROM table1 WHERE id=?',(idx,))
        rec = c.fetchall()

        if rec:
            c.execute("UPDATE table1 SET Button1=? WHERE id=?;", (chk_btn.get(),idx))
        else:
            c.execute("INSERT INTO table1 VALUES (?,?,?);", (idx,chk_btn.get()))
        
    conn.commit()
    conn.close()

    messagebox.showinfo("Saved successfully","Saved successfully")


#LOAD WHEN OPEN WINDOWS
def load():
    conn = sqlite3.connect("value.db")
    c = conn.cursor()
    c.execute("SELECT * FROM table1")
    vals = c.fetchall()
    
    for val,chk_btn in zip(vals,chk_lst):
        chk_btn.set(val[1])
    
    conn.close()


#SAVE BUTTON
save = Button(root, text="Save", bg='#b40909', foreground='white', command= save)
save.place(x=10, y=10)

#PRINT BUTTON
button = tk.Button(root, text="Print", command= lambda: [aaa()])
button.place(x=100, y=10)

#TEXTOBOX
textbox = tk.Text(root, width=33, height=10, font=('helvetic', 12))
textbox.place(x=10, y=220)

load()

root.mainloop()

Simple database:

CREATE TABLE "table1" (
    "id"    INTEGER,
    "Button1"   TEXT,
    PRIMARY KEY("id" AUTOINCREMENT)
);



Boostrapious contact form - how to add some checkbox inputs to form

I use this contact form by Boostrapious and works well, but I can't find solution to add some checkbox inputs and send values by email. I added HTML inputs, but I need help with php code. Can anyone help me?

This is a link to this tutorial and code: https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form

<form id="contact-form" method="post" action="contact.php" role="form">

    <div class="messages"> </div>

    <div class="controls">

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_name">Firstname *</label>
                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_lastname">Lastname *</label>
                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_email">Email *</label>
                    <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group checkbox">
                        <label for="checkboxoptions1">
                            <input type="checkbox" name="checkboxoptions[]" id="checkboxoptions1" value="checkboxoptions1">
                            Option1
                        </label>
                        <label for="checkboxoptions2">
                            <input type="checkbox" name="checkboxoptions[]" id="checkboxoptions2" value="checkboxoptions2">
                            Option2
                        </label>
                        <label for="checkboxoptions3">
                            <input type="checkbox" name="checkboxoptions[]" id="checkboxoptions3" value="checkboxoptions3">
                            Option3
                        </label>
                        <div class="help-block with-errors"></div>
                </div>          
                    
                    
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="form_message">Message *</label>
                    <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-12">
                <input type="submit" class="btn btn-success btn-send" value="Send message">
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <p class="text-muted">
                    <strong>*</strong> These fields are required. Contact form template by
                    <a href="https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form" target="_blank">Bootstrapious</a>.</p>
            </div>
        </div>
    </div>

</form>

and php code here

<?php
/*
 *  CONFIGURE EVERYTHING HERE
 */

// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo@domain.com>';

// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo@domain.com>';

// subject of the email
$subject = 'New message from contact form';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('checkboxoptions' => 'My options','name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); 

// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';

/*
 *  LET'S DO THE SENDING
 */

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
            
    $emailText = "You have a new message from your contact form\n=============================\n";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email 
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    // All the necessary headers for the email.
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $_POST['email'],
        'Return-Path: ' . $from,
    );
    
    // Send email
    mail($sendTo, $subject, $emailText, implode("\n", $headers));

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}


// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];



JQuery property evaluation not working as expected [duplicate]

I'm attempting to monitor changes to an existing checkbox in a form, and echo a specific message based on whether the checkbox is checked or not.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>test</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  </head>
  <body>

    <form id="form_for_debugging" action='#' method='POST'>
    <p>
        <input type="text" name='input_number' value="111" maxlength="6" placeholder="#">
    <p>
        <input type="checkbox" name='cb_field' id='cb_field' value='1'  > Check Me
    </form>

    <script>
        $('#cb_field').change(function() 
        {
            alert('change in cb_field detected...');
            if ($('cb_field').prop('checked')) 
            {
                alert('cb_field IS checked!');
            } else {
                alert('cb_field is NOT checked!');
            }

        });
    </script>

    </body>
</html>

The issue is that the if statement returns false (cb_field is NOT checked) whether the checkbox is actually checked or not.

JSFiddle

Am I using the wrong property to test for this or am I missing something else important?




Whenever I select last one from list of RecyclerView,the I go upside then Previous one will also be selected and last one is selection is gone [duplicate]

I am using recyclerview it has 22 items in the list but whenever I select any item for downward or upward it will gone and a previously selected one appears because it recycled that view.

fun setData(dataList: ArrayList<Playerv2>?) { this.dataList = dataList }

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val view: View
    val mInflater = LayoutInflater.from(context)
    view = mInflater.inflate(R.layout.adapter_favourite_playerv2, parent, false)
    return FavouritePlayerViewHolder(view)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    (holder as FavouritePlayerViewHolder).tvFavPlayerId.text = dataList?.get(position)?.shirtnumber.toString()
    holder.tvPlayerFirstName.text = dataList?.get(position)?.firstname + " " + dataList?.get(position)?.lastname
    holder.checkBox.text = dataList?.get(position)?.firstname + dataList?.get(position)?.lastname

    if (holder.checkBox.text.toString().equals(previouslySelectedOption, ignoreCase = true)) {
        holder.checkBox.isChecked = true
        lastCheckedCheckbox = holder.checkBox
        dataSelectedHolder(holder)
    } else {
        holder.checkBox.isChecked =
            false
        dataUnselectedHolder(holder)
    }
    holder.checkBox.text = ""


    holder.checkBox.setOnCheckedChangeListener { compoundButton, b ->
        if (lastCheckedCheckbox != null) {
            lastCheckedCheckbox?.isChecked = false
            lastCheckedCheckbox = null
            dataUnselectedHolder(holder)
        }
        if (holder.checkBox.isChecked) {
            lastCheckedCheckbox =
                holder.checkBox
            dataSelectedHolder(holder)
        }
        onRecyclerItemClicked.onItemClicked(dataList?.get(position)?.shirtnumber + ":" + dataList?.get(position)?.firstname + " " + dataList?.get(position)?.lastname)
    }
}

fun dataSelectedHolder(holder: FavouritePlayerViewHolder) {
    holder.tvPlayerFirstName.setTextColor(Color.RED)
    holder.tvFavPlayerId.setTextColor(Color.RED)
    holder.ConstraintbackgroundColor.setBackgroundResource(R.color.white)
}

fun dataUnselectedHolder(holder: FavouritePlayerViewHolder) {
    holder.tvFavPlayerId.setTextColor(Color.WHITE)
    holder.tvPlayerFirstName.setTextColor(Color.WHITE)
    holder.ConstraintbackgroundColor.setBackgroundResource(R.color.background_profile_color_0a2240)


    //Set imageView Here as well.
}

override fun getItemCount(): Int {
    return dataList!!.size
}

class FavouritePlayerViewHolder(itemView: View) :
    RecyclerView.ViewHolder(itemView) {
    var checkBox: CheckBox

    //        ImageView ivPlayerImage;
    var tvFavPlayerId: TextView
    var tvPlayerFirstName: TextView
    var tvFavPlayerLastName: TextView? = null
    var ConstraintbackgroundColor: ConstraintLayout

    init {
        checkBox = itemView.findViewById(R.id.cbFavPlayer)
        //            ivPlayerImage = itemView.findViewById(R.id.ivPlayerImage);
        tvFavPlayerId = itemView.findViewById(R.id.tvFavPlayerId)
        tvPlayerFirstName = itemView.findViewById(R.id.tvFavPlayerFirstName)
        ConstraintbackgroundColor = itemView.findViewById(R.id.ConstraintbackgroundColor)
    }
}

}

For Example, Previously I have selected the first option then I will select the last one in the list then I scrolled up and I see previously one is selected




How can I create a checkbox that only if it's checked the installer creates shortcuts on Desktop in InstallScript project in InstallShield?

This is weird that in InstallScript projects in InstallShield there is no dialog with a checkbox that allows the user to choose whether or not shortcuts on Desktop, Start Menu, or everywhere else are created at the end of the installation, and I never want to create installers that force creation of shortcuts on Desktop on users who don't want it.




Php with checkbox and array [duplicate]

Here's some sample of my code:

SQL Request which populate checkbox:

$sql = "SELECT * FROM tab WHERE name='$name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    ?>
    <form action="" name="showitems" method="post">
    <?php
while($row = $result->fetch_assoc()) {
    ?>
            <p>"<?php echo $name. " " .$row['description'];?>" <input type="checkbox" name="item[]" value=<?php echo $row['numitem'];?> /></p> 
    <?php
    
    }  
    ?>
    </form>
<?php
 
} else {
    echo "0 results";
    }

then on submit button I try to fetch all checked button to do some SQL tasks:

if(isset($_POST['item]){
    foreach($_POST['item'] as $currentitem) {
     //do some stuff
    }

} 

but it never goes to the foreach, try to echo some stuff and it does work.




Vuetify checkbox unchecked when changing pagination

i have datatable that contain checkbox in actions column

my datatable on template

<v-data-table
                    :headers="head"
                    :items="items"
                    :items-per-page="10"
                    class="elevation-1"
                    :loading="loading"
                >   
                    <template v-slot:item.filename={item}>
                        
                    </template>

                    <template v-slot:item.circuit={item}>
                        <v-chip :color="getStatus(item.circuit)" dark>
                            
                        </v-chip>
                    </template>

                    <template v-slot:item.actions="{ item, index }">
                        <div class="d-flex">
                            <v-icon
                                small
                                @click="deleteItem(item)"
                            >
                                mdi-delete
                            </v-icon>

                            <v-checkbox
                                multiple
                                class="ml-4"
                                :value="item"
                                :true-value="item"
                                v-model="fileselected"
                                v-if="isInused(item)"
                            >
                            </v-checkbox>
                        </div>
                    </template>
                </v-data-table>

my headers options on data

head: [
    { text: 'Fichier', align: 'start', value: 'filename' },
    { text: 'Circuit', align: 'start', value: 'circuit' },
    { text: 'Action', align: 'start', value: 'actions' }
],

so when i check some in the first page, it added to my model, i swtich to another page to check some other, and when i return to the previous page, all checkbox checked recentely are unchecked but my model value is inchanged; and i return to the other page, all checked checkbox are unchecked too. If i recheck the recently checked one, my model value still inchanged and if i uncheck it, the item is removed from my model. as if my checkbox not understand that he is checked and in the model when i change page;

Edit I have another checkbox that make all items checked, so all of it are in model, but when i change page, the sae behavior is occured, but if i used the option to show all row, all the unchecked in the page still unchecked, but the rest of the list are all checked

Other Edit I noticed that if i check some on one page, i switch page, and check other some in this page, all recently checked from the first page all removed from the model




Toggle Angular checkbox with string values instead of boolean true/false

I have to create three checkboxes in my form and their values need to toggle as "optin" and "optout" (string) as I check/uncheck the checkbox. Also I need to check all the checkboxes by default for "optin" value. I cannot figure out any solution, any help would be really appreciated :( as I am fairly new to angular

Here is the code I am working on

component.html

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">
    <div class="form-group">

   <input type="checkbox" formControlName="optOutFlag1" id="privacy" aria-labelledby="check1">
   <label for="privacy" id="check1"> Checkbox 1</label><br><br>

   <input type="checkbox" formControlName="optOutFlag2" id="security" aria-labelledby="check2">
   <label for="security" id="check2"> Checkbox 2</label><br><br>

   <input type="checkbox" formControlName="optOutFlag3" id="consent" aria-labelledby="check3">
   <label for="consent" id="check3"> Checkbox 3</label><br><br>

   <button> Submit Preference </button>

</div>
</form>

component.ts file

optOutForm:FormGroup
this.optOutForm=this.fb.group({
    optOutFlag1:["optin",Validators.required],
    optOutFlag2:["optin",Validators.required],
    optOutFlag3:["optin",Validators.required]
});  



mardi 15 février 2022

Is there an automatic way to recognize the plurality of multiple selected checkboxes?

I would like to obtain that if I select the first or the third checkbox individually I get the print in the textbox, or that if I select the first and the third at the same time I get the print in the textbox. Is there an automatic way to recognize the plurality of multiple selected checkboxes? The problem is this function:

def aaa():
    if Button1_func() and Button2_func() and Button3_func():
        textbox.insert("end", "Ok")

Currently I don't get this because in Button2_func I voluntarily wrote 5 + 3 = 7, so that's right, that's fine. However, I would also like that if I do NOT select checkbox2, but select the others 1 or 3 individually, or at the same time 1 and 3, I get the print of "ok" in the textotox

I guess the solution is to create other conditions for each type of multiple selection case, but I think there is a more automatic and better way without creating selection cases with conditions, because I will have to add dozens of other checkboxes and the situation would get complicated.

IMPORTANT: Please do not make sarcasm about True and False, because 5 + 3 = 8 is just a simple example to understand the logic of the checkboxes to which I will have to apply other different code. Leave the return True and False as is, without changing the functions.

    import sqlite3
    from tkinter import *
    from tkinter import ttk
    import tkinter as tk
    import tkinter.messagebox
    from tkinter import messagebox
    
    root = tk.Tk()
    root.geometry("600x600")
    root.configure(bg='white')
    
    Checkbutton1 = IntVar()
    Checkbutton2 = IntVar()
    Checkbutton3 = IntVar()
    
    #CHECKBOX'S FUNCTIONS
    def Button1_func():
        if 5 + 3 == 8:
            return True 
        else:
            return False
       
    def Button2_func():
        if 5 + 3 == 7:
            return True
        else:
            return False
    
    def Button3_func():
        if 5 + 3 == 8:
            return True
        else:
            return False
       
    #CHECKBOX 
    Button1 = Checkbutton(root, text = "Checkbox 1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                          bg="white", foreground='black', activebackground="white", command=Button1_func)
    Button1.place(x=10, y=36)
    
    Button2 = Checkbutton(root, text = "Checkbox 2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1,
                          bg="white", foreground='black', activebackground="white", command=Button2_func)
    Button2.place(x=10, y=66)
    
    Button3 = Checkbutton(root, text = "Checkbox 3", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 1,
                          bg="white", foreground='black', activebackground="white", command=Button3_func)
    Button3.place(x=10, y=146)
    
    #BUTTON FUNCTION
    def aaa():
        if Button1_func() and Button2_func() and Button3_func():
            textbox.insert("end", "Ok")
    
    #TEXTOBOX
    textbox = tk.Text(root, width=33, height=10, font=('helvetic', 12))
    textbox.place(x=30, y=220)
    
    #BUTTON
    button = tk.Button(root, text="Ok", command= lambda: [aaa()])
    button.pack()


root.mainloop()



Can't access checkbox value in flutter_picker's footer

I'm new to flutter and I'm trying to get a checkbox value that's in a flutter_picker's footer. I'm using the flutter_picker for picking a date value.

void showYearMonthPicker(BuildContext context) {
    Map japaneseMap =  getJapaneseYearMap();
    Picker picker = Picker(
        adapter: NumberPickerAdapter(data: [
          NumberPickerColumn(
              begin: 1,
              end: 5,
              initValue: 1,
              onFormatValue: (v) {
                return "$v年(" + japaneseMap["$v"] + ")";
              }
          ),
          NumberPickerColumn(
              begin: 1,
              end: 12,
              initValue: 1,
              onFormatValue: (v) {
                return "$v月";
              }
          ),
        ]),
        cancelText: "cancel",
        confirmText: "confirm",
        columnFlex: [2, 1],
        footer: CheckboxWithState(),
        selectedTextStyle: TextStyle(color: Colors.deepOrangeAccent),
        onConfirm: (Picker picker, List value) {
          // use checkbox _value when confirm button is pressed. 
          // for example, use default dates instead of picker selection if checkbox is selected. 
        }
    );
      picker.show(_scaffoldKey.currentState!);
    }

At first the checkbox wasn't displaying the updated value so I put the checkbox with its value in another statefulwidget class and put it in the footer of my Picker.

class CheckboxWithState extends StatefulWidget {
  @override
  _CheckboxWithState createState()=> new _CheckboxWithState();
}


class _CheckboxWithState extends State<CheckboxWithState>{
  bool _value = false;

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

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 30.0,
        alignment: Alignment.center,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Checkbox(
                value: _value,
                onChanged:(isCheck){
                  setState(() {
                    _value=isCheck!;
                  });
                } ,
              ),
              Text("not determined",
                  style: TextStyle(fontSize: 18)),
            ]
        )
    );
  }

  bool getDetermined(){
    return _value;
  }
}

I want to use the checkbox value in the onConfirm of my Picker class but I don't know how to access it. The solution could be very simple as I don't know the basics of flutter very well.




focus-within css not working for html label

I'm trying to build a dropdown list with checkboxes in dropdown area.

Here is the code I'm using:

.search-box {
  color: black;
  width: 450px;
}

.search-box .fake-tb {
  display: flex;
  flex-wrap: nowrap;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  box-sizing: border-box;
  border-radius: 6px;
  padding: 2px 5px;
  margin: auto;
  height: 35px;
  max-width: 700px;
}

.search-box .fake-tb * {
  border: 0 !important;
  height: auto !important;
}

.search-box .fake-tb input[type=search] {
  border-radius: 6px;
  width: 100% !important;
  outline: none;
}

.search-box .fake-tb img {
  vertical-align: middle;
  margin: auto;
  padding: 2px;
}

.search-box .dropdown {
  display: none;
  position: absolute;
  border: 1px solid #e5e5e5;
  cursor: default;
  background: white;
  z-index: 99999;
  text-align: left;
}

.search-box:focus-within .dropdown {
  display: block;
  background-color: white;
  color: black;
}

.search-box .dropdown>table {
  padding: 3px 10px 3px 2px;
  width: 100%;
}

.search-box .dropdown table tr:hover {
  background-color: lightskyblue;
}
<div>line before ...</div>
<div class="search-box">
  <div class="fake-tb">
    <input name="ctl32$txtCusSearch" id="ctl32_txtCusSearch" auto-complete="off" type="search">
    <img src="search.svg" />
  </div>
  <div class="dropdown">
    <table id="ctl32_lstOptions">
      <tbody>
        <tr>
          <td><input id="ctl32_lstOptions_0" name="ctl32$lstOptions$0" type="checkbox" value="Value1"><label for="ctl32_lstOptions_0">Checkbox 1</label></td>
        </tr>
        <tr>
          <td><input id="ctl32_lstOptions_1" name="ctl32$lstOptions$1" type="checkbox" value="Value2"><label for="ctl32_lstOptions_1">Checkbox 2</label></td>
        </tr>
        <tr>
          <td><input id="ctl32_lstOptions_2" name="ctl32$lstOptions$2" type="checkbox" value="Value3"><label for="ctl32_lstOptions_2">Checkbox 3</label></td>
        </tr>
        <tr>
          <td><input id="ctl32_lstOptions_3" name="ctl32$lstOptions$3" type="checkbox" value="Value4"><label for="ctl32_lstOptions_3">Checkbox 4</label></td>
        </tr>
        <tr>
          <td><input id="ctl32_lstOptions_4" name="ctl32$lstOptions$4" type="checkbox" value="Value5"><label for="ctl32_lstOptions_4">Checkbox 5</label></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
<div>line after ...</div>

screenshot

There are 2 problems I'm struggling with:

  1. Clicking on checkbox works fine, but clicking on its label closes the dropdown. How can I keep it open?

  2. How do I make the width of dropdown equal to the textbox area, without specifying a fixed width?

I'll prefer a pure CSS solution if possible.




lundi 14 février 2022

Laravel Get Values from checkbox 0 turn null

I have database like this:

enter image description here

column cek for define checkbox with code like this:

<input type="checkbox" value="" name="ada[]" @if($d->cek) checked @endif>

When its checked it will gave value '1', and when its unchecked its supposed to give value '0' but instead '0' i got null. Anyone here how should it? Thank you.




TypeError: cannot read properties of null [duplicate]

I have a to-do list which I want to be able to cross out tasks as they're completed, as well as delete them by clicking their corresponding "X" button.

I use a global variable (row) which is added to different elements' ID. This is how I differentiate them from other task entries.

This works fine when deleting a task, but not when the checkbox is checked/unchecked. I want to toggle the add-strikethrough CSS class whenever a task's checkbox is clicked.

When a checkbox is checked, there is an error in console stating :

Uncaught TypeError: Cannot read properties of null (reading 'classList') at strikeTask (script.js:80:7)

Haven't been able to find anything helpful regarding this error from Google.

Relevant HTML:

    <body>
        <h1>To-Do-List</h1>
        <form action="" onsubmit="createElements();return false" id="todo" autocomplete=off>
            <input type="text" maxlength="25" id="enter-task" placeholder="Enter a Task">
            <button type="button" id="submit-task" onClick="createElements()"><span>+</span></button>
        </form>

        <h4 class="hide" id="task-header">current tasks</h4>
            
        <form class="hide" id="container">
            <!--This is where the addTask elements go-->
        </form>
        
        
        <script src="script.js"></script>
    </body>

Relevant CSS:

.add-strikethrough{
    text-decoration: line-through;
    text-decoration-color: black;
}

Javascript:

var row = 0;

function createElements(){ 

    //create Checkbox
    var checkbox = document.createElement("input");
    checkbox.setAttribute("type", "checkbox");
    checkbox.setAttribute("id", "entryCheckbox");
    checkbox.setAttribute("value", "unchecked");
    checkbox.setAttribute("onClick", "strikeTask(" + row +");")

    //create label using value from input box
    var label = document.createElement("label");
    label.setAttribute("id", "entryLabel"+row);
    label = document.getElementById("enter-task").value;

    //create deleteTask img
    var deleteTask = document.createElement("img");
    deleteTask.src = "images/x.svg";
    deleteTask.setAttribute("id", "delete-task");
    deleteTask.setAttribute("onClick", "deleteRow(" + row +");")
    
    addTask(checkbox, label, deleteTask);
}

//This function appends the elements
function addTask(box, label, x){

    
    const tasks = document.getElementById("container");
    
    const newTask = document.createElement('div');
    newTask.classList.add('task-entries');

    const header = document.getElementById('task-header');

    //Makes sure input field is not empty
    if(label !== ""){

        //Show task container and header
        if(tasks.classList.contains("hide")){
            tasks.classList.replace('hide', 'task-container');
            header.classList.replace('hide', 'show-header')
        };
        //Append newTask to tasks container
        tasks.appendChild(newTask);
            newTask.setAttribute("id", "contentDiv"+row);
        newTask.appendChild(box);
        newTask.appendChild(document.createTextNode(label));
        newTask.appendChild(x);
            row++;
        
        //Resets input field after task is added
        document.getElementById("enter-task").value = null; 
    }
}



function deleteRow(ID){

    document.getElementById('contentDiv'+ID).remove();

    tasks = document.getElementById('container');
    header = document.getElementById('task-header');

    //Hide header and task container if no tasks exist
    if(tasks.children.length == 0){
        tasks.classList.replace('task-container', 'hide');
        header.classList.replace('show-header', 'hide');
    }
}

function strikeTask(ID){

    const x = document.getElementById('entryLabel'+ID);

    x.classList.toggle('add-strikethrough');
    
}

I appreciate any help!




Check box checked property is not updating on initial check

I have below code where I am checking or unchecking the checkbox based on some conditions, and I came across an issue where I am trying to check the checkbox, and it is failing the first time and from the second time onwards works perfectly,

export const AntdDefaultOverrideInputNumberAdapter = ({
  input: { onChange, value },
  disabled,
  defaultValue,
  formatter,
  ...rest
}) => {
  const [isDefaultValueOverriden, setIsDefaultValueOverriden] = useState(
    !!value && value !== defaultValue
  );

  const handleCheckboxChange = () => {
    const hasOverride = !isDefaultValueOverriden;
    setIsDefaultValueOverriden(hasOverride);
    onChange(hasOverride && !!value ? value : defaultValue);
  };

  const handleOverrideChange = (v) => {
    onChange(v);
  };

  return (
    <Badge
      offset={[0, -6]}
      count={
        <div>
            <Checkbox
              disabled={disabled}
              checked={isDefaultValueOverriden}
              onChange={handleCheckboxChange}
              style=
            />
        </div>
      }
    >
      <InputNumber
        size="small"
        onChange={handleOverrideChange}
        disabled={disabled || !isDefaultValueOverriden}
        style=
        value={isDefaultValueOverriden ? value : defaultValue}
        formatter={formatter}
        {...rest}
      />
    </Badge>
  );
};

I am not sure where I am wrong with the above code, The problem only appears on trying to check the checkbox the first time, and it disappears from the second time onwards..

Could anyone suggest any idea on this? Many thanks in advance!!

I am using "ANTD" library for checkbox




How can I disable two textboxes when a checkbox is checked? I am using Angular 6

form.html

<input id="okornot" class="form-check-input" type="checkbox" name="chkbx1" formControlName="" (change)="checkBelts($event)" />

form.ts

checkBelts(val, event) {
    this.checkBelt = val.target.checked;

    if (val.target.checked == true) {
      this.txtcheck = false;
    } else {
      this.txtcheck = true;
    }
    console.log("value", this.txtcheck);
  }



dimanche 13 février 2022

Toggle class on user-created elements [duplicate]

I have a to-do list which I want to be able to cross out tasks as they're completed, as well as delete them by clicking their corresponding "X" button.

I use a global variable (row) which is added to different elements' ID. This is how I differentiate them from other task entries.

This works fine when deleting a task, but not when the checkbox is checked/unchecked. I want to toggle the add-strikethrough CSS class whenever a task's checkbox is clicked.

When a checkbox is checked, there is an error in console stating :

Uncaught TypeError: Cannot read properties of null (reading 'classList') at strikeTask (script.js:80:7)

Haven't been able to find anything helpful regarding this error from Google.

Relevant HTML:

    <body>
        <h1>To-Do-List</h1>
        <form action="" onsubmit="createElements();return false" id="todo" autocomplete=off>
            <input type="text" maxlength="25" id="enter-task" placeholder="Enter a Task">
            <button type="button" id="submit-task" onClick="createElements()"><span>+</span></button>
        </form>

        <h4 class="hide" id="task-header">current tasks</h4>
            
        <form class="hide" id="container">
            <!--This is where the addTask elements go-->
        </form>
        
        
        <script src="script.js"></script>
    </body>

Relevant CSS:

.add-strikethrough{
    text-decoration: line-through;
    text-decoration-color: black;
}

Javascript:

var row = 0;

function createElements(){ 

    //create Checkbox
    var checkbox = document.createElement("input");
    checkbox.setAttribute("type", "checkbox");
    checkbox.setAttribute("id", "entryCheckbox");
    checkbox.setAttribute("value", "unchecked");
    checkbox.setAttribute("onClick", "strikeTask(" + row +");")

    //create label using value from input box
    var label = document.createElement("label");
    label.setAttribute("id", "entryLabel"+row);
    label = document.getElementById("enter-task").value;

    //create deleteTask img
    var deleteTask = document.createElement("img");
    deleteTask.src = "images/x.svg";
    deleteTask.setAttribute("id", "delete-task");
    deleteTask.setAttribute("onClick", "deleteRow(" + row +");")
    
    addTask(checkbox, label, deleteTask);
}

//This function appends the elements
function addTask(box, label, x){

    
    const tasks = document.getElementById("container");
    
    const newTask = document.createElement('div');
    newTask.classList.add('task-entries');

    const header = document.getElementById('task-header');

    //Makes sure input field is not empty
    if(label !== ""){

        //Show task container and header
        if(tasks.classList.contains("hide")){
            tasks.classList.replace('hide', 'task-container');
            header.classList.replace('hide', 'show-header')
        };
        //Append newTask to tasks container
        tasks.appendChild(newTask);
            newTask.setAttribute("id", "contentDiv"+row);
        newTask.appendChild(box);
        newTask.appendChild(document.createTextNode(label));
        newTask.appendChild(x);
            row++;
        
        //Resets input field after task is added
        document.getElementById("enter-task").value = null; 
    }
}



function deleteRow(ID){

    document.getElementById('contentDiv'+ID).remove();

    tasks = document.getElementById('container');
    header = document.getElementById('task-header');

    //Hide header and task container if no tasks exist
    if(tasks.children.length == 0){
        tasks.classList.replace('task-container', 'hide');
        header.classList.replace('show-header', 'hide');
    }
}

function strikeTask(ID){

    const x = document.getElementById('entryLabel'+ID);

    x.classList.toggle('add-strikethrough');
    
}

I appreciate any help!




vendredi 11 février 2022

Filtering data with selections and checkboxes in Flexdashboard

In a flexdashboard, I want to allow a selection by having selectInput() combined with a checkboxGroupInput(). But the data is not updated correctly and I cannot figure out what is wrong.

I used the toy example from this SO-example [LINK] and included a checkbox. It seems that the Checkbox is still ignored and messes up the other parts of the code.

It would be great if someone could adjust the code so that selection can be based on one of the three columns Team, Name or Year.

---
title: "example"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    runtime: shiny
---

```{r setup, include=FALSE}
library(DT)
library(shiny)

users <- data.frame(
  Name = c("Allan A","Barbara B","Charles C","Darwin D","Evelyn E","Frank F","Greg G","Hans H"),
  Team = c(1,2,3,3,2,1,2,2),
  Year = c(1999,1999,1999,2000,2000,2000,2003,2003), 
  stringsAsFactors = FALSE)
```

Inputs {.sidebar}
=======================================================================
### Input Variables

```{r global_input}

### selection Input based on columns Team and Name
selectInput("teaminput","Team",c("All", unique(users$Team)), selected="All")
selectInput("userinput","User Name", c("All", unique(users$Name) ), selected="All")

### Add Input from CheckboxGroup based on Year starting with all
checkboxGroupInput("yearinput", label = "Year",choices =  unique(users$Year), selected=unique(users$Year), inline = TRUE)


### Filter Team based on one of the three choices (Team, Name, Year)
teamFiltered <- reactive(users[input$teaminput=="All" | 
                                 users$Team==input$teaminput |
                                 users$Year ==input$yearinput,])

### Observe if userinput changes based on SELECTION
observe(updateSelectInput(session,"userinput", 
                          choices = c( unique(teamFiltered()$Name)), 
                          selected="All"))

### Observe if yearinput changes based on CHECK BOX
observe(updateCheckboxGroupInput(session,"yearinput", 
                                  choices =  teamFiltered()$Year,
                                  selected="All"))

```

Results
=======================================================================
### Intake Coordinator KPIs

```{r daily_table}
userFiltered <- reactive(teamFiltered()[input$userinput=="All" | 
                         teamFiltered()$Name==input$userinput | 
                         teamFiltered()$Year==input$yearinput,])

renderDataTable(userFiltered())
```



check box design issue after migrating my native script application

I'm using "@nstudio/nativescript-checkbox": "^2.0.4", package for designing the check box in my application. After migrating, the check box design not matching properly. Facing alignment issue in checkbox.

How to fix this design issue?

Click here to see error image




How to check if a checkbox has been selected using ShinyDashboard?

I have created an app using ShinyDashboard that has one checkboxInput. If you click on it, you will see two checkboxGroupInput where you can select 1 or 2 choices.

The idea is that if you click 1 option, you will subset your dataframe with your individual choice, or if you click both options, you will subset your dataframe with those two options.

IMAGE 1

However, I am having problems to verify which option of the checkboxGroupInput the user has selected.

Here is a reproducible example. As you can see, if you select both, you end in the first if statement, subsetting two columns. However, if you select one option (setosa, for example), you are still subsetting by the two, because it doesn't recognise the choice that you have selected. However, if you select "virginica" it is subsetted.

Moreover, it appears this warning all the time.

Warning in if (c("setosa", "virginica") %in% input$species_choice) { : the condition has length > 1 and only the first element will be used

The code:

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
  
  dashboardHeader(title = "Dashboard"),
  ## Sidebar content
  dashboardSidebar(
    sidebarMenu(
      menuItem("App1", tabName = "App1", icon = icon("th"))
      
    )
  ),
  
  dashboardBody(
    fluidRow(
      tabItems(
        
        tabItem(tabName = "App1",
                sidebarPanel(
                  checkboxInput(inputId = "species", label = "Select species"),
                  
                  conditionalPanel(
                    condition = "input.species",
                    style = "margin-left: 20px;",
                  
                    checkboxGroupInput("species_choice", "Choose the species:",
                                       choices = c("setosa", "virginica"), selected = c("setosa", "virginica"))),
                ),
                mainPanel(
                  dataTableOutput("table")
                  
                )
        )
      )
    )
  )
)

server <- function(input, output, session) {
  
  mytables <- reactive({
   if(input$species){
     
     df_setosa <- iris[iris$Species=="setosa",]
     df_virginica <- iris[iris$Species=="virginica",]
     df_both <- rbind(df_setosa, df_virginica)
     
     if(c("setosa", "virginica") %in% input$species_choice){
       print("both")
       return(df_both)
     }
     
     if("setosa" %in% input$species_choice){
       print("setosa")
       return(df_setosa)
     }
     
     if("virginica" %in% input$species_choice){
       print("virginica")
       return(df_virginica)
     }
   }
  })
  
  output$table <- renderDataTable({
    mytables()
  })
  
}

shinyApp(ui, server)

I have tried this way too, but it doesn't work:

if(input$species_choice == "setosa"){
        print("setosa")
        return(df_setosa)
      }
      
      if(input$species_choice == "virginica"){
        print("virginica")
        return(df_virginica)
      }
      
      if(input$species_choice == c("setosa, virginica"){
        print("both")
        return(df_both)
      }

Does anyone know how to help me, please?

Thanks in advance