vendredi 31 juillet 2020

Undefined offset in checkbox dynamic field

I have a dynamic field where user can add as many rows as it wants. There are 3 checkboxs in each row. after user added as much as they wanted they click a button and get sent to FgProcess.php.

FgTable.php

<script>
var FgRow = 0;
function addfg()
{
    FgRow++;
    var html = "<tr>";
        html += "<td><input type='text' name='SKUDescription[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='LotNumber[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='BBD[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='Size[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='SizeUOM[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='UnitsPerCase[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='CaseCount[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='CasePartial[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='UnitsDamaged[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='UnitsLeak[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='UnitsSample[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='UnitTotal[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='NetWeightTotal[]' class ='form-control'/></td>";
        html += "<td><input type='text' name='ProductTemperature[]' class ='form-control'/></td>";
        html += "<td><input type='checkbox' name='Organic[]' value='1' class='custom-checkbox'/></td>";
        html += "<td><input type='checkbox' name='OnHold[]' value='1' class='custom-checkbox'/></td>";
        html += "<td><input type='checkbox' name='WIP[]' value='1' class='custom-checkbox'/></td>";
        html += "<td style='width: 2%'></td>";
        html += "</tr>";
        
        document.getElementById("finishedgoods_row").insertRow().innerHTML = html;
}

My Problem is that I get an offset error when user does not check the checkboxes. I know the reason is that if not checked the value is NULL.

I tried fixing this issue by adding hidden input for each of my checkboxes but then I got extra checkbox values sometimes!

FgProcess.php

if (isset($_POST['fgAdd']))
{
    $WOID = $_POST['id'];
    print_r($_POST);

    for ($i = 0; $i < count($_POST["SKUDescription"]); $i++)
    {
        $SKUDescription = $_POST["SKUDescription"][$i];
        $LotNumber = $_POST["LotNumber"][$i];
        $BBD = $_POST["BBD"][$i];
        $Size = $_POST["Size"][$i];
        $SizeUOM = $_POST["SizeUOM"][$i];
        $UnitsPerCase = $_POST["UnitsPerCase"][$i];
        $CaseCount = $_POST["CaseCount"][$i];
        $CasePartial = $_POST["CasePartial"][$i];
        $UnitsDamaged = $_POST["UnitsDamaged"][$i];
        $UnitsLeak = $_POST["UnitsLeak"][$i];
        $UnitsSample = $_POST["UnitsSample"][$i];
        $UnitTotal = $_POST["UnitTotal"][$i];
        $NetWeightTotal = $_POST["NetWeightTotal"][$i];
        $ProductTemperature = $_POST["ProductTemperature"][$i];

        if ($_POST["Organic"][$i]==null){$Organic = '0';}else{$Organic = $_POST["Organic"][$i];}
        if ($_POST["OnHold"][$i]==null){$OnHold = '0';}else{$OnHold = $_POST["OnHold"][$i];}
        if ($_POST["WIP"][$i]==null){$WIP = '0';}else{$WIP = $_POST["WIP"][$i];}
        //after this part insert into mysql and check errors and etc
    }
        //the rest of if statement

I tried checking for NULL but it didn't work. Each of these lines gave me a Undefined offset: 1 error.

if ($_POST["Organic"][$i]==null){$Organic = '0';}else{$Organic = $_POST["Organic"][$i];}
if ($_POST["OnHold"][$i]==null){$OnHold = '0';}else{$OnHold = $_POST["OnHold"][$i];}
if ($_POST["WIP"][$i]==null){$WIP = '0';}else{$WIP = $_POST["WIP"][$i];}

for example when i tried to add two rows, with the first row checkboxes being checked and then second row not being checked, this is what i get when print_r($_POST)

[Organic] => Array ( [0] => 1 ) [OnHold] => Array ( [0] => 1 ) [WIP] => Array ( [0] => 1 )

I know the problem is from checkboxes since i had no problem when the 3 checkboxes were text.

I would appreciate any help.




how to get value of checkbox in react js

I am trying to retrieve the check value of my checkbox but i get null value this is my code

<form onSubmit={this.onSubmit}>
<fieldset>
<legend>RFX/RFP:</legend>
<div className="form-check">
  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfx} name="rfx" id="rfx" />
  <label className="form-check-label"  name="rfx">RFX</label>
  &nbsp; &nbsp; &nbsp; &nbsp;

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp}  name="rfp" id="rfp"  />
  
  <label className="form-check-label" >RFP</label>
  &nbsp; &nbsp; &nbsp; &nbsp;

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp_x}  name="rfp(x)" id="rfp(x)"/>
  <label className="form-check-label" >RFP(X)</label>
  &nbsp; &nbsp; &nbsp; &nbsp;


  <input type="checkbox" className="form-check-input"  onChange={this.onChange}name="all" id="all" />
  <label className="form-check-label"  name="all" id="all">ALL</label>
</div>
</form>

and my methods :

constructor(props){
    super(props)
    this.state={
      rfp:"",
      rfx:"",
      rfp_x:"",
      all:"",
    
 
    }
    this.onChange =  this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
   }
  onChange(e){
    this.setState({[e.target.name] : e.target.value});}
  onSubmit(e){
    e.preventDefault();
    const FilterRegion={
  
      rfx:this.state.rfx,
      rfp:this.state.rfp,
      rfp_x:this.state.rfp_x,
      all:this.state.all,
    }
    console.log(FilterRegion)
   }

and the screen when i submit my form :

https://gyazo.com/32a24813545ebf7d3a48b72be724a76f

please I try to solve my problem and display the value or the name of my check box! what do I have to do




Grapesjs - Custom Checkbox Group

I am trying to create custom component type in grapejs, but not getting its documentation. Tried to write this plugin, but somehow its working partially, it render well when i drop it to canvas, but after refresh all checkboxes go away and static text Please update checkbox metadata for generating checkbox group appears.

I am also calling same checkbox render code in view: onRerender().

Please show some light.

const metaData = {
    name: 'checkbox-group',
    noOfCols: 2,
    class: 'checkbox-wrapper',
    checkboxes: `{
      "data": [
        {
          "label": "First",
          "value": "checkbox value"
        },
        {
          "label": "Second",
          "value": "checkbox value",
          "checked": true
        },
        {
          "label": "Third",
          "value": "checkbox value",
          "textbox": {
            "placeholder": "reason of choosing",
            "name": "other"
          }
        }
      ]
    }`,
  }
  
  const CustomCheckboxGroup = editor => {
    editor.DomComponents.addType('checkbox-group', {
      model: {
        defaults: {
          tagName: 'div',
          draggable: 'form, form *',
          droppable: false, 
          editable: false,
          traits: [
            'name',
            {
              type: 'text',
              name: 'class',
              label: 'class',
              changeProp: 1
            },
            { 
              type: 'text', 
              name: "checkboxMeta", 
              label: 'Checkbox Meta',
              changeProp: 1,
            },
            { 
              type: 'number', 
              name: "noOfCols", 
              label: 'Number of columns',
              changeProp: 1
            },
            {
              type: 'checkbox',
              name: 'required'
            }
          ],
          attributes: { name: metaData.name, required: true  },
          content: `Please update checkbox metadata for generating checkbox group`,
        },
        init(){
          this.on('change:noOfCols', this.handlePropChange);
          this.on('change:checkboxMeta', this.handlePropChange);
          this.on('change:attributes:name', this.handlePropChange);
          this.on('change:class', this.handlePropChange);
          this.on('change:attributes:required', this.updateRequired);
        },
        handlePropChange(){
          const el = this.getEl();
          const name = this.get('name') || Date.now().toString();
          const className = this.get('class') || metaData.class;
          const noOfCols = this.get('traits').where({name: 'noOfCols'})[0].get('value') || metaData.noOfCols;
          let checkboxesToGenerate = this.get('traits').where({name: 'checkboxMeta'})[0].get('value') || metaData.checkboxes;
          let generate = 0;
          const columns = [];
          if(checkboxesToGenerate.trim().length > 0) {
            generate = checkboxesToGenerate.length;
            try {
              checkboxesToGenerate = JSON.parse(checkboxesToGenerate).data;
              for (let i = noOfCols; i > 0; i--) {
                columns.push(checkboxesToGenerate.splice(0, Math.ceil(checkboxesToGenerate.length / i)));
              }
            } 
            catch(err) {
              console.log("Error :", err);
            }
          }
          el.innerHTML = "";
          if(generate > 0) {
            for (let j = 0; j < noOfCols; j++) {
              const data = columns[j];
              const column = (document.createElement("div") as HTMLElement);
              column.setAttribute('class', "col col-"+(j+1));
              column.style.width = (100 / noOfCols) + "%";
              if(data) {
                for(let i = 0; i < data.length; i++) {
                  const parentEle = (document.createElement("div") as HTMLElement);
                  parentEle.classList.add(className);
                  const checkboxEle = (document.createElement("input") as HTMLInputElement);
                  checkboxEle.setAttribute('class', 'checkbox');
                  checkboxEle.type = 'checkbox';
                  checkboxEle.name = name;
                  checkboxEle.value = data[i]['value'];
                  checkboxEle.id = name + '-' + j + '-'+ i;
                  checkboxEle.checked = data[i]['checked'];
                  var newlabel = document.createElement("Label");
                  newlabel.setAttribute("for", checkboxEle.id);
                  newlabel.innerHTML = data[i]['label'];
                  parentEle.appendChild(checkboxEle);
                  parentEle.appendChild(newlabel);
                  column.appendChild(parentEle);
                  if(data[i]['textbox']) {
                    var newTextBox = document.createElement("input");
                    newTextBox.setAttribute('type', 'text');
                    newTextBox.name = data[i]['textbox']['name'];
                    newTextBox.placeholder = data[i]['textbox']['placeholder'];
                    newTextBox.classList.add('hide');
                    // eslint-disable-next-line no-loop-func
                    checkboxEle.addEventListener('change', function(){
                      if(this.checked) {
                        newTextBox.classList.remove("hide");
                      } else {
                        newTextBox.classList.add('hide');
                      }
                    });
                    parentEle.appendChild(newTextBox);
                  }
                }
                el.appendChild(column);
              }
            }
          }
        }
      },
      view: {
        tagName: 'div',
        onRender({ el, model }) {
          const name = model.get('traits').where({name: 'name'})[0].get('value') || Date.now;
          const className = model.get('traits').where({name: 'class'})[0].get('value') || metaData.class;
          const noOfCols = model.get('traits').where({name: 'noOfCols'})[0].get('value') || metaData.noOfCols;
          let checkboxesToGenerate = model.get('traits').where({name: 'checkboxMeta'})[0].get('value') || metaData.checkboxes;

          let generate = 0;
          const columns = [];
          if(checkboxesToGenerate.trim().length > 0) {
            generate = checkboxesToGenerate.length;
            try {
              checkboxesToGenerate = JSON.parse(checkboxesToGenerate).data;
              for (let i = noOfCols; i > 0; i--) {
                columns.push(checkboxesToGenerate.splice(0, Math.ceil(checkboxesToGenerate.length / i)));
              }
            } 
            catch(err) {
              console.log("Error :", err);
            }
          }
          if(generate > 0) {
            for (let j = 0; j < noOfCols; j++) {
              const data = checkboxesToGenerate[j];
              const column = (document.createElement("div") as HTMLElement);
              column.setAttribute('class', "col col-"+(j+1));
              column.style.width = (100 / noOfCols) + "%";
              if(data) {
                for(let i = 0; i < data.length; i++) {
                  const parentEle = (document.createElement("div") as HTMLElement);
                  parentEle.setAttribute('class', className);
                  const checkboxEle = (document.createElement("input") as HTMLInputElement);
                  checkboxEle.setAttribute('class', 'checkbox');
                  checkboxEle.type = 'checkbox';
                  checkboxEle.name = name;
                  checkboxEle.value = data[i]['value'];
                  checkboxEle.id = name + '-' + j + '-'+ i;
                  checkboxEle.checked = data[i]['checked'];
                  
                  var newlabel = document.createElement("Label");
                  newlabel.setAttribute("for", checkboxEle.id);
                  newlabel.innerHTML = data[i]['label'];
                  parentEle.appendChild(checkboxEle);
                  parentEle.appendChild(newlabel);
                  column.appendChild(parentEle);
                  if(data[i]['textbox']) {
                    var newTextBox = document.createElement("input");
                    newTextBox.setAttribute('type', 'text');
                    newTextBox.name = data[i]['textbox']['name'];
                    newTextBox.placeholder = data[i]['textbox']['placeholder'];
                    newTextBox.classList.add('hide');
                    // eslint-disable-next-line no-loop-func
                    checkboxEle.addEventListener('change', function(){
                      if(this.checked) {
                        newTextBox.classList.remove("hide");
                      } else {
                        newTextBox.classList.add('hide');
                      }
                    });
                    parentEle.appendChild(newTextBox);
                  }
                }
                el.appendChild(column);
              }
            }
          }
        }
    })
  }
  export default CustomCheckboxGroup;



How to jqGrid dynamic multiselecet?

I hava jqGrid checkbox column,This dynamic build

                colNames: ['Id', 'True/False'],
            colModel: [
                { name: 'Id', index: 'Id', sorttype: "int", hidden: false },
                {
                    name: "Selected", index: 'Selected', width: 70, align: "center",
                    formatter: "checkbox", formatoptions: { disabled: false },
                    editable: false, editoptions: { value: "True:False", defaultValue: "No" },
                    stype: "select", searchoptions: {
                        sopt: ["eq", "ne"],
                        value: ":Any;true:Yes;false:No"
                    },
                },

this code selected columns is checkbox how to this column is multiple selection with its own feature jqGrid

Multiselect: true

And I cant checkbox value (true or false ) How can I do it? ;

If selected column value is true, get multiselect (jqGrid feature) true If selected column false,get multiselect column false

Thank you in advance for your help. I wish you a good day.




Add checkboxes to php contact form

I would like to add checkboxes to a contact form, but not getting it to work. How do i get it to send in the email?

I have this form from a previous contact form and would like to adapt it so that it handles checkboxes which are sent to the email address. Is there a way to change the php to process which items are selected and which are not?

Html

      <form class="contact-page" method="post" action="/mail.php">
      <div class="form-group">
          <input name="name" type="text" class="form-control" placeholder="Name" required>
      </div>
      <div class="form-group">
          <input name="email" type="email" class="form-control" placeholder="Email" 
      required>
      </div>
      <div class="form-group">
          <input name="phone" type="text" class="form-control" placeholder="Phone" required>
      </div>
      <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
      <label for="vehicle1"> I have a bike</label><br>
      <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
      <label for="vehicle2"> I have a car</label><br>
      <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
      <label for="vehicle3"> I have a boat</label><br><br>
      <div class="form-group">
          <textarea name="message" class="form-control" rows="6" style="height: 150px;" 
       placeholder="Message" required></textarea>
      </div>
      <div class="form-group form-check">
          <input type="checkbox" class="form-check-input" id="exampleCheck1">
          <label class="form-check-label" for="exampleCheck1" required>I confirm that ???? 
       can store my details</label>
      </div>
     <input type="submit" class="btn btn-light" value="Submit">
      </form>

PHP

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    # FIX: Replace this email with recipient email
    $mail_to = "test@test.com";

    # Sender Data
    $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST["phone"]);
    $message = trim($_POST["message"]);

    if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR 
    empty($message)) {
        # Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo '<p class="alert alert-warning">Please complete the form and try again.</p>';
        exit;
    }

    $ip = $_SERVER['REMOTE_ADDR'];
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify? 
    secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
    $responseKeys = json_decode($response,true);

    if(intval($responseKeys["success"]) !== 1) {
      echo '<p class="alert alert-warning">Please check the the captcha form.</p>';
    } else {
        
        $subject = 'Enquiry From Website ' . $_SERVER['HTTP_HOST'];
        # Mail Content
        $content = "Name: $name\n";
        $content .= "Email: $email\n\n";
        $content .= "Phone: $phone\n";
        $content .= "Message:\n$message\n";


        $body .= 'Selected Projects: ' . $selectedProjects;
        # email headers.
        $headers = "From: $name <$email>";

        # Send the email.
        $success = mail($mail_to, $subject, $content, $headers);
        header('Location: thank-you');
        if ($success) {
        header('Location: thank-you');
        } else {
            # Set a 500 (internal server error) response code.
            http_response_code(500);
            echo '<p class="alert alert-warning">Oops! Something went wrong, we couldnt send 
     your message.</p>';
        }
    }

    } else {
    # Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo '<p class="alert alert-warning">There was a problem with your submission, please 
    try again.</p>';
    }

     ?>



Rshiny: Extract checked values from a list of grouped checkboxes

I'm trying to make check boxes for each car model in a grouping variable, 'cylinders'.

To achieve this, I'm using lapply() to go through the groups making a groupedCheckbox in a collapsing well panel, for each.

However only some of the checked car models are read. Initially all of the checked cars in the first cylinder group can be read but not those in the second two groups !

However once some of the car models in the first group are ticked, then cars in the second two groups are also read. Image of multiple checkbox groups with only checkboxes in first box are read

MultipleGroupCheckboxProblem

Does anyone know how all of the ticked cars can be extracted into a reactive vector?

I have a feeling the solution might involve proper use of lapply and/or unlist.

Also the car names originate from the row names of the input table.

Code here, using mtcars :

library(shiny)
library(shinyBS)
ui <- fixedPage(
  h2("R Shiny: Multiple collapsing tickboxes"),
  

  
  tags$style(HTML("
.checkbox{margin-top: -20px; margin-left: 0px; margin-bottom: -5px;padding:-5px; margin-right: -400px;}
  .panel{margin: -5px;}")),

  uiOutput("grouped.tickboxes"), 
  
  textOutput("selectedtext")
)

# .panel{margin: 2px;padding:1px}")),



server <- function(input, output, session) {
  
  output$grouped.tickboxes <- renderUI({
    
    lapply(sort(unique(mtcars$cyl)), function(x) {
      
      fluidRow(
        
        div(tags$style(HTML("
                 .checkbox{margin: 0px; ;padding:0px; margin-right: -400px;}")),
            
        bsCollapsePanel(paste0("Cylinders: ", x), 
                        style = "color:grey; border-top: 1px solid black",
                        # style = "color:grey;",
                        
                        column(12,
                               
                               checkboxGroupInput(inputId = "stuff", 
                                                  NULL, choices = sort(row.names(subset(mtcars, cyl %in% x))))))
      )
      )
    })
  })
  
  
  seltex = reactive({
    ## maybe need to use lapply to read values.
    # paste0(input$stuff, collapse = ", ")
    # paste0(as.vector(unlist(input$stuff, use.names = FALSE)), collapse = ", ")
    # as.vector(unlist(input$stuff, use.names = FALSE))[1]
    # head(str(input$stuff))
    # lapply(input$stuff, str(input$stuff)[2]
    # paste0(unlist(unlist(unlist(input$stuff), use.names = FALSE)), collapse = ", ")
    # paste0(unlist(unlist(unlist(input$stuff)), use.names = FALSE), collapse = ", ")
    # paste0(unlist(unlist(input$stuff)), collapse = ", ")
    paste0("Selected cars : ", paste0(unlist(input$stuff), collapse = ", "))
  })

  output$selectedtext = renderText({ as.character(seltex() )})
  
}


# grouped.tickboxes

shinyApp(ui, server)



Google Sheets - Conditional Formatting - Multiple Check Boxes

Google Sheets Check Boxes Conditional Formating Multiple Boxes.

CLICK ON THE TITLE TO SEE AN IMAGE OF THE SPREADSHEET

I am trying to make conditional formatting in google sheets so that if one box is checked, the row highlights orange; if the second checkbox is marked, the row is highlighted red; and if both checkmarks are marked, the row highlights green. I think I can do this if I create a formula: =IF([$Z4]$1 = 1, "A") + IF([$AA4]$2 = 1, "B") +IF([$z4:$AA4]$3 = 1, "C") and then set the conditional formating based on the letter returned by the formal. Some help would be appreciated




How to call back checkboxs in kivy?

self.t_and_c = Label(text='Accept terms and conditions: ') self.inside.add_widget(self.t_and_c)

    self.checkbox_first = CheckBox(active=False)
    self.checkbox_first.bind(active = self.checkbox_status)
    self.inside.add_widget(self.checkbox_first)
    
    self.pvt_policy = Label(text='Accept private policy: ')
    self.inside.add_widget(self.pvt_policy)
    
    self.checkbox_second = CheckBox(active=False)
    self.checkbox_second.bind(active = self.checkbox_status)
    
    self.inside.add_widget(self.checkbox_second)
    self.inside.add_widget(Label())
    self.enter = Button(text='Enter information', disabled=True)
    self.inside.add_widget(self.enter)
    
    
def checkbox_status(self, instance):
    if self.checkbox_first.active == True and self.checkbox_second.active == True:
        self.enter.disabled == False
    else:
        self.enter.disabled == True

I want to create a function which disables a button until two checkboxes have been 'checked'. I am trying to call the checkbox but I get this error:

TypeError: checkbox_status() takes 2 positional arguments but 3 were given

I am confused as to why I would need another input argument, any help is appreciated but please could the answer be given in the Python language rather than kv?




Vuetify datatable select all with disabled checkboxes

I'm having an issue with datatables with select rows. I have rows which have the checkbox disabled, but the select all checks them anyway... Is this a bug?

I made a codepen: https://codepen.io/slayerbleast/pen/jOWjzWJ

How can I fix the selectAll checkbox only check the available checkboxes?

Template:

<v-content>
    <v-data-table
        v-model="selected"
        :headers="headers"
        :items="desserts"
        item-key="name"
        show-select
    >
    <template #item="{ item }">
        <tr>
            <td>
                <v-checkbox
                    :disabled="item.calories > 250"
                    class="pa-0 ma-0"
                    :ripple="false"
                    v-model="selected"
                    :value="item"
                    hide-details
                >
                </v-checkbox>
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </template>
    </v-data-table>
</v-content>

data:

data: () => ({
        selected: [],
            headers: [
          {
            text: 'Dessert (100g serving)',
            align: 'start',
            sortable: false,
            value: 'name',
          },
          { text: 'Calories', value: 'calories' },
          { text: 'Fat (g)', value: 'fat' },
          { text: 'Carbs (g)', value: 'carbs' },
          { text: 'Protein (g)', value: 'protein' },
          { text: 'Iron (%)', value: 'iron' },
        ],
        desserts: [...]
})



Update database with html Switch Checkbox php if statement

Hope someone help sort this for me, even if its another solution, as I have hit the php brick wall

I have a form with a checkbox switch in it

                       <div class="col-md-3">
                        <input type="hidden" name="needclean" value="No" checked />
                        <div class="switch">
                        <label>NO<input type="checkbox" name="needclean" value="Yes"><span class="lever switch-col-green"></span>YES</label>
                        </div>
                        </div>

What I want to happen is when the user clicks "Yes" it populates the cell in the DB called "Status" to "Needs Cleaning" and if the user Clicks "No" it populates the "Status" cell in the DB to "Good to Go"

I have tried this

<?php
                    if(isset($_POST['needclean'])){
                    $clean = $_POST['needclean'];
                }
                if(isset($needclean) == "Yes"){ 
                    echo '<input type="hidden" name="status" value="Needs Cleaning" />';
                } else {
                     echo '<input type="hidden" name="status" value="Good to Go" />';
                }

                    ?>

But all it does is populate the "Status" cell with "Good to go" no matter if I select Yes or No

I hope I have explained this and if you need any more info please let me know

Thanks in advance for any help




onCheckedChanged vs onCheckStateChanged

What is the difference between onCheckedChanged and onCheckStateChanged? Both yield the same result when I check/uncheck the box.

import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3

Page {

    id : somepageid


    CheckBox {
        checked: true
        text: qsTr("Check Me")
        indicator.width: 15
        indicator.height: 15

        onCheckedChanged: {
            console.log(checked)
        }

        onCheckStateChanged: {
            console.log(checked)
        }

    }
}




jeudi 30 juillet 2020

Why is the checkbox checked value not changing?

I have a react component in Filter.js which acts as a filter and have the following code:

const filter = (props) => {
  const dataArray = [];
  for (const key in props.chapter) {
    const data = props.chapter[key][0][0];
    dataArray.push(
      <li key={key}>
        <div>
          <GreyCheckbox
            value={data.verse.number}
            onChange={props.changeHandler}
          />
          <p>{data.verse.englishName}</p>
        </div>
      </li>
    );
  }

  return (
    <div className="filter">
      <div className="filterTitle">Filter</div>
      <div>
        <ul>
          {dataArray.map((data) => {
            return data;
          })}
        </ul>
      </div>
    </div>
  );
};

I have the onChange={props.changeHandler} which is passed in my App.js as the following handler:

const filterHandler = (event) => {
    if (event.target.checked) {
      setFilterView({
        ...filterView,
        [event.target.value]: chapters[event.target.value],
      });
      console.log('got it checked');
    } else {
      console.log('it was unchecked');
    }
    //console.log(event.target.checked);
  };

The issue I am having is that when the setFilterView code is present the checkbox does changed to a checked state. When that is removed and it is only the console.log statement the box gets checked. What am I doing wrong in how I setup the handler?




Vuetify data table override item slot with select row

I'm using the <v-data-table> and I wanted to override the item slot, the problem is I want the select row funcionality too and I don't know how to replicate the same default.

I made this codepen: https://codepen.io/slayerbleast/pen/jOWjzWJ




Uncheck/Check all checkboxes at once

I want to check/uncheck all the remaining checkboxes on checking/unchecking of another checkbox (All option - the first checkbox in the listview).

In QML such actions are handled using IDs and since my Listview is dynamically generated from a model, I am unable to generate IDs for the other checkboxes. Currently, my code only checks/unchecks the first checkbox in the list. Please point me what am I doing wrong

import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3

Page {

    id : somepageid

    ListView{

        id: multiSelectCheckList
        model: ["1", "2", "3", "4"]
        height: parent.height
        width: parent.width

        delegate: Column{

            height: 20
            width: parent.width


            // All checkbox option

            Loader{

                id: loaderAll
                height: 15
                active: model.row === 0
                sourceComponent:

                    CheckBox {
                    checked: true
                    text: "All"
                    indicator.width: 15
                    indicator.height: 15

                    onCheckStateChanged: {
                        // Here I want the check/uncheck feature
                        console.log("All", checked)

                        if(checked){
                            modelCheckBoxes.checked = true
                        } else{
                            modelCheckBoxes.checked = false
                        }
                    }
                }
            }

            // These checkboxes need to be check/uncheck
            // on clicking the above checkbox
            CheckBox {

                id: modelCheckBoxes
                anchors.top: loaderAll.bottom
                checked: true
                text: modelData
                indicator.width: 15
                indicator.height: 15

            }

        }
    }


}



mercredi 29 juillet 2020

Multiselection of Checkbox is not working in JQuery

I have a button for "Select All" that will set all the List of Orders in that Page as checked in checkbox. And I am able to achieve this function with this below code

$("#SelectAll").on("click", function () {
    var txt = $(this).val();
    if (txt === 'Select All') {
        $(this).val("Unselect All");
        $("input[name='SelectOrder']").attr('checked', true);
        document.getElementById('bulk-action').style.display = "block";
    }
    else {
        $(this).val("Select All");
        $("input[name='SelectOrder']").attr('checked', false);
        document.getElementById('bulk-action').style.display = "none";
    }

});

I have checkbox each data so that the user can select which data in the list. When selecting orders in the sales orders grid and unselecting, then clicking "Select All", the rows previously selected do not select. Here is the implementation for selecting order.

$(".SelectOrder").on("click", function () {
    var idVal = $(this).val();
    var idData = "#tdid-" + idVal;
    if (idVal.checked == true) {
        $(idData).attr('checked', false);
    } else {
        $(idData).attr('checked', true);
    }
    document.getElementById('bulk-action').style.display = "block";
    GetSelectedOrdersBulk();
});

function GetSelectedOrdersBulk() {
    var checkedVals = $('.SelectOrder:checkbox:checked').map(function () {
        var orderId = this.value;
        return orderId;
    }).get();

    if (checkedVals.length == 0) {
        document.getElementById('bulk-action').style.display = "none";
    }
    return checkedVals;
}

Select All button and checkbox:

 <input type="button" class="btn btn-info btn-xs" name="SelectAll" value="Select All" id="SelectAll" />

<td>
    <input type="checkbox" name="SelectOrder" class="SelectOrder" value="@item.OrderId" id="tdid-@item.OrderId"/>
</td>

enter image description here




Not rerender checkbox after clicking on them/ changing internal status

I am trying to create checkboxes but I cannot get them to rerender when I click on them, so for some reason I feel like the setState is not causing React to rerender and I am not sure how to fix it. The code is the following:

import React, { PureComponent } from 'react';                                    
                                                                                 
export const CheckBox = props => {                                               
    return (                                                                     
      <li>                                                                       
       <input key={props.id}                                                     
        onClick={props.handleCheckChildElement}                                  
        type="checkbox"                                                          
        checked={props.isChecked}                                                
        value={props.value}                                                      
        /> {props.value}                                                         
      </li>                                                                      
    )                                                                            
}                                                                                
                                                                                 
export default CheckBox 

and then using them on an array this way:

import React, { PureComponent } from 'react';                                    
import  CheckBox  from './CheckBox';                                             
                                                                                 
class FruitSelect extends PureComponent {                                         
    constructor(props) {                                                         
        super(props)                                                             
        this.state = {                                                           
            fruits: [                                                             
                {id: 1, value: "Apple", isChecked: false},                           
                {id: 2, value: "Orange", isChecked: false},                           
                {id: 3, value: "Banana", isChecked: false}                                                     
            ]                                                                    
        }                                                                        
    }                                                                            
                                                                                 
    handleAllChecked = (event) => {                                              
        let newFruits = this.state.fruits                                          
        newFruits.forEach(fruit => fruit.isChecked = event.target.checked)          
        this.setState({fruits: newFruits})                                         
    }  

   handleCheckChildElement = (event) => {                                       
        let newFruits = this.state.fruits                                          
        newFruits.forEach(fruit => {                                               
            if (fruit.value === event.target.value){                              
                fruit.isChecked = !fruit.isChecked                                 
            }                                                                    
        })                                                                       
        this.setState({fruits: newFruits})                                         
    }                                                                            
                                                                                 
    render() {                                                                   
        return (                                                                 
            <div className="FruitSelect">                                         
                <input type="checkbox"                                           
                       onClick={this.handleAllChecked}                           
                       value="checkedall"                                        
                />                                                               
                <ul> {                                                           
                    this.state.fruits.map((fruit) => {                             
                        return (<CheckBox                                        
                            handleCheckChildElement={this.handleCheckChildElement}
                            {...fruit}                                            
                        />)                                                      
                    })                                                           
                }</ul>                                                           
            </div>                                                               
        );                                                                       
    }                                                                            
}                                                                                
                                                                                 
export default FruitSelect  

but when I try using the component on my App it does not re render when I check the boxes (I can see internally the checked values do change. How canI fix this?




Why checkbox rectangle is by far smaller than the container that contains it?

Can understand why the rectangle that get color (when checked) and uncolored (when unchecked) isn't take all the place (please find attached screenshot). Try to investigate the issue but didn't come to any conclusion. Hope that someone can help me here The layout xml is:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="@android:color/holo_blue_bright"
    tools:context=".MainActivity">


   <TextView
       android:id="@+id/textViewww"
       android:layout_width="150dp"
       android:layout_height="80dp"
       android:text="Just For Try"
       app:layout_constraintTop_toTopOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       android:gravity="center"
       android:background="#34ab56"
       android:layout_margin="15dp"/>

    <Button
        android:id="@+id/button_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Draw Again On TextView"
        app:layout_constraintTop_toBottomOf="@id/textViewww"
        app:layout_constraintStart_toStartOf="parent"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintTop_toBottomOf="@id/button_b"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="15dp"/>

    <androidx.appcompat.widget.AppCompatCheckBox
        android:id="@+id/checkbox_checkbox"
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="20dp" />


</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here




check checkbox only if values in array A exist in array B

I'm checking through an array to check if some selected values exists in there then a checkbox should be checked. Though the values are found in there, the checkbox it's not checked. When I log the results, its able to produce the correct response ('hello') in the console meaning the code works perfectly but I don't know why its not able to check the checkbox

this.selected = [ 1, 8032, 8042, 8047, 8021, 7986];

this.srvresp = [{id:11, name:'AA'}, {id:8032, name:'BB'}, {id:10, name:'CC'}, {id:409, name:'DD'}, {id:300, name:'EE'} ,{id:302, name:'FF'}, {id:478, name: 'GG'}, {id:8042, name: 'HH'}, {id:8047, name:'II'}, {id:8021, name:'JJ'}, {id:7986, name:'KK'}];

for (const  s of this.srvresp) {
  for (const  selected of this.selected) {
    if (s.id == selected) {
      console.log('hello')
      s.checked = true;
    }
  }
}

HTML

<div *ngFor="let item of srvresp; index as ind">
 <input [(ngModel)]="item.checked" formControlName="selectedStudents" [value]="item.id" type="checkbox" class="custom-control-input" id="-item-">

</div>



Listener for checkboxes in two different JTables

I am creating a java GUI in netbeans that has two tables. I made a listener for the JTables that will detect if the value of the checkboxes within the JTables changes, but for some reason it only works for my first table.

Here is my code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;

import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

/**
 *
 * @author Lenovo
 */
public class TaskFrame extends javax.swing.JFrame {
    
    /**
     * Creates new form Main
     */
    public TaskFrame() {
        initComponents();
        this.setLocationRelativeTo(null);
        taskList t = new taskList();
       
        TableModel modelA = jtblTodayTasks.getModel();
         modelA.addTableModelListener(new TableModelListener(){
            @Override
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            if (column == 4) {
                int input = JOptionPane.showConfirmDialog(null, "Set task as completed?", "Confirm Completion", JOptionPane.YES_NO_OPTION);;
                if(input == 0){
                taskList a = new taskList();
                int ID = Integer.parseInt(modelA.getValueAt(row, 0).toString());
                boolean completed;
                Boolean checked = (Boolean) modelA.getValueAt(row, column);
                if (checked) {
                    completed = true;
                } else {
                    completed = false;
                }
                a.updateCompleted(ID, completed);
                
                }else{
                    TaskFrame.this.dispose();
                    new TaskFrame().setVisible(true);
                }
            }
        }
        });
        TableModel modelB = jtblTomTasks.getModel();
         modelB.addTableModelListener(new TableModelListener(){
            @Override
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            if (column == 4) {
                int input = JOptionPane.showConfirmDialog(null, "Set task as completed?", "Confirm Completion", JOptionPane.YES_NO_OPTION);;
                if(input == 0){
                taskList a = new taskList();
                int ID = Integer.parseInt(modelB.getValueAt(row, 0).toString());
                boolean completed;
                Boolean checked = (Boolean) modelB.getValueAt(row, column);
                if (checked) {
                    completed = true;
                } else {
                    completed = false;
                }
                a.updateCompleted(ID, completed);
                
                }else{
                    TaskFrame.this.dispose();
                    new TaskFrame().setVisible(true);
                }
            }
        }
        });
        
        jtblTodayTasks.setModel(t.filljtblTodayTasks(jtblTodayTasks));
        jtblTomTasks.setModel(t.filljtblTomTasks(jtblTomTasks));
        
        jtblTodayTasks.setAutoCreateRowSorter(true);
        jtblTomTasks.setAutoCreateRowSorter(true);
    }

    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblTodayTasks = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblTomTasks = new javax.swing.JTable();
        
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(1100, 619));
        setResizable(false);
        setSize(new java.awt.Dimension(1100, 619));
        getContentPane().setLayout(null);

        tabbedPane.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        tabbedPane.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            tabbedPaneMouseClicked(evt);
        }
        });

        jtblTodayTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        jtblTodayTasks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Task", "Subject", "Due Date", "Completed"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtblTodayTasks);
        if (jtblTodayTasks.getColumnModel().getColumnCount() > 0) {
            jtblTodayTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
        }

        tabbedPane.addTab("Due Today", jScrollPane1);

        jtblTomTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        jtblTomTasks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Task", "Subject", "Due Date", "Completed"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtblTomTasks);
        if (jtblTomTasks.getColumnModel().getColumnCount() > 0) {
            jtblTomTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
        }

        tabbedPane.addTab("Tomorrow", jScrollPane3);

        getContentPane().add(tabbedPane);
        tabbedPane.setBounds(230, 80, 530, 450);               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TaskFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jtblTodayTasks;
    private javax.swing.JTable jtblTomTasks;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

taskList class populates the tables with data from an access database. Please help me get the checkbox listener to work for both tables. Thank you!




Python Selenium input check click failed

I have following html:

<input id="!T1319457706_SPY" type="checkbox" name="!T1319457706_SPY" class="checkbox" onclick="toggleTextField(['1319457706'],this.checked,'','');" style="">

This is checkbox that I want to click,I have tried all the selector to locate it,but all failed and system have no error message,in this page I have tried to click other element,it works,expect this checkbox.

I have tried follow ways:

driver.find_element_by_id('!T1319457706_SPY').click()
driver.find_element_by_css_selector("input[name='!T1319457706_SPY']").click()
driver.find_element_by_xpath("//body[@class='grdtradeOrder']//form[@name='displayopenorders']//table[@class='t0']//tr[@name='orderid1319457706']//input[@name='!T1319457706_SPY']").click()

I also tried use:

 click_check=driver.find_element_by_id('!T1319457706_SPY')

 driver.execute_script("arguments[0].click();", click_check)

All above tries have failed.Any friend can help?




mardi 28 juillet 2020

Checking if checkbox value isset when part of an array - Codeigniter

I have a dynamic form that is populated with check boxes. I'm trying to implement a permissions / roles system for my dashboard.

the form is populated depending on what permissions are stored in the db. for this example i only have 2. this is the code for the form :

                                  if (!empty($permissions)) {
                                    foreach ($permissions as $perm) {
                                ?>
                                        <tr>
                                            <td><?php echo $perm->display_name; ?></td>
                                            <td class="text-center"><div class="checkbox checkbox-success checkbox-circle mb-2 ml-2">
                                               
                                            <input name="view[]" id="<?php echo $perm->id ?>-view" type="checkbox" value="1">
                                            <label for="<?php echo $perm->id ?>-view">&nbsp;</label>
                                        </div></td>
                                            <td class="text-center"><div class="checkbox checkbox-success checkbox-circle mb-2 ml-2">
                                           
                                            <input name="edit[]" id="<?php echo $perm->id ?>-edit" type="checkbox" value="1">
                                            <label for="<?php echo $perm->id ?>-edit">&nbsp;</label>
                                        </div></td>
                                            <td class="text-center"><div class="checkbox checkbox-success checkbox-circle mb-2 ml-2">
                                            
                                            <input name="create[]" id="<?php echo $perm->id ?>-create" type="checkbox" value="1">
                                            <label for="<?php echo $perm->id ?>-create">&nbsp;</label>
                                        </div></td>
                                            <td class="text-center"><div class="checkbox checkbox-success checkbox-circle mb-2 ml-2">
                                            
                                            <input name="delete[]" id="<?php echo $perm->id ?>-delete" type="checkbox" value="1">
                                            <label for="<?php echo $perm->id ?>-delete">&nbsp;</label>
                                        </div></td>
                                        </tr>
                                       
                                    <input type="hidden" name="permission_id[]" value="<?php echo $perm->id ?>">
                                    <input type="hidden" name="permission_name[]" value="<?php echo $perm->permission_name ?>">
                                        <?php
                                    }
                                }
                                ?>

the form works great and is displayed like this :

enter image description here

this is my controller code :

 public function setPermissions()
 {
    if ($this->isAdmin() == true) {
        $this->loadThis();
    } else {
        // GET FORM FIELD INPUTS
        
        extract($_POST);

            foreach ($permission_id as $key => $permission_id) {
                $data = array(
                    'permission_id'=> $permission_id,
                    'permission_name' => $permission_name[$key],
                    'can_view' => $view[$key],
                    'can_edit' => $edit[$key],
                    'can_create' => $create[$key],
                    'can_delete' => $delete[$key],
                    'role_id' => $roleId,
                     );
                                 

                $result = $this->settings_model->setPermissions($data);
            }
        }

        if ($result > 0) {
            $this->session->set_flashdata('success', 'Permissions set successfully');
        } else {
            $this->session->set_flashdata('error', 'Setting permissions failed');
        }

        // LOAD VIEW

        redirect('staffPermissions');
    }

and my model :

public function setPermissions($data)
 {
    $this->db->trans_start();
    $this->db->insert('app_staff_permissions', $data);       
    $this->db->trans_complete();
    
    return true;
}

i have tried the trick of putting a hidden input field above the checkbox's but this only returns a result for the last row added to the db.

The problem i having is when a check box is not checked i get an error that the variable is not declared. Presumably this is because it is returning a null value.

i have tried to check for a value like this :

                    'can_view' => ($view[$key]) == '1' ? '1' : '0',
                    'can_edit' => ($edit[$key]) == '1' ? '1' : '0',
                    'can_create' => ($create[$key]) == '1' ? '1' : '0',
                    'can_delete' => ($delete[$key]) == '1' ? '1' : '0',

but that also does not work and throws the same error. i have tried an if else statement within the array but that obviously does not work. I'm really stuck with this now and willing to try any suggestions. Is there any way to check if the value is null and if so assign a '0' to it?




VBA about dragging and multi-select checkboxes

Any Excel VBA code can process selecting or unselecting checkboxes in the dragged area by mouse and shade the area at the same time? The attached image is what I want. enter image description here




jTable boolean column shows true/false instead of checkboxes

I am creating a netbeans java project that retrieves data from a microsoft access database. I need to display an editable checkbox for one of my columns but for some reason it comes up as true/false instead. The jTable in the Design view shows checkboxes but when I run the program true/false is displayed. I really don't understand editors and renders though I have tried, a solution without this would be preferable but if it is the only way, please explain how to do it.

Here is my GUI code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;



/**
 *
 * @author Lenovo
 */
public class TaskFrame extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public TaskFrame() {
        initComponents();
        this.setLocationRelativeTo(null);
        
        taskList t = new taskList()
        jtblTodayTasks.setModel(t.filljtblTodayTasks());
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtblTodayTasks = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(1100, 619));
        setResizable(false);
        setSize(new java.awt.Dimension(1100, 619));
        getContentPane().setLayout(null);


        jtblTodayTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
        jtblTodayTasks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Task", "Subject", "Due Date", "Completed"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtblTodayTasks);
        if (jtblTodayTasks.getColumnModel().getColumnCount() > 0) {
            jtblTodayTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
        }
        

        pack();
    }// </editor-fold>                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        //</editor-fold>

        /* Create and display the form */
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TaskFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtblTodayTasks;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

Here is my taskList class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lenovo
 */
public class taskList {
    ArrayList<Task> taskArray = new ArrayList<>();
    
    public taskList(){
        ConnectDB db = new ConnectDB();
        ResultSet rs = db.getResults("SELECT * FROM tblTasks WHERE userID = " + Login.currentUserID + " ORDER BY dueDate;");
        
        try{
            while (rs.next()){
                Task task = new Task(rs.getInt("taskID"), rs.getInt("userID"), rs.getString("taskName"), rs.getString("Subject"), rs.getString("taskDetails"), rs.getString("dueDate"), rs.getBoolean("Completed"));
                taskArray.add(task);
            }
            rs.close();
        }catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Database error. Please contact the system Administrator");
        }
    }
    
    public DefaultTableModel filljtblTodayTasks(){
        
        Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        
        for (int i = 0; i < taskArray.size(); i++) {
            model.addRow(new Object[]{taskArray.get(i).getTaskID(), taskArray.get(i).getTaskName(), taskArray.get(i).getSubject(), taskArray.get(i).getDueDate(), taskArray.get(i).isCompleted()});
        }
        return model;
    }

Thank you so much!




I need to delete from the check box with PHP and codeigniter

I need to delete from the check box with PHP and codeigniter

I'm doing a foreach to return data from the database This is my view

    <div class="conteudo tabelaMovCaixa">
    <div class="col-xs-12 usuarioTitulo">
        <div class="input entrada1">
            <input type="checkbox" id="checkboxAll" onclick="selecionaTodosCheckbox()" value="Selecione">
        </div>
        <div class="conta">
            Conta
        </div>
        <div class="descricao">
            Descrição
        </div>
        <!-- <div class="centro_custo">
            Centro de Custo
        </div> -->
        <div class="data">
            Vencimento
        </div>
        <div class="tipo">
            Tipo
        </div>
        <div class="valor">
            Valor
        </div>
        <!-- <div class="actions2" id ="actions2">
            Ações
        </div> -->
    </div>
    <!-- PRIMEIRO USUÁRIO -->
                </form >
    <form action="<?php echo base_url('configuracoes/excContaPR') ?>" method = "POST">
    <?php if ($dados_caixa_filtro == null) { ?>
        <?php
        $data = date('d/m/Y');
        $data2 = date('d/m/Y', strtotime('-1 days', strtotime(date('Y-m-d'))));
        $data3 = date('d/m/Y', strtotime('-2 days', strtotime(date('Y-m-d'))));
        ?>
        <div class="col-xs-12 vencimento">
            <h5>Vencimento: <?php echo $data ?></h5>
        </div>
        <?php
        if(!empty($dados_caixa)){
        foreach ($dados_caixa as $dados) {
            $checkbox = [];
            $checkbox[] = $dados->id_contas_pagar_receber;
            foreach ($checkbox as $checkbox=>$value) {
                //echo "ID da conta : ".$value."<br />";
            }
            $checked = "checked";
    
            if (date("d/m/Y", strtotime($dados->vencimento)) == $data) {
                $urlExcluir = base_url('configuracoes/excContaPR') . "/" . $dados->id_contas_pagar_receber;
                if ($dados->tipo_pessoa == '1') {
                    echo "<div class='col-xs-12 usuario saida'>";
                } else if ($dados->tipo_pessoa == '2') {
                    echo "<div class='col-xs-12 usuario entrada'>";
                }
                echo "<div class='input entrada1'>"
                
                . "<input type='checkbox' name='checkbox[]' value='$value' id='checkbox[]' onclick=verificarCheckBox() >"
                

                . "</div>"
                . "<div class='conta'>"
                . "$dados->nome"
                . "</div>"
                . "<div class='descricao'>"
                . $dados->descricao
                . "</div>"
                /* . "<div class='centro_custo'>"
                . $dados->centro_custo
                . "</div>" */
                . "<div class='data'>";
                if ($dados->vencimento == '') {
                    echo "----------";
                } else {
                    echo date('d/m/Y', strtotime($dados->vencimento));
                }
                echo "</div>"
                . "<div class='tipo'>"
                . $dados->forma_pagamento
                . "</div>"
                . "<div class='valor'>"
                . "<span class='entrada2'>" . 'R$ ' . number_format($dados->valor, 2, ',', '.') . "</span>"
                . "</div>"
                . "<div class='actions2'>"
                . "<li><a onclick='pagar2($dados->id_contas_pagar_receber, $dados->tipo_pessoa)' title='Editar'><i class='fas fa-pencil-alt'></i></a></li>"
                . "<li><a onclick='pagar($dados->id_contas_pagar_receber, $dados->tipo_pessoa)' title='Pagar'><i class='fas fa-file-invoice-dollar'></i></a></li>"
                . "<li><a href='#' onclick = \"confirmExclusaoContaPR(" . '\'0' . $dados->id_contas_pagar_receber . '\',' . '\'' . $urlExcluir . '\'' . ");\" title='Excluir'><i class='fa fa-trash'></i></a></li>"
                . "</div>"
                . "</div>";
                
                for($i=0;$i<count(['checkbox']);$i++){
                    $id = $value;
                    //echo $value;
                    }
            }
        }
    }

<input type='submit' name='delete' value='Deletar' onclick="confirmExclusaoContaPR()"/>

Here the javascript function that selects all checkboxes

This is My JAVASCRIPT

 <script>
retorna = "";

function retornaAcoes() {
    document.getElementById("pagos").hidden = false;
    document.getElementById("actions2").hidden = false;
  
}

function verificaCheckbox(){
    
    let checkbox = document.getElementById("checkbox[]").value;
    
    
    alert(checkbox);
    
}

function selecionaTodosCheckbox(){
    var checkbox = document.getElementsByName('checkbox[]');
   
    var button = document.getElementById('checkboxAll');

    
    
    if(button.value == 'Selecione'){
        for(var i in checkbox ){
            checkbox[i].checked = 'FALSE'; 
            var checkSelecionado = document.getElementsByName('checkbox[]');
            
        }
        button.value = 'Não selecionado'
        
        
        }else{
            for(var i in checkbox){
            checkbox[i].checked = '';
        }
        button.value = 'Selecione'
    }
}

Here the controller that fetches the model registration and sends the message to the user This is MY CONTROLLER

//Excluir Conta PR.
function excContaPR($id_contas_pagar_receber) {
    if ($this->config_m->excluirContaPR($id_contas_pagar_receber)) {
        $this->gerarAlerta('home/listaMovimentacaoDeCaixa', 'Conta excluída com sucesso!');
    } else {
        $this->gerarAlerta('home/listaMovimentacaoDeCaixa', 'Erro ao excluir conta, tente novamente!');
    }
}

Here is the function that deletes from the database in the model

This is my MODEL

//Excluir dados conta na base de dados.
public function excluirContaPR($id_contas_pagar_receber) {

    $this->db->where('contas_pagar_id', $id_contas_pagar_receber);
    if ($this->db->delete('contas_pagar_pagamento')) {
    }
    

    $this->db->where('id', $id_contas_pagar_receber);
    if ($this->db->delete('contas_pagar')) {
    }

   return true;
    
}



Checkboxes not working correctly in RecyclerView

I am using a RecyclerView to display a list of activities saved in my Firebase database. I have added a checkbox to the layout of the activity view so that the user can select whether they want to add this activity to their audit profile.

When the user clicks the checkbox to select the activity, I want to add this activity to their profile (which is stored in a separate table) and update a field in the original activity table to say that it is now included in the audit profile. When they uncheck the box, it is removed from their profile and the original activity is updated to reflect this.

However, when I try doing this, my checkboxes start behaving incorrectly (such as a checkbox being checked that definitely hasn't been clicked by the user, checkboxes not staying ticked). This only happens when I have both the code to add the activity to the profile and to update the original activity.

Any ideas? I think it might be something to do with state, but I'm not sure how to go about doing this.

My code is as follows

 auditAdapter = new FirestoreRecyclerAdapter<Activity, AuditBuilder.AuditViewHolder>(auditBuilder) {
        @Override
        protected void onBindViewHolder(@NonNull final AuditBuilder.AuditViewHolder auditViewHolder, int i, @NonNull final Activity activity) {

            auditViewHolder.aAuditActivityName.setText(activity.getActivity_Name());
            auditViewHolder.aAuditActivityType.setText(activity.getActivity_Type());
            auditViewHolder.aAuditActivityDate.setText(activity.getActivity_Date());

            final String docId = auditAdapter.getSnapshots().getSnapshot(i).getId();

            auditViewHolder.auditCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){

                        //ADD DOCUMENT ID TO DATABASE
                        DocumentReference documentReference = fStore.collection("audits")
                                .document(user.getUid())
                                .collection("myAuditActivities")
                                .document(docId);


                        Map<String, Object> audit = new HashMap<>();

                        audit.put("Activity_ID", docId);
                        audit.put("Activity_Name", activity.getActivity_Name());
                        audit.put("Activity_Description", activity.getActivity_Description());
                        audit.put("Activity_Type", activity.getActivity_Type());
                        audit.put("Activity_Date", activity.getActivity_Date());
                        audit.put("Activity_Hours", activity.getActivity_Hours());
                        audit.put("Activity_Mins", activity.getActivity_Mins());
                        audit.put("Activity_Ref1", activity.getActivity_Ref1());
                        audit.put("Activity_Ref2", activity.getActivity_Ref2());
                        audit.put("Activity_Ref3", activity.getActivity_Ref3());
                        audit.put("Activity_Ref4", activity.getActivity_Ref4());
                        audit.put("Image_URL", activity.getImage_URL());
                        audit.put("In_Audit", true);

                        documentReference.set(audit).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("TAG", "Activity successfully added to audit");
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(AuditBuilder.this, "Error, try again", Toast.LENGTH_SHORT).show();
                            }
                        });


                        //UPDATE BOOLEAN IN_AUDIT IN CPD ACTIVITIES LOCATION IN DATABASE TO TRUE
                        DocumentReference updateActivity = fStore.collection("cpdActivities")
                                .document(user.getUid())
                                .collection("myCPD")
                                .document(docId);

                        Map<String, Object> updateBoolean = new HashMap<>();
                        updateBoolean.put("In_Audit", true);

                        updateActivity.update(updateBoolean).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("TAG", "In_Audit successfully updated");
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.d("TAG", "In_Audit update failed");
                            }
                        });

                    } else {
                        //CHECKBOX UNCHECKED, DELETES FROM AUDIT TABLE
                        DocumentReference docRef = fStore.collection("audits")
                                .document(user.getUid())
                                .collection("myAuditActivities")
                                .document(docId);
                        docRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("TAG", "Activity successfully removed from audit");
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(AuditBuilder.this, "Error, try again", Toast.LENGTH_SHORT).show();
                            }
                        });


                        //UPDATE BOOLEAN IN_AUDIT IN CPD ACTIVITIES LOCATION IN DATABASE BACK TO FALSE
                        DocumentReference updateActivity = fStore.collection("cpdActivities")
                                .document(user.getUid())
                                .collection("myCPD")
                                .document(docId);

                        Map<String, Object> updateBoolean = new HashMap<>();
                        updateBoolean.put("In_Audit", false);

                        updateActivity.update(updateBoolean).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("TAG", "In_Audit successfully updated");
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.d("TAG", "In_Audit update failed");
                            }
                        });


                    }
                }
            });


            auditViewHolder.view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(v.getContext(), ActivityDetails.class);
                    //DISPLAYS ALL THE ATTRIBUTES OF THE ACTIVITY
                    i.putExtra("Activity_Name", activity.getActivity_Name());
                    i.putExtra("Activity_Description", activity.getActivity_Description());
                    i.putExtra("Activity_Type", activity.getActivity_Type());
                    i.putExtra("Activity_Date", activity.getActivity_Date());
                    i.putExtra("Activity_Hours", activity.getActivity_Hours());
                    i.putExtra("Activity_Mins", activity.getActivity_Mins());
                    i.putExtra("Activity_Ref1", activity.getActivity_Ref1());
                    i.putExtra("Activity_Ref2", activity.getActivity_Ref2());
                    i.putExtra("Activity_Ref3", activity.getActivity_Ref3());
                    i.putExtra("Activity_Ref4", activity.getActivity_Ref4());
                    i.putExtra("Image_URL", activity.getImage_URL());
                    i.putExtra("Activity_ID", docId);
                    v.getContext().startActivity(i);
                }
            });



        }

        @NonNull
        @Override
        public AuditBuilder.AuditViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.auditbuilder_view_layout, parent,false);
            return new AuditViewHolder(view);
        }
    };



Angular Help: drop-down with select all selected by default

It looks like by default the dropdown loads the list but keeps the boxes unchecked. But I want to have the boxes checked by default, since they are actually loaded. Is this possible? I am using Angular Material.

<mat-form-field appearance="fill">
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppings" multiple>
    <mat-option (click)="selectAll(ev)" #ev>
        Select all
    </mat-option>
    <mat-option *ngFor="let topping of toppingList"
        [value]="topping">
            
    </mat-option>
  </mat-select>
</mat-form-field>



lundi 27 juillet 2020

How do I get rid of the diagonal offset of an HTML checkbox in CSS when placing it over another element?

I wrote a menu without JavaScript for my blog, however, the checkbox that activates the menu is for some reason slightly offset diagonally from the actual visible button elements. How do I change this (yes, I tried changing the positioning values, however, with no effect)? I'm aware there's a similar question here, however, it seems to be rather JS-based, and uses position: relative rather than position: fixed. My relevant HTML is the following:

<nav>
    <input type="checkbox">
    <div id="oButton">
        Open menu
    </div>
    <div id="cButton">
        Close menu
    </div>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="/posts">Archive</a></li>
        <li><a href="/rss.xml">RSS Feed</a></li>
        <li><a href="#">Privacy</a></li>
        <li><a href="#">Source code</a></li>
    </ul>
</nav>

and the CSS is this:

nav {
    color: Black;
    position: fixed;
    top: 1em;
    right: 1em;
    width: 6em;
    height: 1.5em;
    user-select: none;
    text-align: center;
    margin: auto;
}
nav input {
    display: block;
    opacity: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 3;
    cursor: pointer;
}
nav #oButton {
    position: absolute;
    top: 0;
    right: 0;
    width: 6em;
    height: 1.5em;
    z-index: 1;
    background: #3CE13B;
}
nav #cButton {
    position: absolute;
    top: 0;
    right: 0;
    width: 6em;
    height: 1.5em;
    z-index: 2;
    background: Orange;
    opacity: 0;
}
nav ul {
    position: absolute;
    top: 0.5em;
    right: 0;
    padding: 0.7em;
    width: 7.1em;
    background: #EEE;
    list-style-type: none;
    text-align: right;
    font-size: 0;
    opacity: 0;
    text-align: right;
    padding-top: 0.1em;
}

nav input:hover+#oButton {
    color:white;
}
nav input:hover~#cButton {
    color:white;
}

nav input:checked~#cButton {
    opacity: 1;
}
nav input:checked~ul {
    font-size: 1.5em;
    transition: opacity 0.25s linear;
    opacity: 1;
}
fantasycookie17@ChameleonBook: ~/fantasycookie17.onederfultech.com $ kak _site/static/menu.css
fantasycookie17@ChameleonBook: ~/fantasycookie17.onederfultech.com $ ./deploy.sh 
[info] Building from "/home/fantasycookie17/fantasycookie17.onederfultech.com/" into "/home/fantasycookie17/fantasycookie17.onederfultech.com/_site"
[info] Build successful
Enter passphrase for key '/home/fantasycookie17/.ssh/id_rsa': 
Successfully synced.
Enter passphrase for key '/home/fantasycookie17/.ssh/id_rsa': 
fantasycookie17@ChameleonBook: ~/fantasycookie17.onederfultech.com $ cat _site/static/menu.
cat: _site/static/menu.: No such file or directory
fantasycookie17@ChameleonBook: ~/fantasycookie17.onederfultech.com $ cat _site/static/menu.css 
nav {
    color: Black;
    position: fixed;
    top: 1em;
    right: 1em;
    width: 6em;
    height: 1.5em;
    user-select: none;
    text-align: center;
    margin: auto;
}
nav input {
    display: block;
    opacity: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 3;
    cursor: pointer;
}
nav #oButton {
    position: absolute;
    top: 0;
    right: 0;
    width: 6em;
    height: 1.5em;
    z-index: 1;
    background: #3CE13B;
}
nav #cButton {
    position: absolute;
    top: 0;
    right: 0;
    width: 6em;
    height: 1.5em;
    z-index: 2;
    background: Orange;
    opacity: 0;
}
nav ul {
    position: absolute;
    top: 0.5em;
    right: 0;
    padding: 0.7em;
    padding-top: 0.1em;
    width: 7.1em;
    background: #EEE;
    list-style-type: none;
    text-align: right;
    font-size: 0;
    opacity: 0;
    text-align: right;
}

nav input:hover+#oButton {
    color:white;
}
nav input:hover~#cButton {
    color:white;
}

nav input:checked~#cButton {
    opacity: 1;
}
nav input:checked~ul {
    font-size: 1.5em;
    transition: opacity 0.25s linear;
    opacity: 1;
}



How to prevent a function from running until the user has given input?

I am creating a quiz and I don't want the next question to appear until the user has selected an answer to the first question, by ticking one of the checkboxes. If they haven't yet selected an answer, and try to click the NEXT buttton, an alert should pop up. How would I do this using javascript? My HTML:

<div id= "Q1"> Select your answer:
<input type = "checkbox" class="a"> a <br>
<input type="checkbox" class="b"> b <br>
</div>
 <button id="nextbtn" onclick="nextClicked()">NEXT</button>
<div id= "Q2"> Select your answer:
<input type = "checkbox" class="a"> a <br>
<input type="checkbox" class="b"> b <br>
</div>

My JS:

function nextClicked() {
                var Q2 = document.getElementById("Q2")
                Q2.style.opacity = "1"

                ``



FLUTTER Checkbox UI not updating

I have of many checkboxes as You can see the image uploaded, please see the image first.

PLEASE SEE THE IMAGE FIRST AND AFTER THAT YOU CAN UNDERSTAND MY PROBLEM

Now the problem is that you can see the 3 cards views Conditions, Allergies and Past Surgeries. and all of these cards contains checkboxes and now what happens is that when I check or uncheck any box the UI of the CheckBox doesn't update to tick or untick and I have checkboxes outside the build method.

Can anyone let me know that what am I doing wrong and I will share the checkboxes codes also?

EDIT

CREATING CHECK BOXES DYNAMICALLY

List<Widget> _dynamicListWidget(List<dynamic> list) {

 List<Widget> widgetList = List<Widget>();
 for (var i = 0; i < list.length; i++) {
  Condition condition = list[i];
  widgetList.add(
    Container(
      width: _containerWidth,
      //padding: EdgeInsets.only(top: 2, bottom: 2),
      child: Row(
        children: <Widget>[
          Expanded(
              child: Container(
            margin: EdgeInsets.only(left: 10),
            child: Text(condition.name, style: _textStyle),
          )),
          //Expanded(child: Container()),
          Checkbox(
            value: condition.selected,
            onChanged: (bool value) {
              print("$value  value");
              setState(() {
                condition.selected = value;
              });
              addRemoveFavHealth(value, condition.id);
            },
          ),
        ],
      ),
    ),
  );
}
return widgetList;

}

CREATING A CARD VIEW

 Widget mainbody(String name, List<dynamic> dynamicList) {
final screenWidth = MediaQuery.of(context).size.width;
final screenheight = MediaQuery.of(context).size.height;
print("$screenWidth width of device");
List<Condition> list = List();

return Container(
  width: screenWidth * 0.49,
  child: Card(
    color: Colors.white,
    child: Column(
      children: <Widget>[
        Container(
          //width: 200,
          padding: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
          decoration: BoxDecoration(
            color: Colors.black12,
          ),
          child: Row(
            children: <Widget>[
              ClipOval(
                child: Material(
                  color: Colors.white,
                  child: SizedBox(
                    width: 40,
                    height: 40,
                    child:
                        /*Image.asset(
                                        'assets/icons/doc_icon.png'),*/
                        Icon(
                      Icons.playlist_add_check,
                      color: AppTheme.primaryColor,
                    ),
                  ),
                ),
              ),
              Flexible(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        _localization.localeString(name),
                        style: TextStyle(color: AppTheme.primaryColor),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          child: Column(
            children: _dynamicListWidget(list),
          ),
        ),
      ],
    ),
  ),
);

}

BUILD METHOD

@override
Widget build(BuildContext context) {
  _localization = AppTranslations.of(context);

  return Expanded(
    child: SingleChildScrollView(
      child: Column(
        children: _mainList,
      ),
    ) 
  );
}

In the build method, _mainList is the list of the MAINBODY METHOD.




React Native checkbox element is not working

I am using checkbox from react-native-elements. I am facing issue with checkbox checked value.

First I have to get data from database. I am getting preference array with two key and values such as:

  1. name
  2. Key

for an instance: {name:'Events', selected:'true'}

Now, I am retrieving name value from database and setting that name for my checkbox, it is working fine. I am having issue with checkbox checked button.

Here is my checkbox :

 <CheckBox
 key={index}
 name={x.name}
checked={this.state.checked}
checkedIcon={<Image source={require('../../assets/icons/checkmark.png')} style= />}
uncheckedIcon={<Image source={require('../../assets/icons/check-box.png')} style= />}
onPress={() => this.toggleCheckbox(x.name)}/>

Here is my toggleCheckbox method:

toggleCheckbox(name) {

    console.log("NAME===", name);

    const changeCheckbox = this.state.filterCategoryName.find((cb) => cb.name === name);
    changeCheckbox.selected = !changeCheckbox.selected;

    if (changeCheckbox.selected) {
        console.log("Checked  if ====", changeCheckbox.selected);
        this.setState({ checked: changeCheckbox.selected })
        console.log("State updating during true====", this.state.checked);
    }
    else {
        console.log("Checked else ====", changeCheckbox.selected);
        this.setState({ checked: changeCheckbox.selected })
        console.log("State updating during false===", this.state.checked);
    }

    const checkboxes = Object.assign({}, this.state.filterCategoryName, changeCheckbox);
    this.setState({ checkboxes });

}

When I select one checkbox at that time it will select all checkbox instead of single and when I uncheck single checkbox it will uncheck all checkbox.

I am not getting id from database only getting name and selected value so I used name in togglecheckmethod.




dimanche 26 juillet 2020

How to bind two things to IsChecked property of checkbox?

Ok, so I have a datagrid with a checkbox in a DataGridTemplateColumn since I would like to do a single-click check. I also have a "select all" checkbox at the top. (I disabled the header because I wanted to make a custom one). My datagrid is programmatically populated. and I'm using the mahApps nuget package (if that means anything).

What I want to do is bind the "Select All" status to the IsChecked property on my populated checkboxes but also be able to click the row to check the checkbox. But to be able to do that, I need to add: IsChecked="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=IsSelected, Mode=OneWay}".

I have both of them, and they both work, but I can only seem to use one at a time. How would I go about doing both? Please let me know if you need more info

Edit: I would also need multi-selection!




Limit number of javascript automated generated checkbox

kinda worried with following code that should automatically generate checkbox content AND limit up to 3 the number of checked boxes.

Separately both codes work fine, the issue occurs when they are combined:

    <form name="competencies" action="algo.php" method="POST">
    <div class="container">
        <ul class="ks-cboxtags"  id="skillsContainer">
        <input class="button" type="submit" value="Valider">
        </ul>
    </div>
   </form>

        <script type="text/javascript">
        $('input[type=checkbox]').change(function(e){
        if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        }
        });



        var skills = [<?php echo '"'.implode('","',  $miss).'"' ?>];
        var skillContainer = $("#skillsContainer");
        skills.forEach(skill => skillContainer.append('<li> <input type=\"checkbox\" id=\"'+ skill +'\" value=\"'+ skill +'\"> <label for=\"'+ skill +'\"> '+ skill +' </label> </li>'));

        console.log(skillContainer);
        $("#skillsContainer").append(checkboxElement);
    </script>

jsfiddle = here

any idea ?