vendredi 30 avril 2021

Trying to add the values of 4 check boxes together

this is probably very very simple but if someone could steer me int he right direction I would appreciate it.

Im trying to make a check list where the values of each box checked are all added together and displayed in a textbox with the code " weekExtras.Text = Convert.ToString(calWeekExtras()); " where the checkbox values are exAc = 1, exPt = 20, exDi = 20 and exVi = 2

(This is what I have so far)

 *public double calWeekExtras()
    {
        double exAc= 00.00;
        double exPt = 00.00;
        double exDi = 00.00;
        double exVi = 00.00;
        double total = 00.00;
        if (access.Checked)
        {
            exAc = 1.00;
        }
        else if (personalT.Checked)
        {
            exPt = 20.00;
        }
        else if (diet.Checked)
        
            exDi = 20.00;
        }
        else (accessVid.Checked)
        {
            exVi = 2.00;
        }
        total += exAc + exPt + exDi + exVi;
        return total;*

I think the 'total += exAc + exPt + exDi + exVi;' is wrong but I'm having trouble finding the answer.




check checkboxes for values that exists in a list

I am trying to check checkboxes that have values in a list of strings returned from a ModelForm class.

The field is declared in models.py file like this:

class IC(models.Model):
    class Meta:
        verbose_name = "Get Info"

    p_data = MultiSelectField("Some data", max_length=255, choices=choices.P_DATA_CHOICES, blank=True, null=True)

P_DATA_CHOICES looks like this

P_DATA_CHOICES = [
    ("ch1", "Choice 1"),
    ("ch2", "Choice 2"),
    ("ch3", "Choice 3"),
    ("ch4", "Choice 4"),
    ("ch5", "Choice 5"),
]

I have this ModelForm class in forms.py that I am implementing to the entire class:

class ICForm(ModelForm):
class Meta:
    model = IC
    exclude = ["fk_field"]


def __init__(self, *args, **kwargs):
    super(ICForm, self).__init__(*args, **kwargs)

    for i, f in self.fields.items():
        f.widget.attrs['class'] = "custom_class"

In my template I am generating the checkboxes as such:


If I check a few checkboxes (say Choice 1 and Choice 2) and submit the form, I can see ch1,ch2 in the p_data column of the database, but when I load the page again, their respective checkboxes are not checked.

I believe this has to do with this logic I'm trying to apply

Liquid error: Unknown operator in

I'm not sure if those values are sent from the ModelForm or not, and how I may access them in the template and loop through them.




There is problem with checkbox. I want to delete the content with delete button when checkbox is selected

I trying to make a web application but there is a small problem in checkbox. whenever I select the checkbox it gives me output saying undefined. I want to delete the content with delete button when checkbox is selected I am not able to catch the problem what exactly causing it can anyone explain me. need Help

var btnAdd = document.getElementById("add");
var btnRem = document.getElementById("rem");
var container = document.getElementById("cont");
var frm = document.getElementById("frm");

btnAdd.addEventListener("click", () => {
  var x = document.getElementById("txt").value;
  var y = document.getElementById("country");
  var h = document.getElementById("country").value;

  var element4 = document.createElement("input");
  element4.type = "checkbox";
  element4.id = "check";

  if (!x || !h) {
  } else {
    if (y.selectedIndex == 0) {
    } else {
      var base = document.createElement("div");
      var b = container.appendChild(base);
      b.id = "base";

      var element = document.createElement("div");
      var d = b.appendChild(element);

      d.appendChild(element4);

      var element1 = document.createElement("input");
      d.appendChild(element1);
      element1.value = x;
      element1.id = "text2";
      element1.readOnly = true;

      var array = new Array();

      for (var i = 0; i < y.length; i++) {
        array.push(y.options[i].text);
      }

      var element = document.createElement("div");
      var d1 = b.appendChild(element);

      var element2 = document.createElement("select");
      var O = d1.appendChild(element2);

      for (var j = 1; j < array.length; j++) {
        O.innerHTML +=
          "<option value=" + array[j] + ">" + array[j] + "</option>";
      }

      O.value = h;

      frm.reset();
      y.selectedIndex = 0;

    
    }
  }


btnRem.addEventListener("click",()=>{

    var g = document.getElementById("check").checked;
        
        if ( g == true ) {
            alert( this.value )
            this.parentElement.parentElement.remove();
            ;


        } 
})


 



});
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
input,button{
    border-radius: none;
    outline: none;
    border: 1px solid black;
}
.select-country{
    max-width: 100%;
}

.container{
    max-width: 80%;
    margin: 0 auto;
    padding-top: 50px;
}

.container-1{
    max-width: 50%;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
}
form{
    max-width: initial;
}
.container-1 :first-child{
    flex: 3;
}
.container-1 div{
    flex: 1;
}

.container-1 div input,.container-1 div select{
    min-width: 100%;
    padding: 5px 0;
}

#add,#rem{
    min-width: 100%;
    padding: 5px 0;
}

.container-2{
    max-width: 50%;
    margin: 0 auto;
    padding-top: 50px;
}

.container-2 #base{
display: flex;
padding: 10px 0;
}
.container-2 :first-child{
flex: 3;
display: flex;
}

.container-2 :first-child #check{
    flex: 0.1;
    padding: 5px 0;
}
.container-2 :first-child #text2{
    flex: 3;
    padding: 5px 0;
}
.container-2 div{
flex: 1;
}

.container-2 div select{
    padding: 5px 0;
    min-width: 100%;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="select-country">
      <div class="container">
        <div class="container-1">
          <div>
            <form action="" id="frm"><input type="text" id="txt" /></form>
          </div>
          <div>
            <form action="" id="frm" onsubmit="return false">
              <select id="country">
                <option value="select-country" selected disabled>
                  select country
                </option>
                <option value="India">India</option>
                <option value="S.Korea">S.Korea</option>
                <option value="China">China</option>
                <option value="UAE">UAE</option>
                <option value="finland">finland</option>
                <option value="Germany">Germany</option>
                <option value="France">France</option>
                <option value="UK">UK</option>
                <option value="Bhutan">Bhutan</option>
                <option value="USA">USA</option>
                <option value="Austrailia">Austrailia</option>
              </select>
            </form>
          </div>
          <div>
            <button id="add" type="submit">Add</button>
          </div>
          <div>
            <button id="rem" type="submit">Delete</button>
          </div>
        </div>
        <div class="container-2" id="cont"></div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>



My question is about checkbox gird I am trying to make a google form for the discord server but not getting proper data

When someone is submitting the form I am not getting proper data in the discord server like I have used check box gird system in my form but I am not getting the data of row just getting the data of column I couldn't solve this issue can anybody help me.

I can even send pictures for better understanding.




How to check at least one selected checkbox using form validation jquery?

html

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="/jquery-ui.js"></script>
<body>
    <form id="applicationForm" method="POST" class="valida en" action="../../lib/air-condition-request.php">
    <label class="serviceDay">
    <input type="checkbox" id="airConDaily">Daily 
    <input type="checkbox" id="airConMon" name="monday" value="1">Monday
    <input type="checkbox" id="airConTue" name="tuesday" value='1'>Tuesday
    <input type="checkbox" id="airConWed" name="wednesday" value='1'>Wednesday
    <input type="checkbox" id="airConThur" name="thursday" value='1'>Thursday
    <input type="checkbox" id="airConFri" name="friday" value='1'>Friday
    <input type="checkbox" id="airConSat" name="saturday" value='1'>Saturday
    <input type="checkbox" id="airConSun" name="sunday" value='1'>Sunday
    <input type="checkbox" id="airConPh" name="ph" value='1'> Public Holiday
    </label>
    <input type="hidden" name="type" value="2">
    <input type="submit" name="button" id="button" value="Submit" class="all-btn">
    </form>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script src="../../js/form-validation.js"></script>
</body>
                  

form-validation jquery

$('#itemForm').validate({
  errorClass:"validationError",
    rules:{
    
    },
    messages:{
      
    }
  

});

Hello all,

I check many answers about at least one selected checkbox but they cannot solve my question.

How the system shows error if the the user does not choose any checkbox.

Thank you




jeudi 29 avril 2021

How to put Dynamic id in checkbox in javascript?

I am attaching my html code to a variable(ctableData) which I am again appending to the main container. Now I want to have dynamic id for the checkbox, So I am running a loop and incrementing the value of k in every iteration and then assigning the k as checkbox id. But this doesnt seem to be working?

for(let k =1; k< x.length; k++){
ctableData += '<div class="table_container"><table id="table1" class="checkboxdiv"><tbody><tr><th>'+plan[0].medicalPlans[i].brokerName+' <input type="checkbox" id= k name="table1" value="table1" onchange="myFunction(event)"> </th></tr>
}



PRINT OUT THE TEXT CORRESPONDING TO A SET OF MARKED CHECKBOX IN PYTHON

i am currently working on checkbox detection where i am trying to print of the question along with the text of only the marked checkbox. the code i have used is given on the below link https://towardsdatascience.com/checkbox-table-cell-detection-using-opencv-python-332c57d25171 or https://github.com/Sreekiranar/box_detection_opencv i have taken a random image with some marked checkboxes. this is the image i used. thank you in advance for your help.




Checkbox in angular without ngmodel? what to replace with?

I have a checkbox that I need to enhance, previous it handled a call to the backend but now this is no longer needed, and is only required to be a checkbox that turns off other checkboxes if selected:

    <label class="custom-control custom-checkbox" style="display: block">
      <input type="checkbox" class="custom-control-input" id="myCheckbox" name="myCheckbox"
             [(ngModel)]="checkboxPolicy" (ngModelChange)="parentcheckbox($event,child1,child2,child3)">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description">
        <span id="checkboxstart">
        </span>
      </span>
    </label>

I need to remove the ngModel altogther, but the input requires it, is there away I can have a data-less checkbox that exists purely for UI purposes. Doesnt control any data, just controls the other boxes in the ngModelChange method.




How to Make Checkbox Flutter Dynamically From Mysql?

I want to make dynamically checkbox from data in database mysql. But i don't know how to make it. the error that appears when executing the code is "This function has a return type of 'Widget', but doesn't end with a return statement. Try adding a return statement, or changing the return type to 'void'." And "This function has a return type of 'FutureOr', but doesn't end with a return statement. Try adding a return statement, or changing the return type to 'void'."

class TambahDataTanaman extends StatefulWidget {
  @override
  _TambahDataTanamanState createState() => _TambahDataTanamanState();
}

class _TambahDataTanamanState extends State<TambahDataTanaman> {
  bool selected = false;
  var dataTanah = List<bool>();
  Future<bool> getData() async {
    final response = await http.get("http://192.168.1.12/tanampedia/tanahtampil.php");
    var jsonData = json.decode(response.body);

    List dataTanah2 = [];

    for (var u in jsonData) {
      var data = jsonData(u["id"], u["nama"]);

      dataTanah2.add(data);
      dataTanah.add(false);
    }
    print(dataTanah2.length);
  }

  Widget build(BuildContext context) {
return Scaffold(
        appBar: AppBar(
          title: Text("Tambah Data Tanaman"),
          backgroundColor: Colors.green,
        ),
        body: SingleChildScrollView(
          child: Form(
            key: addTanamanKey,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: ListView(
                children: [
                  new Column(
                    children: [
                     
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: _image == null
                            ? new Text(
                                "Tidak Ada Gambar yang Dipilih, Silahkan Pilih Gambar")
                            : new Image.file(_image),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          new RaisedButton(
                            child: Icon(Icons.image),
                            onPressed: getImageGallery,
                          ),
                        ],
                      ),
                      FutureBuilder<bool>(
                        future: getData(),
                        builder: (context, snapshot){
                        if(snapshot.hasData){
                          if(snapshot.data != null){
                            return CheckboxListTile(title: const Text('Tidak Ada'),
                            value: snapshot.data,
                            onChanged: (val){
                              setState(() {
                                                              
                                                            });
                            });
                          }
                        }
                      },),
                      new RaisedButton(
                          child: new Text(
                            "Tambah Data",
                            style: TextStyle(color: Colors.white),
                          ),
                          color: Colors.green,
                          onPressed: () {}),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));}
}

there are my code for checkbox, but i am confused how to solve the problem about checkbox dynamically retrieve data from database mysql.




How to set multi check box in jira using python

I actually want to enable First time Resolution check box via python which is displayed in the Resolved workflow in a separate window I could fetch the feild Id. I have tried many ways but couldn't succeed.(Python)

here are few ways I have tried:

  1. issue.fields.customfield_10112 = [{"value": "Resolved First Time"}] or [{"value": "Yes"}]

The above hasn't worked.

  1. fields = {"customfield_10112]: [{"value": "Resolved First Time"}]} issue.update(fields=fields)

the above method I have tried throws an error:-text: Field "'customfield_10112'" cannot be set. It is not on the appropriate screen, or unknown.

I am attaching a screenshot of which checkbox should be enabled.

enter image description here

I would request anyone to help me on this.




mercredi 28 avril 2021

Changing XML value in python .docx file

I'm having simple .docx which contains checkboxes that i want to check if needed. Here is XML: XML

And i want to change the "w:val" to "1", no clue how to do this...




How to create a react native state with key and value array?

I've a flatlist with a list of options and a checkboxes in each row, and I need a state for the checkboxex, using hooks. I tought create a key-value relationship, an associative array somehow, so I can access to the proper state using the "item.option" as key:

export default function Questions({ navigation, route }) {

    const [questionNumber, setQuestionNumber] = useState(0);
    const data = route.params.data;
    const numberOfQuestions = Object.keys(data.questions).length;

    const [selectedOption, setSelectedOption] = useState([null]);
    const [toggleCheckBox, setToggleCheckBox] = useState([false])

    [...]

    const renderItemMultipleChoice = ({ item }) => {
        console.log(toggleCheckBox[item.option],item.option); //******here I get undefined
        return (
            <View style={[styles.option]}>
                <CheckBox style={styles.checkBox}
                    disabled={false}
                    value={toggleCheckBox[item.option]}
                    onValueChange={(newValue) => multipleChoiceHandler(item.option, newValue)}
                />
                <Text style={styles.optionText}>{item.option}</Text>
            </View>

        );
    };

    const multipleChoiceHandler = (item, newValue) => {
        var newHash = toggleCheckBox
        newHash[item] = newValue;
        setToggleCheckBox({toggleCheckBox: newHash});
    }

    useEffect(() => {
        if (data.questions[questionNumber].type_option != "open_choice") {
            for (i = 0; i < Object.keys(data.questions[questionNumber].options).length; i++) {
                var newHash = toggleCheckBox
                newHash[data.questions[questionNumber].options[i].option] = false; 
//*******every checkbox is false at the beginning...
                setToggleCheckBox({toggleCheckBox: newHash});
                console.log("toggle checkbox:",toggleCheckBox[data.questions[questionNumber].options[i].option],
 data.questions[questionNumber].options[i].option); //****** here I get all false, the value I setted. 

            }
            setSelectedOption([null]);
        }
    }, [questionNumber])



     return(
             <FlatList style={styles.flatlistOption}
                    data={data.questions[questionNumber].options}
                    renderItem={renderItemMultipleChoice}
                    keyExtractor={(item) => item.option}
                />
     )
}

I'm supernoob about react, so to insert the intial state of toggleCheckBox for each element (using the parameter option to refer to the proper array element), I've used a for cycle... I know it's not proper and quite spaghetti code. Btw it should work, but when I try to access from the checklist to the toggleCheckBox state I get a undefined, so the checkbox state doesn't work properly. I don't know what I'm missing...




reactjs - Fill text area based on CheckBox clicks

Not very proficient in React, I have the following functional component (by the way I know I could populate the Checkbox list below via a .map function, but for now I did it in this way because some things I tried were breaking)

import React from 'react';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import FormLabel from '@material-ui/core/FormLabel';
import FormControl from '@material-ui/core/FormControl';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import Checkbox from '@material-ui/core/Checkbox';
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';

export default function TicketComponent(props) {

  const [state, setState] = React.useState({
    fluffy_cardigan: false,
    cropped_ls_top: false,
    cropped_jumpsuit: false,
    mama_jeans: false,
    mama_tshirt: false
  });

  const handleChange = (event) => {
    setState({ ...state, [event.target.name]: event.target.checked });

  };

  const { fluffy_cardigan, cropped_ls_top,cropped_jumpsuit, mama_jeans,mama_tshirt  } = state;

  console.log(state)

  return (
    <div>

    <Card>
      <CardActionArea>
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            Ticket Details
          </Typography>
          <Grid container  spacing={8} style=>
            <FormControl component="fieldset" >
              <FormLabel component="legend" style=>Item List</FormLabel>
              <FormGroup>
              <FormControlLabel
                control={<Checkbox name="cropped_ls_top" onChange={handleChange} checked={state.cropped_ls_top} />}
                label="Cropped Long-Sleeved Top"
              />
              <FormControlLabel
                control={<Checkbox name="cropped_jumpsuit" onChange={handleChange} checked={state.cropped_jumpsuit} />}
                label="Cropped Jumpsuit"
              />
              <FormControlLabel
                control={<Checkbox name="fluffy_cardigan" onChange={handleChange} checked={state.fluffy_cardigan} />}
                label="Fluffy Cardigan"
              />
              <FormControlLabel
                control={<Checkbox name="mama_jeans" onChange={handleChange} checked={state.mama_jeans} />}
                label="MAMA Skinny jeans"
              />
              <FormControlLabel
                control={<Checkbox name="mama_tshirt" onChange={handleChange} checked={state.mama_tshirt} />}
                label="MAMA T-Shirt"
              />


              </FormGroup>
            </FormControl>
            <TextField
              id="outlined-multiline-static"
              label="SKU"
              multiline
              defaultValue="test"
              variant="outlined"
            />
          </Grid>
        </CardContent>
      </CardActionArea>
    </Card>

    </div>
  );
}

which produces a checkbox list like shown below

enter image description here

I have added state to capture the various checkbox clicks.

What i want is the following:

  1. Upon clicking a checkbox, paste some specific string values (I will take them from the props passed in, this is fine) on a text area component next to it. For now let's assume we paste just the labels of the checkboxes that are clicked. I want to expand this later to essentially paste a row of values on a table when a checkbox is clicked i.e. the text area initially is an empty table and then rows are added/removed
  2. Then if I un-click a checkbox, remove those labels that were added
  3. I want the text area initially to have the same size as the checkbox list i.e. you can see that the default outline is small, whereas I want to make it seem like there is a big text area waiting to receive all the different strings pasted from the clicks. Perhaps I need a different component, and how could I make the outline have the same size?

If my description is confusing happy to clarify




How do I use checkbox event?

I have created the following GUI:

GUI with an TextBox (#1) to enter a machine name and a CheckBox (#2) to enable conversion of the machine name to uppercase.

I enter my text in a TextBox (#1 in the picture). I have a Button (#2 in the picture) which should change the input in the TextBox to uppercase so I wrote the following code:

private void tuUpperCase(object sender, RoutedEventArgs e)
{
    if (crossBox.IsChecked == true)
    {
        machineName.Text.ToUpper();
    }
}



mardi 27 avril 2021

How to make checkboxes 'checkable' only if another box is checked

So imagine I have 3 checkboxes, 1 'parent' checkboxes and 2 'child' checkboxes.

If the parent checkbox is checked, I want to be able to check either or both of the two child checkboxes.

If the parent checkbox is unchecked, I either of the two child checkboxes should not be checkable at all.

<div id="mycheckboxes">

        <label class="custom-control custom-checkbox" style="display: block">
          <input type="checkbox" class="custom-control-input" id="parentcheckbox" name="parentcheckbox"
                 [(ngModel)]="parentcheckbox1" (ngModelChange)="parentcheckbox1($event)">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">
        </label>


        <label class="custom-control custom-checkbox" style="display: block">
          <input type="checkbox" class="custom-control-input" id="childcheckbox1" name="childcheckbox1"
                 [(ngModel)]="childcheckbox1" (ngModelChange)="childcheckbox1($event)">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">
        </label>

        <label class="custom-control custom-checkbox" style="display: block">
          <input type="checkbox" class="custom-control-input" id="childcheckbox2" name="childcheckbox2"
                 [(ngModel)]="childcheckbox2" (ngModelChange)="childcheckbox2($event)">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">
        </label>

</div>

currently everyone of of these checkboxes are checkable, to reiterate the above, I am trying to make it so if parentcheckbox is checked, the two children are selectable, and if parent is unchecked, the two children are uncheckable.




java.lang.NPE: Attempt to invoke virtual method 'android.view.View android.widget.CheckBox.findViewById(int)' on a null object reference

Just started learning android development and while trying out the working of a checkbox via the onclicklistener functionality, I was thrown this error. It is on line 23 where I have "chkbx = chkbx.findViewById(R.id.chkbx);

Below is my entire Java code

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity  {

    private CheckBox chkbx, chkbx2, chkbx3;

        @Override
        protected void onCreate (Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            chkbx = chkbx.findViewById(R.id.chkbx);
            chkbx2 = chkbx2.findViewById(R.id.chkbx2);
            chkbx3 = chkbx3.findViewById(R.id.chkbx3);

            chkbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        Toast.makeText(MainActivity.this, "You've watched Lord of the Rings", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(MainActivity.this, "You Should Watch Lord of the Rings", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

}

Here is the xml code:

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

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:text="LOTR"
            android:id="@+id/chkbx"/>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:text="GOT"
            android:layout_toRightOf="@+id/chkbx"
            android:id="@+id/chkbx2"/>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:text="X-Men"
            android:layout_toRightOf="@+id/chkbx2"
            android:id="@+id/chkbx3"/>

</RelativeLayout>

I've read multiple potential bugs but can't seem to apply them in my predicament.

A little help would be great as I have a deadline to create my min projects demonstrating different UI components...

Thank you for your consideration.




How to deal with multiple selected checkboxes of the Active Choices Plugin in a script?

Is there a way to use independently the outputs of a checkbox list in the Active Choices plugin on Jenkins ? (as in my example, I need to access to the selected check boxes one at a time

Here are a few screens to explain my problem :

Active Choices configuration in the job

The script

Checkboxes selected

Output

I would like to be able to access first to only the Debian_6, then only the Debian 6 32bits :)

Thanks !




lundi 26 avril 2021

how to check checkboxed with jQuery based on the values of a string

I have a string with values and i want to check the checkboxes which have these values in the string:

var daysofweek = '1,3,4,';

<input class="edit-day" type="checkbox" value="1"><label class="form-check-label">Monday</label>
<input class="edit-day" type="checkbox" value="2"><label class="form-check-label">Tuesday</label>
<input class="edit-day" type="checkbox" value="3"><label class="form-check-label">Wednesday</label>
<input class="edit-day" type="checkbox" value="4"><label class="form-check-label">Thursday</label>
<input class="edit-day" type="checkbox" value="5"><label class="form-check-label">Friday</label>
<input class="edit-day" type="checkbox" value="6"><label class="form-check-label">Saturday</label>
<input class="edit-day" type="checkbox" value="0"><label class="form-check-label">Sunday</label> // sunday has 0

In this case, Monday, Wednesday and Thursday should be checked

How can i do that?

I tried something with code below but that does not work:

$.each(daysofweek, function(i, val){
    $('.edit-day').prop('checked', true);
});



jQuery - checkbox checked on new page with link

With this code I activate checkboxes on a page:

$(".cta-order").click(function() {
    var product = $(this).data('product');
    if(!$(":checkbox[value='"+ product +"']").is(':checked')) {
        $(":checkbox[value='"+ product +"']").click();
    }
});

Checkbox on the page:

<span class="wpcf7-list-item first">
   <label>
      <input type="checkbox" name="produkte[]" value="Einzelheft" class="required"> 
      <span class="wpcf7-list-item-label">Einzelheft</span>
   </label>
</span>

Button:

<a class="cta-btn cta-order" href="#bestellen" data-product="Einzelheft">Bestellen</a>

Problem: How to do this when coming from another page? When I do this:

<a class="cta-btn cta-order" href="https://www.mypage/order#bestellen" data-product="Einzelheft">Bestellen</a>

Nothing happens.




how I can disable the error icon near CheckBox when it checked

Tell me please how I can disable the error icon near CheckBox when it checked in Android Studio? Here is my code:

  if(!checkbox1.isChecked()){
            checkbox1.requestFocus();
            checkbox1.setError("This field isn't checked");
            return false;
          }



Slickgrid -- Checkbox in Grouped rows not getting checked on front end, but getting the data on the backend

I have implemented grouping in my slickgrid. Each row has a check box and the group also has a checkbox(find below code for same).

enter image description here

The checkboxes are seen at group level. It gets checked and the operations on checking are performed, but the checkbox is not visible as checked on front end.

My rowselection model is -->

assignedgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: false }));

If I change the rowselectionmodel to --> CellSelectionModel --> assignedgrid.setSelectionModel(new Slick.CellSelectionModel()); then it gets checked in, but then I'm only able to select one row at a time. Multi selection is not working.

I have tried using groupitemmetadata and syncing the grid as well, but it still doesn't work, and syncGridSelection gives an error.

How I am using syncGridSelection --> assigneddataView.syncGridSelection(assignedgrid, true,true);

I want the checkboxes to be visible as checked on front end, and have multi row selection. Request to kindly help!




dimanche 25 avril 2021

Method is running in the main of its class but not in the other classes [duplicate]

In this code, everything is going great. The 2 statements that are called in the main method are good. However, in the code below this one, it isn't.

package Demo;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class GUIDemo implements ActionListener {
    private static JLabel userLabel;
    private static JTextField userText;
    private static JLabel passwordLabel;
    private static JPasswordField passwordText;
    private static JButton button;
    private static JLabel success;
    private static boolean openWindow;

    @Override
    public void actionPerformed(ActionEvent e) {
        String user = userText.getText();
        String password = passwordText.getText();
        try {
            if (areValid(user, password)) {
                success.setText("Login successfully. This needs a few seconds.");
                openWindow = true;
            } else {
                System.exit(1);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public boolean areValid(String user, String password) throws IOException {
        FileReader fr = new FileReader("C:\\Users\\User\\IdeaProjects\\Tako\\src\\AirTraffic\\Username_password");
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();
        while (line != null) {
            try {
                String[] elements = line.split("-");
                String username = elements[0].trim();
                String pass = elements[1].trim();
                if (username.equals(user) && pass.equals(password)) {
                    br.close();
                    fr.close();
                    return true;
                }
            } catch (Exception e) {
            }
            line = br.readLine();
        }
        br.close();
        fr.close();
        return false;
    }

    public void execute() throws InterruptedException {
        JPanel panel = new JPanel();
        JFrame frame = new JFrame("Tako's airport - Login Process");
        frame.setSize(350, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        panel.setLayout(null);
        userLabel = new JLabel("User");
        userLabel.setBounds(10, 20, 80, 25);
        panel.add(userLabel);
        userText = new JTextField(20);
        userText.setBounds(100, 20, 165, 25);
        panel.add(userText);
        passwordLabel = new JLabel("Password");
        passwordLabel.setBounds(10, 50, 80, 25);
        panel.add(passwordLabel);
        passwordText = new JPasswordField(20);
        passwordText.setBounds(100, 50, 165, 25);
        panel.add(passwordText);
        button = new JButton("Login");
        button.setBounds(10, 80, 80, 25);
        button.addActionListener(new GUIDemo());
        panel.add(button);
        success = new JLabel("");
        success.setBounds(10, 110, 300, 25);
        panel.add(success);
        frame.setVisible(true);

        while (!openWindow) {
            int a = (int) (Math.random() * 10);
        }
        if (openWindow) {
            Thread.sleep(2000);
            frame.setVisible(false);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        GUIDemo gui = new GUIDemo();
        gui.execute();
    }
}

In this code, the same 2 statements are written in the actionPerformed(e) method. Is there an explanation behind it? In the previous code, it's showing the whole window with the panels. However, in this code, it's showing an empty window after I put administrator --> Continue.

package Demo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class FP {
    public JFrame frame;
    public static void main(String[] args) {
        new FP();
    }

    public FP() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame = new JFrame("Login");
                frame.setSize(350, 200);
                frame.add(new MainPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class MainPane extends JPanel implements ActionListener {

        private ButtonGroup checkBoxGroup;
        private JCheckBox jcb1, jcb2;
        private JButton button;
        private JLabel success;

        public MainPane() {
            jcb1 = new JCheckBox("Administrator", false);
            jcb2 = new JCheckBox("Customer", false);

            JLabel selectLabel = new JLabel("Login as:");
            add(selectLabel);

            checkBoxGroup = new ButtonGroup();

            checkBoxGroup.add(jcb1);
            checkBoxGroup.add(jcb2);
            add(jcb1);
            add(jcb2);

            button = new JButton("Continue");
            button.addActionListener(this);
            add(button);

            success = new JLabel("");
            add(success);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (jcb1.isSelected()) {
                try {
                    frame.setVisible(false);
                    GUIDemo gui = new GUIDemo();
                    gui.execute();

                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            } else {
            }
        }
    }
}



How to set Recyclview items on TextView in android

enter image description here

This is my main screen and i want when i click on Select All checkbox then check all checkboxes and set all checkbox's text on below textView(Just text). I successfully select all checkboxes but can't set text on textbox with separate commas, with the help of adapter i get the list of whole data but can't set it on main activity textview layout. plz suggest me any helpful way for done this. Thnakyou.




samedi 24 avril 2021

gridView item click event doesn't work after adding checkbox

When i add a checkbox to my grid view, I cant click the grid view item ? What is the reason ?.

Given below is the image of my implementation and relevant code

   lvResults1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
                                    {
                                        public boolean onItemLongClick(AdapterView<?> parent, View v,int position, long arg3)
                                        {

                                            return true;
                                        }
                                    });



get value of checkbox in react js

How to get the value of checkbox in react js , it is always returning false (boolean value) this is my snippet code

export default class CreateMateriel extends Component {
    constructor(props) {
        super(props);
        this.onChangeEtat = this.onChangeEtat.bind(this);


  this.state = {
        etat: false

onChangeEtat(e) {
    this.setState({
        etat: e.target.value
    });

the html code part

                    <input type="checkbox" className="form-control" value={this.state.etat}
                           onChange={!this.onChangeEtat}/>

Please do anyone has an idea?




vendredi 23 avril 2021

How can a choice box, checkbox, and text field be implemented into one button with JavaFX

I'm trying to create a program that can take data from a choicebox, checkbox, and text field and put it into a single textArea as output. How can I have all the information combine from one button. I have already created the choicebox, checkbox, and text fields.

-There are two text fields. One of them takes a name, and the other takes a number. The number will determine how many times the program is looped.

-The checkbox will take what kind of prefix to put in front of the name (Mr, Mrs, etc).

-The choicebox give options on what follow up statement will be given. (How was your day?, I like your hat, etc)

After clicking the button, the program would display something like this in a textArea if the number in the textField had an input of 2

"1Hello Mr. Johnson. How was your day?"

"2Hello Mr. Johnson. How was your day?"

This is what I have in the button event handler. It only implements the text fields

 private class CreateButtonHandler implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent event) {
        int i = 0;
        String myString = number.getText();
        int foo = Integer.parseInt(myString);
        do {
             OutputTxtArea.setText(OutputTxtArea.getText() + (i + 1) + "Hello " + firstNameTxtFld.getText() + "\n");
        } while(i<foo);
}
}



How to output checkbox selections into a frame with python tkinter?

I am trying to create a simple payment calculator that takes input from multiple checkboxes and uses that to calculate a total cost. I want the user to be able to select the different services they want and then the function would take that and calculate the total cost based on which services they have selected. How do I get my Total Cost function to output into the bottom right frame to the right of "billing total"? Here is what I have so far:

from tkinter import ttk
import tkinter as tk

import random
import datetime

root = Tk()
root.geometry("1100x950+0+0")
root.title("NLG Order Processing")
root.configure(background = 'light blue')

total_cost = 0

def Exit():
    root.destroy()
    return

def OrderNum():
    order1=random.randint(1000, 10000)
    order2=('FW'+str(order1))
    ordnum.set(order2)

def TotalCost():
    total_cost = 0
    if cmdCustomFitting.get() == "None":
        total_cost = total_cost + 0
    elif cmdCustomFitting.get() == "Iron Fitting-$125":
        total_cost = total_cost + 125
    elif cmdCustomFitting.get() == "Wood and Hybrid Fitting-$125":
        total_cost = total_cost + 125
    elif cmdCustomFitting.get() == "Full Set Fitting-$225":
        total_cost = total_cost + 225
    elif cmdCustomFitting.get() == "Putter Analysis-$75":
        total_cost = total_cost + 75
    else:
        total_cost = total_cost + 0
    
    
    if cmdClubRepair.get() == "None":
        total_cost = total_cost + 0
    elif cmdClubRepair.get() == "Grip installation-$4/each":
        total_cost = total_cost + 4
    elif cmdClubRepair.get() == "Save Grip-$6/each":
        total_cost = total_cost + 6
    elif cmdClubRepair.get() == "Lengthen Shaft-$8/each":
        total_cost = total_cost + 8
    elif cmdClubRepair.get() == "Loft Adjustments-$5/each":
        total_cost = total_cost + 5
    elif cmdClubRepair.get() == "Lie Adjustments-$5/each":
        total_cost = total_cost + 5
    elif cmdClubRepair.get() == "Re-Shaft/Shaft Installation-$15/each":
        total_cost = total_cost + 15
    elif cmdClubRepair.get() == "Save Adapter-$8/each":
        total_cost = total_cost + 8
    else:
        total_cost = total_cost + 0
    

    if cmdPrivateLesson.get() == "None":
        total_cost = total_cost + 0
    elif cmdPrivateLesson.get() == "Basic Birdie: One-Hour Lesson-$75":
        total_cost = total_cost + 75
    elif cmdPrivateLesson.get() == "Eager Eagle: (4) One-Hour Lessons-$275":
        total_cost = total_cost + 275
    elif cmdPrivateLesson.get() == "Double Eagle: (8) One-Hour Lessons-$500":
        total_cost = total_cost + 500
    else:
        total_cost = total_cost + 0

    
    if cmdSimulation.get() == "None":
        total_cost = total_cost + 0
    elif cmdSimulation.get() == "30 Minute Range-$10":
        total_cost = total_cost + 10
    elif cmdSimulation.get() == "30 Minute Range-$10":
        total_cost = total_cost + 10
    elif cmdSimulation.get() == "9 Hole Sim-Golf-$20/person":
        total_cost = total_cost + 20
    elif cmdSimulation.get() == "18 Hole Sim-Golf-$30/person":
        total_cost = total_cost + 30
    else:
        total_cost = total_cost + 0
    
    

EmpUsername=StringVar()
EmpPassword=StringVar()
CustID=StringVar()
F_name=StringVar()
L_name=StringVar()
Email=StringVar()
Cust_phone_num=StringVar()
discountcode=StringVar()
discountamount=StringVar
Usercardname=StringVar()
Usercardnum=StringVar()
Cardexpdate=StringVar()
Usersocialsec=StringVar()
ordnum=StringVar()
Service_num=StringVar()
Billing_total=StringVar()
Totalcost=StringVar("")


Tops=Frame(root, width=1350, height=50, bd=16, relief = "flat")
Tops.pack(side=TOP)
LF=Frame(root, width=700, height=650, bd=16, relief="flat")
LF.pack(side=LEFT)
RF=Frame(root, width=600, height=650, bd=16, relief="flat")
RF.pack(side=RIGHT)

Tops.configure(background="light blue")
LF.configure(background="light blue")
RF.configure(background= "light blue")

LeftInsideLF=Frame(LF, width=700, height=100, bd=8, relief= "raise")
LeftInsideLF.pack(side=TOP)
LeftInsideLFLF=Frame(LF, width=700, height=500, bd=8, relief="raise")
LeftInsideLFLF.pack(side=LEFT)

RightInsideLF=Frame(RF, width=700, height=500, bd=8, relief = "raise")
RightInsideLF.pack(side=TOP)
#RightInsideLFLF=Frame(RF, width=700, height=500, bd=8, relief = "raise")
#RightInsideLFLF.pack(side=RIGHT)
RightInsideLFF=Frame(RF, width=300, height=300, bd=8, relief = "raise")
RightInsideLFF.pack(side=TOP)

lblInfo = Label (Tops, font=("times", 50, 'bold'), text="    Next Level Golf Order Processing    ", bd=10, anchor="w")
lblInfo.grid(row=0, column=0)

#Log In Page 
TextUsername=Entry(LeftInsideLF, font=('times', 12), width = 11, textvariable="Username").grid(row=0, column=1)
lblUsername=Label(LeftInsideLF, font=('times', 12), width=11, text="Username:", bd=10, anchor="w").grid(row=0, column=0)
TextPassword=Entry(LeftInsideLF,font=('times', 12), width=11, textvariable='Password').grid(row=1, column=1)
lblPassword=Label(LeftInsideLF, font=('times', 12), width=11, text="Password:", bd=10, anchor="w").grid(row=1, column=0)

#Log in Button
btnlogin = Button(LeftInsideLF, pady=8, bd=8, fg="black",font=('times', 12), width=11, text="Login").grid(row=2, column=0)

#Returning
cmdReturningCustomer=Checkbutton(LeftInsideLFLF, font=('times', 12), text='Returning Customer (ID only)' , width=30)
cmdReturningCustomer.grid(row=0, column =0)

#Customer ID
lblCustomerID=Label(LeftInsideLFLF, font=('times', 12), width=11, text="Customer ID:", bd=10)
lblCustomerID.grid(row=3, column=0)
TextCustomerID=Entry(LeftInsideLFLF, font=('times', 12), textvariable='CustID')
TextCustomerID.grid(row=3, column=1)

#New Customer First Name
TextNewCustFName=Entry(LeftInsideLFLF, font=('times', 12), textvariable='F_name')
TextNewCustFName.grid(row=4, column=1)
lblNewCustFName=Label(LeftInsideLFLF, font=('times', 12), width=11, text="First Name:", bd=10)
lblNewCustFName.grid(row=4, column=0)
#New Customer Last Name
TextNewCustLName=Entry(LeftInsideLFLF, font=('times', 12), textvariable='L_name')
TextNewCustLName.grid(row=5, column=1)
lblNewCustLName=Label(LeftInsideLFLF, font=('times', 12), width=11, text="Last Name:", bd=10)
lblNewCustLName.grid(row=5, column=0)
#New Customer EMail
TextNewCustEMail=Entry(LeftInsideLFLF, font=('times', 12), textvariable='Email:')
TextNewCustEMail.grid(row=6, column=1)
lblNewCustEMail=Label(LeftInsideLFLF, font=('times', 12), width=11, text="Email:", bd=10)
lblNewCustEMail.grid(row=6, column=0)
#New Customer Phone 
TextNewCustPhone=Entry(LeftInsideLFLF, font=('times', 12), textvariable='User_phone_num')
TextNewCustPhone.grid(row=7, column=1)
lblNewCustPhone=Label(LeftInsideLFLF, font=('times', 12), width=11, text="Phone Number:", bd=10)
lblNewCustPhone.grid(row=7, column=0)

#Services entry
lblServiceSelect=Label(RightInsideLF,font=('times', 14, 'bold'),text="Service Selection",fg='black',bd=10,anchor='w')
lblServiceSelect.grid(row=0, column=0)
#Custom Fitting
lblCustomFitting=Label(RightInsideLF, font=('times',12,),text="Custom Fitting", fg='black',bd=10,anchor='w')
lblCustomFitting.grid(row=1, column=0)
cmdCustomFitting=ttk.Combobox(RightInsideLF,font=('times',12))
cmdCustomFitting['value']=('None','Iron Fitting-$125','Wood and Hybrid Fitting-$125','Full Set Fitting-$225','Putter Analysis-$75')
cmdCustomFitting.grid(row=1, column=1)
#Club Repair
lblClubRepair=Label(RightInsideLF, font=('times',12,),text="Club Repair", fg='black',bd=10,anchor='w')
lblClubRepair.grid(row=2, column=0)
cmdClubRepair=ttk.Combobox(RightInsideLF,font=('times',12))
cmdClubRepair['value']=('None','Grip installation-$4/each','Save Grip-$6/each','Lengthen Shaft-$8/each','Loft Adjustments-$5/each','Lie Adjustments-$5/each',
'Re-Shaft/Shaft Installation-$15/each','Save Adapter-$8/each')
cmdClubRepair.grid(row=2, column=1)
#Private Lesson
lblPrivateLesson=Label(RightInsideLF, font=('times',12,),text="Private Lesson", fg='black',bd=10,anchor='w')
lblPrivateLesson.grid(row=3, column=0)
cmdPrivateLesson=ttk.Combobox(RightInsideLF,font=('times',12))
cmdPrivateLesson['value']=('None','Basic Birdie: One-Hour Lesson-$75','Eager Eagle: (4) One-Hour Lessons-$275','Double Eagle: (8) One-Hour Lessons-$500')
cmdPrivateLesson.grid(row=3, column=1)
#Simulation
lblSimulation=Label(RightInsideLF, font=('times',12,),text="Simulation", fg='black',bd=10,anchor='w')
lblSimulation.grid(row=4, column=0)
cmdSimulation=ttk.Combobox(RightInsideLF,font=('times',12))
cmdSimulation['value']=('None','30 Minute Range-$10','60 Minute Range-$17','9 Hole Sim-Golf-$20/person','18 Hole Sim-Golf-$30/person')
cmdSimulation.grid(row=4, column=1)
#Discount Code
TextDiscountCode=Entry(RightInsideLF, font=('times', 12), textvariable='discountcode')
TextDiscountCode.grid(row=5, column=1)
lblDiscountCode=Label(RightInsideLF, font=('times', 12), text="Enter discount code (if applicable):",fg='black', bd=10, anchor='w')
lblDiscountCode.grid(row=5, column=0)


#Confirmation Page
lblConfPage=Label(RightInsideLFF, font=('times', 14,'bold'), text='Confirmation Page',fg='black', bd=10)
lblConfPage.grid(row=0, column=0)
#Customer ID
lblCustomerID=Label(RightInsideLFF, font=('times', 12), width=11, text="Customer ID:", bd=10)
lblCustomerID.grid(row=1, column=0)
lblordnum=Label(RightInsideLFF, font=('times', 12), width=11, text="Order Number:", bd=10)
lblordnum.grid(row=2, column=0)
lblServiceord=Label(RightInsideLFF, font=('times', 12), width=11, text="Services Ordered:", bd=10)
lblServiceord.grid(row=3, column=0)
lblbilltotal=Label(RightInsideLFF, font=('times', 12), width=11, text="Billing Total:", bd=10)
lblbilltotal.grid(row=4, column=0)


#Total cost button
btnTotalCost = Button(RightInsideLF, pady=8, bd=8, fg="black",font=('times', 12), width=16, text="Calculate Total Cost", command=TotalCost).grid(row=6, column=1)
# Total cost button should be on the Service Selection page (instead of the booking confirmation)

#Order Number button
#btnOrderNum = Button(RightInsideLFF, pady=8, bd=8, fg="black",font=('times', 12), width=11, text="Order Number", command=OrderNum).grid(row=5, column=1)
# Jones doesn't want this button on this frame. 

#Exit Button
btnSubmit = Button(RightInsideLFF, pady=8, bd=8, fg="black",font=('times', 12), width=11, text="Submit", command=Exit).grid(row=5, column=2)



root.mainloop()'''



How to save a Checkbox state in android studio?

I'm new to android studio and I just can't figure out how to save the checkbox state using sharedpreference. If someone can help me I would greatly appreciate the assistance.

class SelectAlertSettings : AppCompatActivity() {

    private lateinit var mp : MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.select_alert_config)


    }

    fun onCheckboxClicked(view: View) {
        if (view is CheckBox) {
            val checked: Boolean = view.isChecked

            when (view.id) {
                R.id.checkbox_proximity_alert -> {
                    if (checked) {

                        val proximityAlert = R.raw.proximity_alert
                        mp = MediaPlayer.create(this, proximityAlert)
                        mp.start()

                    } else {

                        mp.stop()
                    }

                }

            }

        }

        val btnCancel : Button = findViewById(R.id.btnDone)
        btnCancel.setOnClickListener{
            finish()
        }
    }
}



Checkbox not working normally in case of event.preventDefault and just working when using setTimeout

I was just going through a scenario where I needed to customize a checkbox so that it can be checked and unchecked not instantly, but when some button is clicked. While working on that, I used preventDefault followed by stopPropagation to stop the checkbox from following default behavior and make it check or uncheck conditionally.

The checkbox is getting checked at first, but then it is not un-checking, given the code is working fine with setTimeout but not without it. Following is the mockup:

window.message = 'Some message that appears on modal';
$(document).ready(function() {
  $('#chkbx').off('click').on('click', function(e) {
    var $checkbox = $(this);
    e.preventDefault();
    e.stopPropagation();
    console.log($checkbox.is(':checked') ? 1 : 0);
    showConfirmation($checkbox.is(':checked') ? 1 : 0);
  });

  function showConfirmation(s_checked) {
    // Why this if block is making checkbox checked 
    if (s_checked) {
    // in place of settimeout, in actual code we are showing a modal having 
    // yes and no buttons, on the click of yes we call a callback function, 
    // in which we check the checkbox and do other necessary UI changes tasks
      setTimeout(function() {
        $('#chkbx').val(1);
        $('#chkbx').prop('checked', true);
      });
      // While a similar code without delay is not working
    } else {
        // Line 24 and 25 code does not unchecks the checkbox
      $('#chkbx').val(0);
      $('#chkbx').prop('checked', false);
      
      // But line 27 to 31 code does unchecks the checkbox
      /* setTimeout(function() {
        $('#chkbx').val(0);
        $('#chkbx').prop('checked', false);
      }); */

    }
    return true;
  }
})

Please help me understand, what is going wrong here due to which the code is not unchecking the checkbox when not using setTimeout.




Incorrect rendering of controlled Fluent UI Checkbox components

I have a form that interacts with a database via REST API and presents several controlled Fluent UI components. For a multi-choice field, I built a component that displays a Stack with an arbitrary number of controlled Checkbox components. Below is the content of the render function.

const choices = this.props.Field.Choices.results;
return (<>
  <Fabric.Stack {...this.props.stackTokens}>
    {choices.map((choice) => (
      <Fabric.Checkbox label={choice} checked={this.state.value[choice]}
        onChange={this.handleChange(choice)} key={choice} />
    ))}
  </Fabric.Stack>
  <div
    className="errorMessage"
    id={`FormFieldDescription--${this.context.Item?.Id}__${this.props.FieldName}`}
    role="alert"
    style=>
    {this.props.errorMessage}
  </div>
</>);

After the form retrieves the data via REST API, this component uses that data to update its state. While the state is correctly updated and the correct values are being passed to the props for each Checkbox component, the UI is misleading. For instance, the checked values below are set to false, true, false, false, and false respectively, according to the React Components inspector in Chrome DevTools.

Initial presentation of Stack containing one Checkbox with checked set to true; No checkboxes are ticked

Obviously, while the props are correctly set, the user is presented with five unticked checkboxes. When the user clicks the checkbox that should have been ticked, the state is correctly updated to reflect that all five checkboxes are unticked. This is what it looks like after the user clicks on the second checkbox.

Updated presentation of Stack containing no Checkboxes with checked set to true; The second checkbox is ticked

The user interacts with the Checkbox components and they behave as expected, but the underlying values are exactly inverted for any where the initial checked property was set to true.




Checkboxes to SQL in ASP.NET Core

I have an existing MS SQL table with data and need to add a new column that should store the value from a checkbox field in a form using ASP.NET Core 5 and razorpages

here are my questions

  • What data type should I use in SQL for this checkbox column?
  • What data type should I use in the Model?
  • What values should be stored in SQL, "false/true", 0/1, -1,0 ?

as a side note I can say I have tried many differrent options but I endup all the time getting some kind of type missmatch error when I submit my form, or when I try to bind the value to the checkbox in an "editform"

thanks




Visual Studio C# DataGridViewColumn to DataGridViewCheckBoxColumn

mysqlCon.Open();
                MySqlDataAdapter sqlDa = new MySqlDataAdapter("ViewAllUsers", mysqlCon);
                sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
                DataTable dtblUsers = new DataTable();
                sqlDa.Fill(dtblUsers);
                usersGridView.DataSource = dtblUsers;
                DataGridViewColumn clmIme  = usersGridView.Columns[0];
                DataGridViewColumn clmPrezime = usersGridView.Columns[1];
                DataGridViewColumn clmOIB = usersGridView.Columns[2];
                DataGridViewColumn clmPassword = usersGridView.Columns[3];
                DataGridViewColumn clmAdmin =usersGridView.Columns[4];

This works fine. Table shows data from database. But clmAdmin is type BIT in mysql database and naturaly it shows 0 or 1 in my DataGridViewColumn. I would like to represent that value with checkBox (DataGridViewCheckBoxColumn), change that column type. I have no idea how to do it, I'm getting conversion error when I try

DataGridViewCheckBoxColumn clmAdmin = (DataGridViewCheckBoxColumn)usersGridView.Columns[4];

(DataGridViewCheckBoxColumn)usersGridView.Columns[4]' threw an exception of type System.InvalidCastException System.Windows.Forms.DataGridViewCheckBoxColumn {System.InvalidCastException}

Can someone please point me in right direction or show me how to do it? Thank you in advance.




jeudi 22 avril 2021

How do you precheck checkboxes in a loop?

I'm attempting to have it that when the table is loaded any completed tasks will have the checkbox prechecked and when the user checks it it updates the array so that I can store it in a file so that it will be checked next time it is loaded. I'm having trouble setting the checkbox to on and retrieving the value when it changes so the array can be updated.

from tkinter import *
Colours=['red','orange','yellow','green']
Priority=[1,0,0]
Completion=[0,1,0]
Date = ['D1','D2','D3']
DateCreated=['D1','D2','D3']
DateModified=['D1','D2','D3']
Action = ['4','3','3']
Project =['Project1','Project2','Project3']
Author = ['Person1','Person2','Person3']
ReportNo = ['124','654','2344']
Vessel=['Vessel1','Vessel2','Vessel3']
Tag = ['Tag1','Tag2','Tag3']
Comments = [['Comment1','Comment2','Comment3'],['Comment1','Comment2','Comment3'],['Comment1','Comment2','Comment3']]

class Table: 
      
    def __init__(self,root): 
        headers=[' ','Date Added', ' ','Created','Modified', 'Project','Author','Report no','Vessel','Tag','Comments']
        Checks={}
        # code for creating table 
        for i in range(total_rows): 
            for j in range(total_columns): 
                if j ==0 :
                    if i==0:
                        self.e = Entry(root, width=5, fg='blue', font=('Arial',10,'bold'))
                    else:
                        Checks[i]=IntVar(value=0)
                        self.e=Checkbutton(root, variable = Checks[i], onvalue = 1, offvalue = 0)

                elif j ==2 :  
                    self.e = Entry(root, width=5, fg='blue', font=('Arial',10,'bold'))
                elif j ==10 :  
                    self.e = Entry(root, width=100, fg='blue', font=('Arial',10,'bold'))
                else: 
                    self.e = Entry(root, width=10, fg='blue', font=('Arial',10,'bold'))
                  
                self.e.grid(row=i+1, column=j)
                if i == 0:
                    if j==0:
                        pass
                    else:
                        self.e.insert(END,headers[j])
                elif j==1:
                    self.e.insert(END, Date[i-1])
                elif j ==2 :
                    self.e.insert(END,Action[i-1])
                    if Action[i-1]==4 or Action[i-1]=='4':
                        self.e.configure(bg=Colours[0])
                    elif Action[i-1]==3 or Action[i-1]=='3':
                        self.e.configure(bg=Colours[1])
                    elif Action[i-1]==2 or Action[i-1]=='2':
                        self.e.configure(bg=Colours[2])
                    else:
                        self.e.configure(bg=Colours[3])
                    if Completion[i-1]==1 or Completion[i-1]=='1':
                        self.e.configure(bg='white')
                elif j==3:
                    self.e.insert(END, DateCreated[i-1])
                elif j==4:
                    self.e.insert(END, DateModified[i-1])
                elif j==5:
                    self.e.insert(END, Project[i-1])
                elif j==6:
                    self.e.insert(END, Author[i-1])
                elif j==7:
                    self.e.insert(END, ReportNo[i-1])
                elif j==8:
                    self.e.insert(END, Vessel[i-1])
                elif j==9:
                    self.e.insert(END, Tag[i-1])
                elif j==10:
                    self.e.insert(END, Comments[i-1])
                    
total_rows = len(Date)+1
total_columns = 11
root=Tk()
t = Table(root) 
root.mainloop()

Above is the code creating the table.




How to update disabled prop on checkbox change?

I have a checkbox that I'm using to toggle whether a li tag gets added to a list. When it is added to the list other li tags and their associated checkboxes (nested under the li tag) are "disabled" using jQuery.

The checkbox will become disabled but it does not un disable when I uncheck the box currently.

I've tried prop, attr, removeProp/Attr which no success in making the checkbox active again.

$('#id_of_ul_that_holds_li's').on('change', li.active input, function() {

    if ($(this).prop('checked')) {
      $(this).parent().addClasss('checked')
      $(this).children('input').prop('disabled', true)
    }
    else if (!($(this).prop('checked')) {
      $(this).parent().removeClasss('checked')
      $(this).children('input').prop('disabled', false)
    }

  });



To select all other checkboxes when checked the option (all) is clicked in dash

I need a logic which selects all checkboxes when the option All is checked in the checklist And the graph would change accordingly.

Or if we can disable the other checkboxes(x,y,x and x1, x2,x3) if the option All is Checked.

The code which I have used is as follows

import pandas as pd
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
df = pd.DataFrame({'category' : ['A','A','A','B','B','B'],
               'subcategory' : ['l', 'y', 'z', 'x1','y1','z1'],
               'x_coord' : [1, 2,3,2,2,2],
               'y_coord' : [1,3,2,1,3,2]})
# lists of categories
options1 = sorted(df["category"].unique().tolist())
# dictionary of category - subcategories
all_options = df.groupby("category")["subcategory"].unique()\
            .apply(list).to_dict()
# we add as first subcategory for each category `all`
for k, v in all_options.items():
    all_options[k].insert(0, 'all')
app = dash.Dash()
app.layout = html.Div([
dcc.Dropdown(
    id='first-dropdown',
    options=[{'label': k, 'value': k} for k in all_options.keys()],
    value=options1[0]
),

html.Hr(),

dcc.Dropdown(id='second-dropdown'),

html.Hr(),

dcc.Graph(id='display-selected-values')
])
# the following two callbacks generate a dynamic 2 option
@app.callback(
    dash.dependencies.Output('second-dropdown', 'options'),
    [dash.dependencies.Input('first-dropdown', 'value')])
def set_2_options(first_option):
   return [{'label': i, 'value': i} for i in all_options[first_option]]


@app.callback(
dash.dependencies.Output('second-dropdown', 'value'),
[dash.dependencies.Input('second-dropdown', 'options')])
def set_2_value(available_options):
   return available_options[0]['value']
@app.callback(
   dash.dependencies.Output('display-selected-values', 'figure'),
   [dash.dependencies.Input('first-dropdown', 'value'),
   dash.dependencies.Input('second-dropdown', 'value')])
def update_graph(selected_first, selected_second):
    if selected_second == 'all':
       ddf = df[df["category"]==selected_first]
    else:
        ddf = df[(df["category"]==selected_first) &
             (df["subcategory"]==selected_second)]

fig = go.Figure()
fig.add_trace(
    go.Scatter(x=ddf["x_coord"],
               y=ddf["y_coord"],
               marker = dict(size=15, color='green'),
               mode='markers'))
return fig

if __name__ == '__main__':
  app.run_server(debug=False)

If the All option is checked from the checkbox for category A then the subcategories can either be all selected(i.e checked) or the can be disbled and the graph must be shown for all the subcategories.

What calls and function is necessary to achieve these. Thanks in Advance!!!




Vuetable: No rowdata are available in data-item on checkbox-toggled method

I am new to vue table 2.

My issue is no rowdata are available in the data-item on checkbox-toggled method.

here is my code

<vuetable
ref="vuetable"
:api-mode="false"
:fields="fields"
class="panel-body desktop-head-only"
:data="groupData"
@vuetable:checkbox-toggled="checkboxToggledCustom"
@vuetable:checkbox-toggled-all="toggleAllCheckboxes"
>

I don't know anything I missed or not?

This is what am getting on the checkboxToggledCustom method. please check this link




Failure checkbox using MVC asp.net and jquery

I using this code when the checkbox True/False is checked:

  1. A value >>> not required and disable this field
  2. B value >>> required

But I have problem because when the checkbox True/False is unchecked and clicking on btnConfirm... the field B is required...

I need

  1. when the checkbox is unchecked the field B is not required
  2. when the checkbox is checked the field B is required

Can you help me?

My code below

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            EnableDisable($("[id*=Truefalse]"));
 
            $("[id*=Truefalse]").click(function () {
                EnableDisable($(this));
            });
 
            $("[id*=btnConfirm]").click(function () {
                if ($('#B').val() == '' && $('#B').attr('disabled') == undefined) {
                    alert('B value is required.');
                    return false;
                }
            });
        });
 
        function EnableDisable(element) {
            if ($(element).is(':checked')) {
                $('#A').attr('disabled', 'disabled');
                $('#B').removeAttr('disabled');
            } else {
                $('#A').removeAttr('disabled');
            }
        }
    </script>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <div class="container">
            <div>&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group" style="background-color: lightgoldenrodyellow; border:3px solid; font-weight:bold;">
                        <h5 style="font-weight: bold; text-indent: 20px;">
                            True/False @Html.CheckBoxFor(m => m.Truefalse, true)
                        </h5>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(m => m.A)
                        @Html.TextBoxFor(m => m.A, "{0:dd/MM/yyyy}", new { @Class = "Mytextarea2", placeholder = "A" })
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        @Html.LabelFor(m => m.B)
                        @Html.TextAreaFor(m => m.B, new { style = "width: 420px; height: 100px;", placeholder = "B" })
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <input id="btnConfirm" type="submit" value="Confirm" class="btn btn-default" />
                    </div>
                </div>
            </div>
        </div>
    }
</body>
</html>



Multiple Check Boxes in PHP form inserted into MySQL

I know similar has been posted before, but nothing I can find is quite the same as my issue, even with me trying to adapt things.

I have a form with 28 checkboxes all named check[]

Along with three other fields on the form, I need this to insert a new record. I just can't work out how to iterate through the array and insert into the correct place. Any ideas appreciated.

I've also tried GetSQLValueString('check'[0]) etc and GetSQLValueString('check') etc

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
    
$selected = array();
if (isset($_POST['check']) && is_array($_POST['check'])) {
    $selected = $_POST['check'];
} else {
    $selected = array($_POST['check']);
}
    
  $insertSQL = sprintf("INSERT INTO checkin (`date`, `time`, room, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['date'], "date"),
                       GetSQLValueString($_POST['time'], "date"),
                       GetSQLValueString($_POST['studio'], "int"),
                       GetSQLValueString($selected[0]),
                       GetSQLValueString($selected[1]),
                       GetSQLValueString($selected[2]),
                       GetSQLValueString($selected[3]),
                       GetSQLValueString($selected[4]),
                       GetSQLValueString($selected[5]),
                       GetSQLValueString($selected[6]),
                       GetSQLValueString($selected[7]),
                       GetSQLValueString($selected[8]),
                       GetSQLValueString($selected[9]),
                       GetSQLValueString($selected[10]),
                       GetSQLValueString($selected[11]),
                       GetSQLValueString($selected[12]),
                       GetSQLValueString($selected[13]),
                       GetSQLValueString($selected[14]),
                       GetSQLValueString($selected[15]),
                       GetSQLValueString($selected[16]),
                       GetSQLValueString($selected[17]),
                       GetSQLValueString($selected[18]),
                       GetSQLValueString($selected[19]),
                       GetSQLValueString($selected[20]),
                       GetSQLValueString($selected[21]),
                       GetSQLValueString($selected[22]),
                       GetSQLValueString($selected[23]),
                       GetSQLValueString($selected[24]),
                       GetSQLValueString($selected[25]),
                       GetSQLValueString($selected[26]),
                       GetSQLValueString($selected[27])
                      
                      );

  mysql_select_db($database_thepcguy_tilly, $thepcguy_tilly);
  $Result1 = mysql_query($insertSQL, $thepcguy_tilly) or die(mysql_error());



Open a input text if checkbox is checked (JQuery)

I'm trying to make a input that just open if checkbox is checked.

<script>
if ($('#flexCheckDefault').is(':checked')) {
    $('#test').prop('disabled')
}
</script>

<input type="checkbox" id="flexCheckDefault">
<input type="text" id="test" disabled>

I've try this but not got success. Help-me pls!




How to show selected checkbox on next screen in flutter?

I am new to flutter. i have created checkbox but don't know how to show selected checkbox data on next screen. Here is my code:

                      Padding(
                        padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
                        child: ElevatedButton(
                          onPressed: (){},
                          style: ButtonStyle(
                              shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20),
                                  side: BorderSide(color: HexColor('#09B9B6')),
                                ),
                              ),
                              backgroundColor: MaterialStateProperty.all<Color>(HexColor('#F2FFFF'))
                          ),
                          child: CheckboxListTile(
                            title:  Text('Maid Service', style: new TextStyle(color: HexColor('#09B9B6'), fontWeight: FontWeight.bold),),
                            subtitle: Text('35 Dollar / 1 Hour'),
                            value: this.valueFifth,
                            checkColor: HexColor("#F2FFFF"),
                            activeColor: HexColor("#09B9B6"),
                            onChanged: (bool value) {
                              setState(() {
                                this.valueFifth = value;
                              });
                            },
                          ),
                        ),
                      ),

please help




mercredi 21 avril 2021

Add clickable checkbox to powerpoint slide on Mac

I want to add a clickable checkbox (one or more) to a PowerPoint presentation slide. I'm using MacOS and Microsoft Office 365.

I guess that it is possible to do using macros created with VBA, but I have no idea what code needs to be created for this.

I would be very grateful if you would share the necessary code or suggest me another relevant ways to create clickable checkboxes in pptx under the Mac.

enter image description here




Javafx TableView with Checkbox

I have the following classes and i need to do a listener on Checkbox in TableView. Also have a ProgressBar, which i need to work based on checked Checkboxes. I did it with ListView(in code below too), and i need something similar with my TableView + color rows, in which are checked Checkboxes

Controller:

public class Controller {
@FXML
private TextField textField2;
@FXML
private TableColumn<Task,String> columnnTime;
@FXML
private TableColumn<Task,String> columnnWork;
@FXML
private TableColumn<Task,CheckBox> columnDone;
@FXML
private TableView<Task> tableViewTabulka;
@FXML
private Label labelDay;
@FXML
private TextField textField;
@FXML
private ListView listView = new ListView<String>();
@FXML
private ProgressBar progressBar;
private Task task;
ObservableSet<Task> selected = FXCollections.observableSet();

 @FXML
private void initialize() {
    addLabels();
    fillInLabelP();
    columnnTime.setCellValueFactory(new PropertyValueFactory<>("time"));
    columnnWork.setCellValueFactory(new PropertyValueFactory<>("work"));
    columnDone.setCellValueFactory(new PropertyValueFactory<>("done"));
}

Task:

public class Task {
private String time;
private String work;
private CheckBox done;


public Task(String time, String work, CheckBox done) {
    this.time = time;
    this.work = work;
    this.done = done;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public String getWork() {
    return work;
}

public void setWork(String work) {
    this.work = work;
}

public CheckBox getDone() {
    return done;
}

public void setDone(CheckBox done) {
    this.done = done;
}

My working ListView from a previous experiment:

listView.setCellFactory(CheckBoxListCell.forListView(new Callback<Item, ObservableValue<Boolean>>() {
        @Override
        public ObservableValue<Boolean> call(Item item) {

            item.onProperty().addListener((obs, wasSelected, isNowSelected) -> {
                if (isNowSelected) {
                    selected.add(item);
                } else {
                    selected.remove(item);
                }
                double y = listView.getItems().size();
                double x= selected.size();
                double kon = ((1/y)*x);

                progressBar.setProgress(kon);
            });
            return item.onProperty();
        }
    }));

}

TableView: enter image description here




why JQuery Mobile not able to check the checkbox?

I put a checkbox on my webpage, but I want to check it, base on the content of the text file. I am using the below code:

    $(document).ready(function(){
        
    
          $.ajax({
        url : "CH1.txt",
        dataType: "text",
        success : function (data) {
            $("CH1.text").html(data);
            
            var jsonData = JSON.parse(data);
            alert(data);
            
            
            if(data=="1"){$("#CH1CheckBox").prob('checked', true);
                else $("#CH1CheckBox").prob('checked', false);
        
            
        }
    });
       });

when I remove the below script that belonged to JQuery mobile, everything is ok.

but when I use the JQM it not works. I already test with the .attr() function as well, but not constructive. please help. thanks in advance




Get value of Checkbox in react custom checkbox

I have this dynamic checkbox, that I want to update the state with the selected options only ,I tried to add some checks to filter the state on change , but it seems I am not seeing what went wrong!

const checkBoxesOptions = [
    { id: 1, title: 'serviceOne' },
    { id: 2, title: 'serviceTwo' },
    { id: 3, title: 'serviceThree' },
];

const [selectedCheckBoxes, setSelectedCheckBoxes] = React.useState([]);

{checkBoxesOptions.map((checkBox, i) => (
                    <CheckBox
                        key={i}
                        label={checkBox.title}
                        value={1}
                        checked={false}
                        onChange={value => {
                            let p = {
                                title: checkBox.title,
                                isTrue: value,
                            };
                            if (p.isTrue) {
                                const tempstate = selectedCheckBoxes.filter(
                                    checkbox => checkbox !== checkBox.title
                                );
                                console.log('temp state', tempstate);
                                setSelectedCheckBoxes([...selectedCheckBoxes, p.title]);
                            }

        
                            console.log(p);
                        }}
                    />
                ))}



JavaFX 8 CheckBox serialization

I have object like

class Person extends Human implements Serializable{ //just random example
String name;
CheckBox check;

//other functions with checkbox and name
}

and I want to serialize whole CheckBox object. I found out that it´s not possible for Java FX elements but is there any workaround around that if I want to serialize only one Java FX object per instance?

Thanks for answers.




WooCommerce admin product custom checkbox field not saving value

i created custom checkbox on product options, but stuck in saving data. I tried all possible variants, but without success. Where i am going wrong? thanks

This is code:

add_action( 'woocommerce_product_options_sku', 'custom_checkbox_field' );
function custom_checkbox_field(){
    global $post, $product_object;

    if ( ! is_a( $product_object, 'WC_Product' ) ) {
            $product_object = wc_get_product( $post->ID );
    }
      
            
    woocommerce_wp_checkbox(
    array(
        'id'            => 'custom_checkbox_field',
        'value'         => empty($values) ? 'yes' : $values,
        'label'         => __( 'Label', 'woocommerce' ),
        'description'   => __( 'Description', 'woocommerce' ),
        )
    );
    
}

add_action( 'woocommerce_process_product_meta', 'save_custom_field' );  
    function save_custom_field( $post_id ) {
    

     // grab the product
     $product = wc_get_product( $post_id );

      // save data
      $product->update_meta_data( 'custom_checkbox_field', isset($_POST['custom_checkbox_field']) ? 'yes' : 'no' ); 
      $product->save();
    }



checkbox not working in jquery Datatables row grouping

I have a datatable in which I apply row grouping to it. Also added checkbox control .i want to update row data of which checkbox is checked on button "btnupdate" clicked event,The api does grouping for the column 2 and when i checked the first checkboxes then my code is working but whenever i checked the last checkbox of any group it doesn't work. I've tried the code for grouping listed on the datatables website.The code I used for the button click event is shown below:

 //CODE FOR ROW GROUPING
     var groupColumn = 2;

        datatable1= $('#tblDemo').dataTable({
                 "pageLength": 25,
                 "displayStart": 25,
                 'length': 50,
                 "sScrollY": 260,
                 "sScrollX": "100%",                 
                  "columnDefs": [
                      { "visible": false, "targets": groupColumn }
                  ],
                  "order": [[groupColumn, 'asc']],
                  "displayLength": 25,
                  "drawCallback": function (settings) {
                      var api = this.api();
                      var rows = api.rows({ page: 'current' }).nodes();
                     var last = null;

                      api.column(groupColumn, { page: 'current' }).data().each(function (group, i) {
                        //  debugger;
                          if (last !== group) {
                              $(rows).eq(i).before(
                                  '<tr class="group"><td colspan="10">' + group + '</td></tr>'

                              );

                              last = group;
                          }
                      });
                  }
             });

//CODE FOR BUTTON CLICK FOR CHECKED/SELECTED ROW UPDATION

    $('#btnupdate').on("click",function () {
    
     var rows1;
     var itemDetails = new Array();
  
     rows1 = datatable1.find('tr:not(:hidden)');
     var temp,cnt;
     for (var i = 0; i < (rows1.length - 1); i++) {           
         var arr1 = new Array();            
         if ($("#chkbx" + i ).is(':checked')) {   ///chkbx is a id for checkboxes upto row count 
           
             temp = $.trim($("#txtSQty" + i ).val());
           
                 if (temp == arrQty[i]) {
                     arr1[0] = 'S'
                 }
                 else {
                     arr1[0] = 'M'
                 }
                 arr1[1] = temp
                 arr1[2] = arrPONo[i]    
                
                 itemDetails.push(arr1);
                 cnt = 0;                 
         }                         
     }
     if (cnt == 0) {
        
             --code for update row details--
             }      
    
     return false
 });

`

//arrPONo[i] ,arrQty[i] having the values in datatable colums,which fetch from database and stored in array

Could anyone help me with this? Thanks in advance.




mardi 20 avril 2021

How to control checkBox's checked props?

I made checkbox component and inside,
set isChecked state to remember checked values even after re-render in case of
new data will be fetched.
but because of this, isChecked state makes every checkbox being checked.
here is example. https://codesandbox.io/s/withered-sun-pm8o9?file=/src/App.js
how can I control checkboxes individually?




When check box filter clicked, it is re-rendered

When check box filter is checked, It calls filter api.
and jobInfo data is fetched.
I wanna filter multiple values. filter A and B,C at the same time.
But the problem is
When jobInfois fetched, checkbox component is re-rendered, and all the checked value
is unchecked automatically. So I can filter only one of them among A,B,C.
even I wrapped CheckboxFilter component with memo.
If there's any idea to solve it, I'd be appreciated.

const JobList = memo((props) => {
  const {jobInfo, filters} = useContext(JobInfoContext);

  //filters
  let filter = useRef([]);

  let info;
  let showTable;
  if (jobInfo['data']) {
    info = jobInfo['data'].map((info) => info);
    showTable = info.map((info) => (
      <TableRow key={uuid()}>
        <TableCell component="th" scope="row">
          {info.title}
        </TableCell>
      </TableRow>
    ));
  }

  const classes = useStyles();
  const option = ['A', 'B', 'C'];

  //체크박스 필터
  const handleCheck = (isChecked, item, label) => {
    if (isChecked && label === 'filter1') {
      filter.current.push(item);
    } else if (!isChecked && label === 'filter1') {
      let index = filter.current.indexOf(item);
      filter.current.splice(index, 1);
    }

    filters(filter.current);
  };

  return (
    <>
      <div className={styles.container}>
        <CheckboxFilter
          label="filter1"
          items={option}
          handleCheck={handleCheck}
        />
      </div>

      {/* Table */}
      <TableContainer component={Paper}>
        <Table className={classes.table} aria-label="simple table">
          <TableHead>
            <TableRow>
              <TableCell>Post date</TableCell>
              <TableCell align="left">Title</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>{showTable}</TableBody>
        </Table>
      </TableContainer>
    </>
  );
});

export default JobList;

this is CheckboxFilter component.

const CheckboxFilter = memo(({label, items, handleCheck}) => {
  const classes = useStyles();

  const check = (e, item) => {
    handleCheck(e.target.checked, item, label);
  };

  return (
    <div>
      <div className={styles.checkBoxDiv}>
        <div className={styles.label}>{label}</div>
        {items.map((item) => (
          <FormControlLabel
            key={uuid()}
            className={styles.formControlLabel + ' box1'}
            value="start"
            control={
              <Checkbox
                className={classes.root}
                disableRipple
                color="default"
                checkedIcon={
                  <span className={clsx(classes.icon, classes.checkedIcon)} />
                }
                icon={<span className={classes.icon} />}
                inputProps=aria-label
                onChange={(e) => check(e, item)}
              />
            }
            label={item}
            labelPlacement="end"
          />
        ))}
      </div>
    </div>
  );
});

export default CheckboxFilter;



On RecyclerView scroll random checkbox selected in kotlin

*Note: There are solutions for this issue in stackoverflow but all are written in java

In Recyclerview implemented checkbox OnCheckedChangeListener as follows, problem is when i scroll recyclerview then random checkbox is selected.

 override fun onBindViewHolder(holder: PickListViewHolder, position: Int) {
      holder.cbSelected.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                selectedSerialNumberList.add(this.scSerialNumberList[position])
            } else {
                selectedSerialNumberList.remove(this.scSerialNumberList[position])
            }
        }
     }

 inner class PickListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
     val cbSelected: CheckBox = itemView.cb_selected
    }



Excel VBA: Control multiple pass/fail checkboxes with one macro

I have a test document that will have a lot of pass/fail checkboxes on it. The checkboxes are ActiveX and when clicked, I need them to print "Pass" or "Fail" to a cell that they are located in within the Sheet. I need them printed to the sheet because Excel's track changes doesn't record when the checkbox is clicked. These checkboxes are not part of a userform.

In my example below, Checkbox7 and Checkbox8 are located in cell C14. I have over 50 groups of the pass/fail checkboxes and I am trying to figure out a way that all of the checkboxes be handled by 1-2 Subs instead of having one per each checkbox.

Private Sub CheckBox7_Click()
If CheckBox7 = True Then
    Range("C14").Value = "Pass"
Else
    Range("C14").Value = ""
End If
End Sub

Private Sub CheckBox8_Click()

If CheckBox8 = True Then
    Range("C14").Value = "Fail"
Else
    Range("C14").Value = ""

End If

End Sub

I don't think I can use the same approach found in this solution since I'm not using a userform. Any suggestions/help would be much appreciated




How to implement check box for permanent address is same as residential address in Mat-Formfield. and stepper I have tried various methods but couldn

Often when creating a form on a web page, I need our customers to fill out a field such as a permanent address, as well as a present address( when checked check box then present address fill automatically).I have searched for different methods but couldn't find a specific way to implement this in angular material components

<br>
<br>
<br>
<form name="registerForm" [formGroup]="registerForm" (ngSubmit)="register()" novalidate>
<mat-horizontal-stepper >
    <mat-step label="Personal Details" style="font-size: 70%;">

  <mat-form-field appearance="outline" style="width:55vw">
    <mat-label>Full Name(First Middle Last name)</mat-label>
    <input matInput  placeholder="full name" formControlName="fullname" [(ngModel)]="customerr.custName">
    <mat-hint style="color:red" *ngIf=" registerForm.get('fullname').touched && registerForm.get('fullname').errors?.required">Full name is required</mat-hint>
  </mat-form-field>  
  <br>
  <!-- <mat-form-field appearance="outline" style="width:55vw">
  <input matInput [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
  </mat-form-field> -->
  
  <br>
  <mat-form-field appearance="outline" style="width:55vw">
    <mat-label>Age</mat-label>
    <input matInput formControlName="age" placeholder="enter age" [(ngModel)]="customerr.custAge" >
    <mat-hint style="color:red" *ngIf=" registerForm.get('age').touched && registerForm.get('age').errors?.required">Full name is required</mat-hint>
  </mat-form-field>
  <br>
  
  <mat-form-field appearance="outline" style="width:55vw">
    <mat-label>Father's Name</mat-label>
    <input matInput matInput formControlName="fname" placeholder="enter father's name" [(ngModel)]="customerr.parentsName">
    <mat-hint style="color:red" *ngIf=" registerForm.get('fname').touched && registerForm.get('fname').errors?.required">Full name is required</mat-hint>
  </mat-form-field>
  <br>
    </mat-step>
  
    <mat-step label="Personal Details">
  <br>
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>MobileNumber</mat-label>
        <input matInput placeholder="Phone number" formControlName="mobileNumber" [(ngModel)]="customerr.mobileNumber" >
        <mat-hint style="color:red" *ngIf=" registerForm.get('mobileNumber').touched && registerForm.get('mobileNumber').errors?.required">Mobile no name is required</mat-hint>
      </mat-form-field>
      <br>
    
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>Email Id</mat-label>
        <input
        type="text"
        matInput
        formControlName="email" [(ngModel)]="customerr.emailID"
        class="form-input-field"
        pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}"
      />
      <mat-error *ngIf="registerForm.get('email').hasError('required')"
        >Email is required</mat-error
      >
      <mat-error *ngIf="registerForm.get('email').hasError('email')"
        >Please enter a valid email address
      </mat-error>
      </mat-form-field>
      <br>
    
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>Aadhar Card Number</mat-label>
        <input matInput placeholder="Enter aadhar no" formControlName="aadhar" [(ngModel)]="customerr.aadhar">
        <mat-hint style="color:red" *ngIf=" registerForm.get('aadhar').touched && registerForm.get('aadhar').errors?.required">Aadhar no  is required</mat-hint>
           </mat-form-field>
    <br>
    <mat-form-field appearance="outline" style="width:55vw">
      <mat-label>PAN Card Number</mat-label>
      <input matInput placeholder="Enter pan no" formControlName="pan" [(ngModel)]="customerr.pan">
        <mat-hint style="color:red" *ngIf=" registerForm.get('pan').touched && registerForm.get('pan').errors?.required">PAN no  is required</mat-hint>
               </mat-form-field>
            
                
  <br>
  
      <br>
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>Residential Address</mat-label>
        <input matInput placeholder="Enter Address" formControlName="addr1" [(ngModel)]="customerr.residentialAddress">
        <mat-hint style="color:red" *ngIf=" registerForm.get('addr1').touched && registerForm.get('addr1').errors?.required">Address  is required</mat-hint>
      </mat-form-field>
      <br>

       
        <!-- <mat-checkbox (click)="checked($event.target.checked)" formControlName="isSameAddress"> Is Permanent Address is same</mat-checkbox>
     -->
      <br>

      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>Permanent Address</mat-label>
        <input matInput  matInput placeholder="Enter Address" formControlName="addr2" [(ngModel)]="customerr.permanentAddress" >
        <mat-hint style="color:red" *ngIf=" registerForm.get('addr2').touched && registerForm.get('addr2').errors?.required">Address  is required</mat-hint>
      </mat-form-field>
      <br>
    
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>State</mat-label>
        <input matInput formControlName="state" placeholder="enter state name" [(ngModel)]="customerr.state">
        <mat-hint style="color:red" *ngIf=" registerForm.get('state').touched && registerForm.get('state').errors?.required">State is required</mat-hint>
      </mat-form-field>
      <br>
    
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>City</mat-label>
        <input matInput formControlName="city" placeholder="enter city name" [(ngModel)]="customerr.city">
        <mat-hint style="color:red" *ngIf=" registerForm.get('city').touched && registerForm.get('city').errors?.required">City is required</mat-hint>
    </mat-form-field>
      <br>
    
      <mat-form-field appearance="outline" style="width:55vw">
        <mat-label>Pincode</mat-label>
        <input matInput formControlName="pincode" placeholder="enter pincode" [(ngModel)]="customerr.pinCode">
        <mat-hint style="color:red" *ngIf=" registerForm.get('pincode').touched && registerForm.get('pincode').errors?.required">pincode is required</mat-hint>
    </mat-form-field> 
      <br>
    
    
         </mat-step> 
     
    <mat-step label="User Profile Login Details">
      <br>
      <mat-form-field appearance="outline"style="width:55vw">
        <mat-label >Login Password</mat-label>
        <input input type="password" matInput formControlName="password" placeholder="enter Password" [(ngModel)]="customerr.loginPassword"> 
      </mat-form-field>
      <br>
      <mat-form-field appearance="outline"style="width:55vw">
        <mat-label>Confirm Login Password</mat-label>
        <input type="password" matInput placeholder="Verify Password" formControlName='verifyPassword' [errorStateMatcher]="errorMatcher">
    <mat-error *ngIf="registerForm.hasError('passwordsDoNotMatch')">
      Passwords do not match! Please Re-enter!
    </mat-error>
      </mat-form-field>
      <div class="state">
        Do passwords match? 
        <strong></strong>
      </div>
      <br>
      <section>
        <button mat-raised-button color="primary" > Submit</button>
    </section>  
      </mat-step>  
    </mat-horizontal-stepper>
  </form>

Ts file of the component

import { Component, OnInit } from '@angular/core';
import{FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm} from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { Router } from '@angular/router';
import { Customerr } from '../Customerr';
import { LoginService } from '../login.service';

/** Error when the parent is invalid */
class CrossFieldErrorMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return control.dirty && control.untouched && form.invalid;
  }
}

@Component({
  selector: 'app-stepper',
  templateUrl: './stepper.component.html',
  styleUrls: ['./stepper.component.css']
})
export class StepperComponent implements OnInit {

  customerr:Customerr= new Customerr();
  
  errorMatcher = new CrossFieldErrorMatcher();
  registerForm: FormGroup;
  passwordValidator(form: FormGroup) {
    const condition = form.get('password').value !== form.get('verifyPassword').value;

    return condition ? { passwordsDoNotMatch: true} : null;
  }

  constructor(private fb:FormBuilder, private service:LoginService, private router:Router) { }
 
  ngOnInit(){
    this.registerForm = this.fb.group({
      // isSameAddress:[false],



      email: new FormControl('', [Validators.required, Validators.email]),
      fullname:['', Validators.required],
        age:['', Validators.required],
        fname:['', Validators.required],
        mobileNumber: ['', [Validators.required, Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")]],
        state:['',Validators.required],
        city:['',Validators.required],
        landmark:['',Validators.required],
        occ:['',Validators.required],
        soi:['',Validators.required],
        gi:['',Validators.required],
        addr1:['',Validators.required],
        addr2:['',Validators.required],
        aadhar:['',[Validators.required,Validators.pattern("^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$")]],
        pan:['',[Validators.required,Validators.pattern("[A-Z]{5}[0-9]{4}[A-Z]{1}")]],
        pincode:['',Validators.required],
        password: ['', Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")],
      verifyPassword: ['',Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")]
    }, {
      validator: this.passwordValidator
    })


  }
 

    register(){
      this.service.registerUser(this.customerr).subscribe(
        customerPersisted=>{ console.log( customerPersisted);

        }
      );

    }

    // checked(value:boolean){
    //   if(value){
    //     this.registerForm.controls.addr1.setValue(this.registerForm.value.addr2);
    //      //this.registerForm.controls.addr2.setValue(this.registerForm.value.addr1)
    //   }else{
    //     this.registerForm.controls.addr1.setValue(undefined);
    //     this.registerForm.controls.addr2.setValue(undefined)
    //   }
    // }
}
```