dimanche 30 juin 2019

Why can I not use checkboxes when using tkinter?

I am trying to grab a list from a website, assign each option to a checkbox, and allow the user to select an option. When i run the code however, the window pops up, but I am unable to select an option. When i try to check the box, it does not allow me to.

Here is the portion of my code that is causing issues.

            select_element = Select(driver.find_element_by_css_selector("#songID"))
            select_song.config(background="deep sky blue")
            select_song.title('Select Song')
            song_label = Label(select_song, text="Please select the song you would like to promote")
            song_label.config(background="deep sky blue", foreground="white")
            song_label.grid(row=0)
            rowId = 1
            var = IntVar()
            songList = [o.text for o in select_element.options]
            optionList=[]

            for song in songList:
                check = Checkbutton(select_song, text=song, variable=var, bg="deep sky blue", fg="white").grid(row=rowId)

                rowId = rowId + 1
            select_song.mainloop()
            optionList.append([song,var])

I haven't had this issue before and I'm not sure what is causing it.

Here is my full code:

from Tkinter import *
from PIL import ImageTk,Image
import time
from datetime import tzinfo
from selenium.webdriver.support.ui import Select


def main():

    chromedriver = "C:\Users\Alex\Desktop\chromedriver"
    driver = webdriver.Chrome(chromedriver)
    driver.get("https://www.soundclick.com/community/SC4/login.cfm")

    def songOptions():
        print (song,var.get())


    def start():
        my_window.mainloop()

    def prepare():
        email = email_text.get()
        password = pass_text.get()
        my_window.destroy()
        xpathEmail = '//*[@id="email"]'
        loginEmail = driver.find_element_by_xpath(xpathEmail)
        loginEmail.send_keys(email)
        xpathPass = '//*[@id="password"]'
        loginPass = driver.find_element_by_xpath(xpathPass)
        loginPass.send_keys(password)
        xpathLogin = '//*[@id="loginform"]/div[3]/div[2]/input'
        login = driver.find_element_by_xpath(xpathLogin)
        login.click()
        time.sleep(2)

        if driver.current_url == "https://www.soundclick.com/bandAdmin2/default.cfm?ipv=0":
            xpathEdit = '//*[@id="mySCTab_content"]/div/div[2]/div[2]/a[1]'
            edit = driver.find_element_by_xpath(xpathEdit)
            edit.click()
            time.sleep(2)

            xpathClose = '/html/body/div[9]/div/div/a'
            close = driver.find_element_by_xpath(xpathClose)
            close.click()
            time.sleep(2)

            xpathPromote = '//*[@id="mySCTab"]/li[6]/a'
            promote = driver.find_element_by_xpath(xpathPromote)
            promote.click()

            xpathSOD = '//*[@id="mySCTab_content"]/ul/li[3]/a'
            SOD = driver.find_element_by_xpath(xpathSOD)
            SOD.click()


            select_song=Tk()
            select_element = Select(driver.find_element_by_css_selector("#songID"))
            select_song.config(background="deep sky blue")
            select_song.title('Select Song')
            song_label = Label(select_song, text="Please select the song you would like to promote")
            song_label.config(background="deep sky blue", foreground="white")
            song_label.grid(row=0)
            rowId = 1
            var = IntVar()
            songList = [o.text for o in select_element.options]
            optionList=[]

            for song in songList:
                check = Checkbutton(select_song, text=song, variable=var, bg="deep sky blue", fg="white").grid(row=rowId)

                rowId = rowId + 1
            select_song.mainloop()
            optionList.append([song,var])


        elif driver.current_url == "https://www.soundclick.com/community/SC4/loginRegAuth.cfm":
            driver.close()
            main()



    my_window=Tk()

    my_window.title('SoundClick Login')

    my_window.configure(background="deep sky blue")

    email_label=Label(my_window, text="Please Enter The Email Used To Sign Into SoundClick")
    email_label.config(background="deep sky blue", foreground="white")

    email_text = Entry(my_window)
    email_text.pack()
    pass_label=Label(my_window, text="Please Enter The Password Used To Sign Into SoundClick")
    pass_label.config(background="deep sky blue", foreground="white")
    pass_text=Entry(my_window)
    pass_text.pack()



    pass_text.config(show="*")
    song_text = Entry(my_window)
    song_label=Label(my_window, text="Please Enter The Name Of The Song You Want To Promote. Warning:cAsE SensItIvE")
    song_label.config(background="deep sky blue", foreground="white")

    finish_button = Button(my_window, text="Done",command=prepare)
    finish_button.config(background="white")
    note_label=Label(my_window, text="This information will not be stored anywhere")
    note_label.config(background="deep sky blue", foreground="white")


    email_label.grid(row=0, column=0)
    email_text.grid(row=0, column=1)
    pass_label.grid(row=1, column=0)
    pass_text.grid(row=1, column=1)
    finish_button.grid(row=3, column=0)

    start()
main()




samedi 29 juin 2019

(HTML & CSS) How to hide checkbox while still being able to check image

I've been creating a checkbox that has a custom background image. I want to hide the checkbox, but whenever I do I am unable to check it.

HTML:

<div class="arrow">
  <label for="togglearrow"></label>
  <input type='checkbox' id="togglearrow"/>
  <div class="arrowmenu"></div>
</div>

CSS:

#togglearrow {
  display: none;
  cursor: pointer;
}

.arrow {
  position: absolute;
  display: block;
  background: url('arrow.png') no-repeat;
  background-size: 65%;
  height: 35px;
  bottom: 0;
}

.arrowmenu {
  position: absolute;
  background: url('test.png') no-repeat;
  background-size: 65%;
  height: 35px;
  bottom: 0;
  right: 20px;
}

label[for="togglearrow"] {
      display: block;
      cursor: pointer;
}
#togglearrow:checked + .arrowmenu {
      display: block;
      bottom: 0;
      left: 50px;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
}

I expect that the checkbox will be hidden and can still click on "tasks.png" to check the box, however, it results in the checkbox not being able to be checked.




How can I change R-Shiny "checkboxinput" value to FALSE/TRUE programmatically?

I want to change the checkboxinput value to FALSE/TRUE during run-time. How can I do this?

checkboxInput(inputId = "smoother", label = "Overlay smooth trend line", value = FALSE)




Draw multiple plots based on user checkbox selection in R Shiny

I have created an R shiny app, which asks user to enter certain values and select checkbox. I want o plot graphs based on checkbox. Plot get changes when checkbox is selected by user but I want to plot multiple graphs based on user selection checkbox. Right now I am getting only one checkboxGroupInput(I have gone through the following urls Multiple plots according to checkboxGroupInput , Combining R shiny checkboxGroupInput with other input selections but none seems to be working in my case. It might be a case that I am doing something wrong)

library(shiny)
library(rjson)
library(dplyr)
library(plotly)
library(DT)
require(gridExtra)
require(ggplot2)
l='[{"a": "abc", "date": "20190506","model": "honda", "features":"weather", "value": "10"},
{"a": "abc", "date": "20190506","model": "honda", "features":"bad", "value": "14"},
{"a": "abc", "date": "20190506","model": "honda", "features":"failure", "value": "20"},
{"a": "abc", "date": "20190506","model": "honda", "features":"not", "value": "1"},
{"a": "abc", "date": "20190506","model": "honda", "features":"search", "value": "24"},
{"a": "abc", "date": "20190506","model": "honda", "features":"esrs", "value": "2"},
{"a": "abc", "date": "20190506","model": "honda", "features":"issue", "value": "1"},
{"a": "abc", "date": "20190506","model": "honda", "features":"errors", "value": "30"},

{"a": "abc", "date": "20190510","model": "ford", "features":"ice", "value": "12"},
{"a": "xyz", "date": "20190509", "model": "honda", "features":"summer", "value":"18"},
{"a": "xyz", "date": "20190507", "model": "ford", "features":"hot", "value":"14"},

{"a": "abc", "date": "20190506","model": "ford", "features":"search", "value": "20"},
{"a": "abc", "date": "20190510","model": "honda", "features":"400", "value": "18"},
{"a": "xyz", "date": "20190509", "model": "ford", "features":"fail", "value":"24"},
{"a": "xyz", "date": "20190507", "model": "honda", "features":"200", "value":"15"}]'
l = fromJSON(l)
df = data.frame(do.call(rbind, l))

ui <- # Use a fluid Bootstrap layout
  fluidPage(

    # Give the page a title
    titlePanel("Top Terms by System"),

    # Generate a row with a sidebar

        selectInput("serialNumber", "Serial Number:",
                    choices=df$a),

        selectInput("date", "Date:",
                    choices=NULL),

        # checkboxGroupInput("plots", "draw plots:", 
        #                    choices=list("ford", "honda")),
    mainPanel(
    uiOutput("checkbox"),

    plotlyOutput("plot")
    # plotOutput("plot_list")
    )

    )

  # server

server <- # Define a server for the Shiny app
    function(input, output, session) {


      observe({
        print(input$serialNumber)
        # x = df %>% filter(date == input$date) %>% select(a)
        x = df %>% filter(a == input$serialNumber) %>% select(date)
        updateSelectInput(session, "date", "date", choices = x)
      })

      observe({
        # print(input$serialNumber)
        logselected = df$model[df$date == input$date]
        updateSelectInput(session, "models", "model", choices = logselected)
      })

      output$data = renderTable({
        selectedVal = subset(df, (df$a == input$serialNumber & df$date == input$date & df$model==input$models))


      })

      output$checkbox <- renderUI({
        choice <-  unique(df[df$a %in% input$serialNumber, "model"])
        print(choice)
        checkboxGroupInput("checkbox","Select model", choices = choice)

      })

      filtered_data <- reactive({
        req(input$serialNumber)
        req(input$date)
        req(input$checkbox)

        data = df[df$a==input$serialNumber & df$date == input$date& df$model==input$checkbox,]
        print(data)
      })

      # output$table=renderDataTable({
      #   filtered_data()
      # })
      output$plot <- renderPlotly({

        plot_ly(
          filtered_data(),
          y = ~features,
          x = ~value,
          width = 0.1,
          orientation='h',
          type = "bar"
        )
      })
      # output$plot <- renderPlotly({
      #   # selectedVal = subset(df, (df$a == input$serialNumber & df$date == input$date & df$model==input$models))
      #   data <-  df %>% filter(a %in% input$serialNumber)  %>% filter(date %in% input$date) %>% filter(model %in% input$checkbox)
      #   # df[input$serialNumber, input$date, input$models]
      #   plot_ly(
      #     y = data$features,
      #     x = data$value,
      #     width = 0.1,
      #     orientation='h',
      #     type = "bar"
      #   )
      # })

    }

shinyApp(ui = ui, server = server)




jQuery Datatables: Add checkbox to column-visibility dropdown items?

I am using a basic column visibility button to create a dropdown list where the user can show/hide desired columns.

The above example uses different colored backgrounds to show whether a dropdown item has been enabled.

Is it possible to also add a checkbox to the left of the item text to further reflect the enabled state?

Like this:

enter image description here

The above screenshot is from this webpage, but it appears that the supplied code no longer works with the current version of DataTables.




vendredi 28 juin 2019

Google Sheets Query using Checkbox as search criteria

I want to use a query in Google Sheets that lets me look at a column of checkboxes to filter on ones that are checked (TRUE).

QUERY(Available!$A$3:$O, "select A,B,C,D,E,F,G,H,I,J,K,L,M,N,O where O = '"& TEXT(TRUE) &"' and B > 100,000 order by B desc")

It is complaining of a literal value, but I am having a lot of trouble figuring out the proper syntax to ensure the query is reading the checkbox properly.




How to display checked checkbox from database in php?

I want to display checked checkbox which are stored as values in a mysql database.

For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.

Here's the code for inserting the data.

$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
 ?>

<form id="addReport" action ='./functions/report-functions.php' method="post">

<table id="table1" class="table table-hover">

    <thead>
    <?php
    echo '<tr><th>Goals</th>';
    for ($i = 0; $i < count($course); $i++) {
        echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';            
    }
    echo '</tr>';   
    ?>
    </thead>
        <tbody>

    <?php
    for ($y = 0; $y < count($goals); $y++) {           
        echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>

        </tr>';           
   ?>

    <?php
    for( $z = 0; $z < count($mainobj); $z++){
  if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
        echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>

    </tr>';
     ?>

    <?php

    for ($j = 0; $j< count($subobj); $j++) {
       if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
       echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';

   for ($x = 0; $x < count($course); $x++) {
      echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
        }
        echo '</tr>';
    }
   }
  }
 }
}       
    ?>       
        </tbody>       
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>

</form>

report-functions.php

if( isset( $_POST['submit'], $_POST['check'] ) ){
    try{
      require_once 'db-connect.php';
        $conn = DatabaseConnection::getConnection();
       $sql= " insert into `Report`  (`ColRow`) values (:value) ";
        $stmt = $conn->prepare( $sql );
       if( $stmt ){
         $conn->beginTransaction();
           foreach( $_POST['check'] as $index => $value ) {
               $result = $stmt->execute( [ ':value' => $value ] );
                if( !$result ) {
                   echo '
        <script>
           alert("Error, please try submitting again. Error code 1");
           window.history.back();
        </script>';
                }
            }
            $conn->commit();
          echo '<script>
            alert("Report was submitted successfully.");
            window.location = "http://socrates.njms.rutgers.edu/";
        </script>';
      }
    } catch( Exception $e ){
       $conn->rollback();
        exit( $e->getMessage() );
    }

I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.

Please comment if I need to provide any additional information.




SetState() called in constructor

I've build a Custemized List. Now I include a Checkbox and if I would checked or unchecked , the following error was thrown: 'setState() called in constructor'

class Lists extends StatefulWidget{  
     @override
    _List createState() => _List();
}

class _List extends State<Lists> {  
  bool checkedvalue = true;
  @override
Widget build(BuildContext context) {

 return futureBuilder();
}

Widget futureBuilder(){  
  var futureBuilder = new FutureBuilder(
      future: rest.fetchPost(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return new Text('loading...');
          default:
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            else                    
                return listBuilder(context, snapshot);            
        }
      }
 );

 return new Scaffold(         
      body: futureBuilder,
    );
}

Widget listBuilder(BuildContext context, AsyncSnapshot snapshot) {  
  List<rest.Status> values = snapshot.data;

  if (values == null || values.length == 0){
    return null;
  }


  int items = values.length;

  return ListView.builder(   
  itemCount: items,
  itemBuilder: (BuildContext context, int index) {
    String statusText;
    Image image ;
    Uint8List bytes;

    if(statusList.globalStatus != null){
      for(int i=0;i< statusList.globalStatus.length; i++){
        if(values[index].statusID == statusList.globalStatus[i].id){

            if(statusList.globalStatus[i].kurzform != null){
              statusText = statusList.globalStatus[i].kurzform;
            }else{
              statusText = statusList.globalStatus[i].kurzform;
            }

            if (statusList.globalStatus[i].icon != null){
              bytes = base64Decode(statusList.globalStatus[i].icon);
              image = new Image.memory(bytes) ;
            } 
        }

        if(image== null || statusText == null){            
          statusText= 'Kein Status';
          image=  new Image.asset('assets/null.png');
        }              
      }
    }   
    return new Container( 
      decoration: new BoxDecoration(
          border: Border(top: BorderSide(
          color: Colors.black26,
          width: 1
          )
        )
      ), 


      child:Column(
        children: <Widget>[
          CustomListItemTwo( 
            statusText: statusText,                               
            status:image,
            materialNR: values[index].uArtText,          
            material: values[index].untersuchungsMaterialName,
            probenArt:  values[index].probenart,
            eingansdatum: values[index].eingangsdatumText,
            patient: values[index].vorname + ' ' + values[index].nachname ,
            geburtsdatum: values[index].geburtstagText ,

          ),
          Checkbox(            
              value: checkedvalue ,           
              onChanged: (bool newValue) =>                
                setState(() {
                  checkedvalue = newValue; 
                })              
            ),
        ] 
      ),
    );
  }       
  );
}

}

I/flutter ( 5067): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter ( 5067): The following assertion was thrown while handling a gesture: I/flutter ( 5067): setState() called in constructor: _List#9044e(lifecycle state: created, no widget, not mounted) I/flutter ( 5067): This happens when you call setState() on a State object for a widget that hasn't been inserted into I/flutter ( 5067): the widget tree yet. It is not necessary to call setState() in the constructor, since the state is I/flutter ( 5067): already assumed to be dirty when it is initially created.




jeudi 27 juin 2019

Checkbox value is not changing in reactive forms angular

i m generating form from json file with help of reactive forms.Generation of form works properly but the problem i m facing is - when i click on checkbox for first time in mozila its value becomes "on". but when i uncheck it nothing is happening its value remains "On" which should be "off or false". In chrome on click nothing is happening.

app.components.ts

import { Component } from '@angular/core';
import { QuestionControlService } from './question-control.service';
import GxData from './gx.json';
@Component({
  selector: 'app-root',
  template: `
    <div>
      <app-dynamic-form [questions]="questions"></app-dynamic-form>
    </div>
  `,
  providers: []
})
export class AppComponent{

  questions: any[];
  constructor() {
    this.questions = GxData;
  }

} 

dynamic-form.components.ts

import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionControlService } from '../question-control.service';
import SbbData from '../sbb.json';
import GxData from '../gx.json';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: any[] = [];
  form: FormGroup;
  payLoad = '';

  constructor(private qcs: QuestionControlService) { }

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
  }
  callGx() {
    this.questions = GxData;
    this.form = this.qcs.toFormGroup(this.questions);
  }
  callSbb() {
    this.questions = SbbData;
    this.form = this.qcs.toFormGroup(this.questions);
  }

  onSubmit() {

    this.payLoad = JSON.stringify(this.form.value);
    console.log(JSON.parse(this.payLoad));
  }

}

dynamic-form.component.html

<div class="search_box">
  <form (ngSubmit)="onSubmit()" [formGroup]="form">
      <button type="button" (click)="callSbb()">SBB</button> 
      <button type="button" (click)="callGx()">GX</button> 
    <div *ngFor="let question of questions" class="form-row">
      <app-question [question]="question" [form]="form"></app-question>
    </div>

    <div class="form-row">
      <button type="submit" [disabled]="!form.valid">Save</button>
    </div>
  </form>

  <div *ngIf="payLoad" class="form-row">
    <strong>Saved the following values</strong><br>
  </div>
</div>
 

question-control.service.ts

import { Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: any[]) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
        : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}

dynamic-form-question.component.ts

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

// import { QuestionBase } from '../question-base';

@Component({
  selector: 'app-question',
  templateUrl: './dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
  @Input() question: any;
  @Input() form: FormGroup;
  get isValid() { return this.form.controls[this.question.key].valid; }
}

dynamic-form-question.component.html

<div [formGroup]="form">


  <div [ngSwitch]="question.controlType" class="checkbox_wrapper">

    <input *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type" name="">
    <label [attr.for]="question.key"></label>

    <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key" name = "" >
      <option *ngFor="let opt of question.options" [attr.value]="opt.key" [selected]="opt.select"></option>
    </select>
  </div>
  <div class="errorMessage" *ngIf="!isValid"> is required</div>
</div> 

both json-files look like

[
    {
        "key": "Context",
        "label": "Context",
        "required": false,
        "order": 1,
        "controlType": "textbox",
        "name": "Context",
        "type": "checkbox"
    },
    {
        "key": "contextopt",
        "label": "",
        "required": false,
        "order": 2,
        "controlType": "dropdown",
        "name": "contextopt",
        "options": [
            {
                "key": "All Context",
                "value": "All Context",
                "select": true
            },
            {
                "key": "aaa",
                "value": "aaa"
            },
            {
                "key": "bb",
                "value": "bb"
            },
            {
                "key": "Other",
                "value": "Other"
            }
        ]
    },
    {
        "key": "Movement",
        "label": "Movement",
        "required": false,
        "order": 3,
        "controlType": "textbox",
        "name": "Movement",
        "type": "checkbox"
    }
]




VBA: How to filter through a sheet based on a checkbox?

I'm new to VBA and I'm trying to set up a customizable sheet that allows the user to filter certain columns based on the checkboxes that I have set up. So far, I understand how checkboxes work and how I can integrate them into the code, but I think I have an issue with the autofilter function. Specifically, I think that I'm putting the wrong value for Criteria1.

I've been looking around for similar coding problems, but none of them seem to work with what I'm trying to do.

Sub Auto_filter()

'variables are for checkboxes'
    Dim VC1500 As Shape 
    Dim VC7500 As Shape
    Dim VC144024 As Shape

'initiates to check for the checkboxes'
   Set VC1500 = Sheets("Sheet7").Shapes("Check Box 4")
   Set VC7500 = Sheets("Sheet7").Shapes("Check Box 5")
   Set VC144024 = Sheets("Sheet7").Shapes("Check Box 6")

'if statement that will add a string to strCriteria if checkbox is true'
    If VC1500.OLEFormat.Object.Value = 1 Then
       strCriteria = strCriteria & ", VC1500"
    End If

    If VC7500.OLEFormat.Object.Value = 1 Then
       strCriteria = strCriteria & ", VC7500"
    End If

    If VC144024.OLEFormat.Object.Value = 1 Then
       strCriteria = strCriteria & ", 144024"
    End If

'with statement that finds for column vendor then filter it based on 
strCriteria, I think this is where my issue is'

    With Worksheets("Open Purchase Orders")
        With .Range("A1", .Cells(1, Columns.Count).End(xlToLeft))
            Set vendorfind = .Rows(1).Find("Vendor")
            If Not vendorfind Is Nothing Then
                .AutoFilter Field:=vendorfind.Column, 
           Criteria1:=Split(strCriteria, ", "), Operator:=xlFilterValues
            End If
        End With
         .AutoFilterMode = False
   End With

End Sub

I expect to have the sheet filtered based on the checkboxes. I get a runtime error 9 error:subscript out of range




How to save multiple checkboxes

I have this td inside table tag with form method post:

<td><input  type="checkbox" class="isProper" name="is_proper[]" value="V"   /></td>
 <td><input  type="checkbox" class="notProper" name="is_proper[]" value="X" /></td>

User can checked only one checkbox per row, and I want to save checked value - "V" / "X".

In controller I have:

    public function update(Request $request)
    {
        $oper_id = $request->oper_id;
        $comment = $request->comment;
        $rescoring = $request->rescoring;
        $isproper = $request->is_proper;

        foreach($oper_id as $key => $value){
            $finalcontrol = Finalcontrol::find($value);
            $finalcontrol->comment = $comment[$key];
            $finalcontrol->rescoring = $rescoring[$key];
            $finalcontrol->isproper = $isproper[$key];
            $finalcontrol->save();
            
            return redirect()->back()->with('success','Saved');        
    }

The thing is that controller save only the first row records to DB The problem started when I added this two of checkbox tag, before that all the records of all rows was saved corectly . Someone can please tell me what I am doing wrong about the checkboxes?




Checkbox does not for each row

I have a list of 1624 items you can choose with a checkbox, but in the form, it can detect 'on' only for the 622 first items. If rows are checked below it does not return 'on'.

I display a list of pieces from a database, you can choose pieces thanks to a checkbox and then the database is uptaded. It works for all the items at the top of the list but starting from a row, if the box is checked, it is not detected in the php form. Whatever the order of the piece is, it works only for the 622 first items. I do not understand where is the issue since, I think, it does not come from the variables. I wonder if it is a problem of time execution, or, if by default, it stops looking from a certain row.

I have all ready verified if the algorithm check each line and it does and if all variables are good.

  $cpt = 1;
  $id_asm = (isset($_GET['id'])) ? $_GET['id'] : "";
  $SQLQuery2="(select * FROM pieces";
  $SQLResult2 = mysqli_query($MySqliConn, $SQLQuery2);
  $_html_tbStock .= '<tr>';
  // [...other information for the list...]

  while ($row2 = mysqli_fetch_array($SQLResult2, MYSQLI_ASSOC)) {            
      $idpiece = $row2['ID_PIECE'];
      $SQLQuery4 = "SELECT * from parametrage_envoi_stock where ID_ASM = '". $id_asm . "' AND ID_PIECE ='". $idpiece ."'";
      $SQLResult4 = mysqli_query($MySqliConn, $SQLQuery4);
      $row4 = mysqli_fetch_array($SQLResult4, MYSQLI_ASSOC);
      $pointee = ($row4['COCHE'] != 0) ? 'checked="checked"' : ''
      //if the piece was checked before, it is checked by default in the display, else it is not

      $_html_tbStock .= '<td><input id="parametrage_' . $cpt . '" name="parametrage_' . $cpt . '" type="checkbox" ' . $pointee . '/></td>';
      $_html_tbStock .= '</tr>';
    $cpt++;

    }

In the form we got this :

 $totalpiece = 1624
 $cpt = 1;
 while ($cpt <= $totalpiece) {
   if (isset($_POST['parametrage_' . $cpt])) {
        $ref = $_POST['ref_' . $cpt];
        $rev = $_POST['rev_' . $cpt];
        $nom = $_POST['nom_' . $cpt];
        var_dump($ref);
        var_dump($rev);
        var_dump($nom);

        $SQLQuery2 = "SELECT * FROM pieces WHERE REF_PIECE LIKE '%". $ref ."%' AND REV_PIECE LIKE '%". $rev ."%' AND NOM_PIECE LIKE '%". $nom ."%'";
        $SQLResult2 = mysqli_query($MySqliConn, $SQLQuery2) or die('Erreur2<br />' . mysqli_error($MySqliConn));
        $cnt = 1;
        while ($row2 = mysqli_fetch_array($SQLResult2, MYSQLI_ASSOC)) {
            $id_piece = $row2['ID_PIECE'];
            $SQLQuery2 = "INSERT INTO parametrage_envoi_stock (ID_ASM, ID_PIECE,COCHE) VALUES ('$idasm','$id_piece','1')";
            mysqli_query($MySqliConn, $SQLQuery2) or die('Erreur 1<br />' . mysqli_error($MySqliConn));
            var_dump($SQLQuery2);
            $cnt++;
        }
     }

    }

The list with all items and checkboxes is displayed. We can click on all the chekboxes we want.




Listview items with checkbox checked at start

I have a fragment with a listView.

The view is populated from a remote received JSON array as follows:

private void callVolley(){



        SharedPreferences prefs3 =
                getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);

        final String id_materia= "42";
        final String num_examen= "787878";
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Cargando temas de la materia seleccionada...");
        showDialog();


        JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                hideDialog();




                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject obj = response.getJSONObject(i);

                        Data item = new Data();

                        item.setMenu(obj.getString(TAG_NOMBRE));
                        item.setId(obj.getString(TAG_ID));


                        itemList.add(item);



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                // list.invalidateViews();
                adapter.notifyDataSetChanged();



            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideDialog();
            }
        });


        AppController.getInstance().addToRequestQueue(jArr);
    }

Then I add programmatically a checkbox to each list item. This is the adapter:

 public class Adapter extends BaseAdapter {

    private Context activity;
    private ArrayList<Data> data;
    private static LayoutInflater inflater = null;
    private View vi;
    private ViewHolder viewHolder;

    public Adapter(Context context, ArrayList<Data> items) {
        this.activity = context;
        this.data = items;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        vi = view;
        final int pos = position;
        Data items = data.get(pos);

        if(view == null) {
            vi = inflater.inflate(R.layout.list_row, null);
            viewHolder = new ViewHolder();
            viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
            viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
            vi.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();

        }
        viewHolder.menu.setText(items.getMenu());
        if(items.isCheckbox()){
            viewHolder.checkBox.setChecked(true);
        } else {
            viewHolder.checkBox.setChecked(false);
        }

        return vi;
    }

    public ArrayList<Data> getAllData(){
        return data;
    }

    public void setCheckBox(int position){
        Data items = data.get(position);
        items.setCheckbox(!items.isCheckbox());
        notifyDataSetChanged();
    }

    public class ViewHolder{
        TextView menu;
        CheckBox checkBox;
    }
}

At start I need all checkboxes to be checked.

Then the user can check/uncheck the desired items.

On the fragment there is a button that reads all items checkbox states.

What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?

This is a screenshot at start with all items unchecked: enter image description here




Stay checkboxes state when app restart/ reload

I'm creating my own app. The goal is to have a list of products with 3 checkboxes for each one. 1 checkbox : " I have " 1 checbox : "I want" and 1 for " I want to exchange".

But click function is OK but when I restart the app, I didn't have my checkboxes completed. They are all false.

I stock in my Firebase the state of the chechbox in "possede" of each user. see picture)

Can you help me please. I tried lots of things but nothing works

@Override
protected void onStart() {
    super.onStart();
    FirebaseRecyclerOptions<Products> options =
            new FirebaseRecyclerOptions.Builder<Products>()
                    .setQuery( ProductsRef, Products.class )
                    .build();

    FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
            new FirebaseRecyclerAdapter<Products, ProductViewHolder>( options ) {
                @Override
                protected void onBindViewHolder(@NonNull final ProductViewHolder holder, int position, @NonNull final Products model) {

                    holder.txtProductName.setText( model.getTitle() );
                    possedeCheckbox = (CheckBox) holder.itemView.findViewById( R.id.pin_posseder_checkbox );
                    echangeCheckbox = (CheckBox) holder.itemView.findViewById( R.id.pin_echanger_checkbox );
                    desireCheckbox = (CheckBox) holder.itemView.findViewById( R.id.pin_desirer_checkbox );

                    DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child( "Users" );
                    UserRef.child( Prevalent.currentOnlineUser.getPseudo() ).child( "possede" );
                    ValueEventListener valueEventListener = new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            ArrayList<String> possedePins = new ArrayList<String>(  );
                            for (DataSnapshot ds : dataSnapshot.child(Prevalent.currentOnlineUser.getPseudo()).child( "possede" ).getChildren()) {
                                String name = ds.getKey();
                                possedePins.add( name );
                            }
                            System.out.println(model.getTitle());
                            if(possedePins.contains( model.getTitle() )){
                                possedeCheckbox.setChecked( true );
                                System.out.println("YEEESSSSS");
                            } else {
                                System.out.println("NOOOOOOOO");
                            };
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                        }
                    };

                    UserRef.addValueEventListener( valueEventListener );



                    // initialiser les Checkbox
                    Picasso.get().load( model.getImage() ).into( holder.imageView );

                    possedeCheckbox.setOnLongClickListener( new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            Toast.makeText(getApplicationContext(),"clique si tu possède ce pin", Toast.LENGTH_SHORT).show();
                            return false;
                        }
                    } );
                    holder.itemView.findViewById( R.id.pin_posseder_checkbox ).setOnClickListener( new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // quand je deselectionne
                            if (possedeCheckbox.isChecked()) {
                                possedeCheckbox.setChecked( false );
                                AddPosedePins(model.getTitle(), "remove");
                                Toast.makeText( HomeActivity.this, "possede pas", Toast.LENGTH_SHORT ).show();
                            } else {
                                // quand je selectionne
                                possedeCheckbox.setChecked( true );
                                AddPosedePins(model.getTitle(), "add");
                                Toast.makeText( HomeActivity.this, "possede ", Toast.LENGTH_SHORT ).show();
                            }
                        }
                    } );
                    holder.itemView.findViewById( R.id.pin_echanger_checkbox ).setOnClickListener( new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (echangeCheckbox.isChecked()) {
                                possedeCheckbox.setChecked( false );
                                Toast.makeText( HomeActivity.this, "echange pas", Toast.LENGTH_SHORT ).show();
                            } else {
                                possedeCheckbox.setChecked( true );
                                Toast.makeText( HomeActivity.this, "echange", Toast.LENGTH_SHORT ).show();
                            }
                        }
                    } );
                    holder.itemView.findViewById( R.id.pin_desirer_checkbox ).setOnClickListener( new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (desireCheckbox.isChecked()) {
                                possedeCheckbox.setChecked( false );
                                Toast.makeText( HomeActivity.this, "desire pas", Toast.LENGTH_SHORT ).show();
                            } else {
                                possedeCheckbox.setChecked( true );
                                Toast.makeText( HomeActivity.this, "desire ", Toast.LENGTH_SHORT ).show();
                            }
                        }
                    } );
                }

                @NonNull
                @Override
                public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from( parent.getContext() ).inflate( R.layout.product_items_layout, parent, false );
                    final ProductViewHolder holder = new ProductViewHolder(view);
                    return holder;
                }
            };
    recyclerView.setAdapter( adapter );
    adapter.startListening();

}

Image of 1 product with its checkboxes image of my database here




Is there a way to get multiple checkbox value and put it in database table?

I'm trying to get variables values, surname and name, that are inside a table in the same row and there is a check box near of that row and if checked shoaled get both the information but differently so I can put them in a database table

I've tried something with php but I'm not getting out of it

I create the table in this way.

<?php
    include 'db_connect.php';
    $sql="SELECT nome, cognome FROM informazioni";
    if ($result = $db->query($sql)) {
        echo '<table border="2" align="center" id="table">';
        echo '<tr>'
        . '<th>Cognome </th>'
        . '<th>Nome</th>';

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            echo '<tr>
                    <td>
                        <p>'.$row['cognome'].'</p>
                    </td>
                    <td>
                        <p>'.$row['nome'].'</p>
                    </td>
                    <td>
                        <input type="checkbox" name="nome_var[]" value="'.$row['id'].'">
                    </td>
                </tr>';
        }
        echo '</table>';

        /* free result set */
        $result->free();
    }
?>

and here is what I've tried to get the checked elements but doesn't work

<?php
$nome_var = $_POST['nome_var'];
if(is_array($nome_var){
        $toinsert = "INSERT INTO pagamentiEffettuati 
                            (cognome, nome) 
                    VALUES ('$surname', '$name')";
        echo "Elementi selezionati: ".count($nome_var)."<br/>";
        echo "-> ".reset($nome_var);
        while( $elemento = next($nome_var) )echo "-> $elemento <br/>";         
}
?>

and there is what I've tried to get the checked elements but doesn't work




mercredi 26 juin 2019

Find whether all input checkbox is checked within a parent div element

I am trying to get the state of two input checkboxes within a div element. I need to set a flag variable to true only if both the checkboxes are checked. If any of the input checkbox is unchecked , then it should be set to false.

I tried this using for loop using the below code

        var oParNode = oNode.ParentNode;
                if (null != oParNode) {

                    for (var i = 0; i < oNode.ParentNode.Nodes.length; i++) {
                        if (oNode.ParentNode.Nodes[i].Checked) {
                            checked = true;
                        }
                        else {
                            checked = false;
                        }
                    }
                }


In this code , Nodes[i] returns the input element. When I check the first checkbox first and the second one next this loop works fine but when I check the second one first , the checked variable is set to true based on the second checkbox value which is executed at last.

Expected: I need to return "checked" to be true only if both checkboxes are checked .

Can somone suggest me on this

Thanks & Regards,

Keerthana.




I am new to mvc and want to save the checkbox data in the sql server using mvc I am new To MVC and want to save the checkbox

Controller Code: public ActionResult SaveRecord(CustomerCount cc) { try { CustomerCounterDBEntities1 dbs = new CustomerCounterDBEntities1(); List infos = dbs.CustomerInfoes.ToList(); ViewBag.CustomerInfoList = new SelectList(infos, "Name", "Mobile"); CustomerInfo ct = new CustomerInfo(); ct.CustomerID = cc.CustomerID; ct.Name = cc.Name; ct.Mobile = cc.Mobile; ct.Email = cc.Email; ct.Comments = cc.Comments; ct.Western_Union = cc.Western_Union; ct.Ria = cc.Ria; ct.Money_Gram = cc.Money_Gram; ct.Intel = cc.Intel; ct.JazzCash = cc.JazzCash; ct.Contact = cc.Contact; ct.No_Business = cc.No_Business; dbs.CustomerInfoes.Add(ct); dbs.SaveChanges(); int CustomerID = ct.CustomerID; return RedirectToAction("Index");

            }
       Model Code:
namespace Customer_Counter.Models
{
    public class CustomerCount
    {
       [Key]
        public int CustomerID { get; set; }

        public string Name { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Comments { get; set; }
        public Boolean Western_Union { get; set; }
        public Boolean Ria { get; set; }
        public Boolean Money_Gram { get; set; }
        public Boolean Intel { get; set; }
        public Boolean JazzCash { get; set; }
        public Boolean Contact { get; set; }
        public Boolean No_Business { get; set; }
    }
}
CustomerInfo:
namespace Customer_Counter.Models
{
    using System;
    using System.Collections.Generic;

    public partial class CustomerInfo
    {
        public int CustomerID { get; set; }
        public string Name { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Comments { get; set; }
        public Nullable<bool> Western_Union { get; set; }
        public Nullable<bool> Ria { get; set; }
        public Nullable<bool> Money_Gram { get; set; }
        public Nullable<bool> Intel { get; set; }
        public Nullable<bool> JazzCash { get; set; }
        public Nullable<bool> Contact { get; set; }
        public Nullable<bool> No_Business { get; set; }
    }
}
CustomerForm View: //Only the error part
  @Html.CheckBoxFor(Model => Model.Western_Union)
                    @Html.CheckBoxFor(Model => Model.Ria)
                    @Html.CheckBoxFor(Model => Model.Money_Gram)
                    @Html.CheckBoxFor(Model => Model.Intel)
                    @Html.CheckBoxFor(Model => Model.JazzCash)
                    @Html.CheckBoxFor(Model => Model.Contact)
                    @Html.CheckBoxFor(Model => Model.No_Business)

I am new To MVC and want to save the checkbox data in boolean form in sql server. The error is CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)




Highlight the label item after clicking on checkbox

I am trying to display the cards as input type is a checkbox, on selecting the cards I am able to fetch the details what are cards selected by the user, and my requirement is I required to highlight the card which is selected by the user.

for example, I need to highlight the card whose checkbox is checked, and if the checkbox is unchecked I need to show as the card.

<form [fromGropu]="form1">

<label for="" *ngFor="let item of items";let i =index">
<input type="checkbox" id="" [value]="item" (change)="onchange()"/>

<div class="card rounded-0">
<div class="card-header"></div>
<diva class="card-body></div>
<div class="card-footer"></div>
</div>
</div>
</label
</form>

css trying:

lable+ input[type=checkbox]:checked {
//some css code
}

but above CSS is not working, could anyone help on this




How to unckeck checkboxes in another div when checkbox in one div is checked

I've 3 div elements namely part1 and part2 and part3

There are multiple checkboxes in each div

If checkboxes in part1 and part2 are checked then part3 should be unchecked. (Not working)

If checkbox in part3 is checked then the other should be unchecked (This is working)

The checkbox in part3 is uncheckable.

Link In the comments




IE-Edge check box values are not persisting when if we go some page and come-back to current page by using the browser back button.?

When if we check the checkbox and go somewhere and come-back by using the browser back button, the values are persisting properly in (IE, FF and Chrome). But in IE-Edge check box values are not persisting.

When if we check the checkbox and go somewhere and come-back by using the browser back button, the values are persisting properly in (IE, FF and Chrome). But in IE-Edge check box values are not persisting.

Save the below content as as 1.html and 2.html files.

I want to use the IE-EDGE and even after go next page and come back to the current page still the check box values(checked) should persist.

1.html file.

    <!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Vertical (basic) form</h2>
  <form action="2.html">
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" autocomplete="on">
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
    </div>
    <div class="checkbox">
      <label><input type="checkbox" class="form-control" id="remember" name="remember" autocomplete="on"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

</body>
</html>

And 2.html file

<html>
<body>Testing browser back button and state of the checkbox value</body>
</html>




config method does not work for my buttons and checkbox widgets what seems to be the problem

i am creating an application that has many widgets including buttons and check boxes and i want to be able change their background colors while it's running by clicking on a button that calls a function that randomly picks colors from a list, it works for labels and frames but the button's and and check boxes gives me an error: AttributeError: 'NoneType' object has no attribute 'config' please help me.

def color2(self): colors2 = ['snow','navajo white','lavender','coral1', 'conflower','blue','cyan3','spring green', 'lightcoral','HotPink2','PeachPuff2','RoyalBlue4', 'yellow','orange2','RosyBrown2','SpringGreen2',
'AntiqueWhite2','turquoise2','plum2']
pick2 = random.choice(colors2)

    #this are buttons
    self.calculator.config(bg=pick2)
    self.btnExit.config(bg=pick2)
    self.btnReceipt.config(bg=pick2)
    self.btnSave.config(bg=pick2)
    self.btnTotal.config(bg=pick2)
    self.btnReset.config(bg=pick2)
    #this are labels
    self.lblCostofDrinks.configure(background=pick2)
    self.lblCostofFood.configure(background=pick2)
    self.lblCostofSnacks.configure(background=pick2)
    self.lblServiceCharge.configure(background=pick2)
    self.lblSubTotal.configure(background=pick2)
    self.lblTotal.configure(background=pick2)
    #this are frames
    self.Buttons_Frame.configure(background=pick2)
    self.RCF.configure(background=pick2)
    self.Receipt_Frame.configure(background=pick2)
    self.MenuFrame.configure(background=pick2)
    self.Food_Frame.configure(background=pick2)
    self.Snacks_Frame.configure(background=pick2)
    self.Drinks_Frame.configure(background=pick2)
    self.Cost_Frame.configure(background=pick2)




VB.NET : How to print the checkbox text and the checkbox state

I new in VB.net programming I am asking if there is a way to print the checkbox itself including the box beside the text and the text itself.Is it possible to print it?If so ,can you share some code?




mardi 25 juin 2019

Place checkbox embedded in the upper right of an image?

How do I place a checkbox embedded in the upper right of an image? This currently does not work

HTML:

<div class="container">
    <img src="https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" />
    <input type="checkbox" class="checkbox" id="check1" />
</div>

CSS:

.container {
    position: relative;
    width: 100px;
    height: 100px;
    float: left;
    margin-left: 10px;
}

.checkbox {
    position: absolute;
    right: 5px;
    top: 5px;
}




how to change checkbox to a validate icon in database?

when I tick the checkbox and click on the validate button, I want the checkbox to become an validation icon within the table like the example below. Hello, when I tick the checkbox and click on the validate button, I want the checkbox to become an validation icon within the table like the example below.

datatable with checkboxes

Here is my HTML:

<table class="table table-bordered" id="mytable">
  <tr>
    <th><input type="checkbox" id="check_all"></th>
    <th>matricule</th>
    <th>salary</th>
    <th>number day</th>
    <th>premium</th>
  </tr>
  <tr>
    <td><input type="checkbox" class="checkbox"></td>
    <td>1</td>
    <td>5000</td>
    <td>2</td>
    <td><input type="text" name="prime" class="form-control" value="0"></td>
  </tr>
  <tr>
    <td><input type="checkbox" class="checkbox"></td>
    <td>2</td>
    <td>6000</td>
    <td>2</td>
    <td><input type="text" name="prime" class="form-control" value="0"></td>

  </tr>
  <tr>
    <td><input type="checkbox" class="checkbox"></td>
    <td>1</td>
    <td>7000</td>
    <td>1</td>
    <td><input type="text" name="prime" class="form-control" value="0"></td>

  </tr>
</table>
<div class="form-group col-md-offset-5 ">
  <button class="btn btn-success add-all" type="submit" id="hide">Pointage men</button>
</div>

Here is my JQuery:

$(document).ready(function() {
  $('#check_all').on('click', function(e) {
    if ($(this).is(':checked', true)) {
      $(".checkbox").prop('checked', true);
    } else {
      $(".checkbox").prop('checked', false);
    }
  });
  $('.checkbox').on('click', function() {
    if ($('.checkbox:checked').length == $('.checkbox').length) {
      $('#check_all').prop('checked', true);
    } else {
      $('#check_all').prop('checked', false);
    }
  });

  $("#hide").click(function() {
    $("tr").each(function(i, r) {
      if (i > 0 && $(r).find("input").first().prop("checked")) {
      }
    });
  });
})




How to use setState() function inside SearchDelegate?

I am using a list with Check Box in it. The check box are used to select the items in the list. I have implemented a Search function using SearchDelegate.

Reference with below link

How to Set/Update Sate of StatefulWidget from other StatefulWidget in Flutter?

I have called the setState of parent from SearchDelegate.

But when I select an Item from search delegate the checkbox is not animating, when I hit the back button in the search bar, the value has been changed in the List.

Checkbox(
      value: list[index].isSelected,
      onChanged: (val) {
        this.parent.setState((){
        this.parent.widget.invoiceList[index].isSelected = val;
  });
});

I just want the check box to be animated while tapping it from the search delegate. Thank you.




Multi-select in jQuery not working even after the addition of the dependancies in a right format as mentioned in the multi-select Tutorial

I am trying with the multi select with check box plugin of jQuery as suggested in the following link http://davidstutz.de/bootstrap-multiselect/#getting-started But while i implemented at js fiddle for testing means doesnt work as expected, what would be the issue here This is the link to js fiddle test code




How to get the id from programmatically linear layout item

I don't know how to get the id from an programmatically linear layout created item. I want to "catch" the right id of an button and associate that with fields.

LinearLayout layout = (LinearLayout) findViewById(R.id.content_doodle_linearlayout3); layout.setOrientation(LinearLayout.VERTICAL);

    String[] data = {"1","2","3","4"};
    String[] users = {"1","2","3"};


 for (int i = 0; i < users.length; i++) {
        row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        text = new TextView(this);
        text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        text.setText("Name " + (i));
        text.setId(1000 + i);

        row.addView(text);
        int ergebnis = -1;
        for (int j = 0; j < daten.length; j++) {
            CheckBox btnTag = new CheckBox(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            //btnTag.setText("Button " + (j + 1 + (i * 4)));
            btnTag.setId(j + 1 + (i * 4));

            row.addView(btnTag);
        }

        layout.addView(row);
    }

The Buttons can't not be found, because there "isn't" a (R.id.{XML-Field}). How can i "find" the clicked button from the specific row. Do i have to code every button?




How to check if a checkbox is checked in a qtablewidget?

I'm setting a filtering tool in Python 3.7 and I'm using pyqt5. I've created a qtablewidget to store the filters and their complementaries choosed by the user. I'd like to allow the user to combine filters over a data so I added grouped checkboxes in each row to select wanted filters. Which commands should I use to loop over my qtable to get wich checkbox is selected please ?

enter image description here

def bindApply(self):
    checked_list = []
    for i in range(self.tableWidget.rowCount()):
        #print(self.tableWidget.rowCount())
        if self.tableWidget.item(i, 1).checkState() == QtCore.Qt.Checked:
            checked_list.append([i,1])
        elif self.tableWidget.item(i, 2).checkState() == QtCore.Qt.Checked:
            checked_list.append([i,2])
        else:
            pass
    return(checked_list)

I expect a list containg the indexes of selected rows and columns but my function returns nothing.




lundi 24 juin 2019

Angularjs: How to keep checkbox value after reload

I got the following code from W3Schools, but am wondering how to get the checkbox value to persist even after reload:

Keep HTML: <input type="checkbox" ng-model="myVar">

<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>

<p>The DIV element will be removed when the checkbox is not checked.</p>
<p>The DIV element will return, if you check the checkbox.</p>

Right now, if you check the box and reload the page, the checkbox becomes unchecked again. How would you get the checkbox to retain its value even after reload? Thanks!




_tkinter.TclError: unknown option "-title" error in python checkbox

I am trying to make a class to display checkbox on calling that class again and again without rewriting the whole code but just by providing the basic variable values using tkinter with python version 3.7.2. Got stuck in this problem.


# easyfunc.py

import tkinter as tk

class checkButton:
    """docstring for checkButton"""
    def __init__(self, title, bg, command):
        super(checkButton, self).__init__()
        self.title = title
        self.bg = bg
        self.command = command
        var = IntVar()
        checkbutton = Checkbutton(master, title=title, bg=bg, command=command, variable=var)
        checkbutton.pack()

------------------------------------------------------------------------------

# try.py

import easyfunc

def helloworld():
    print("helllo")
gui.checkButton("BUTTON", "white", "helloworld")

Traceback (most recent call last):
  File "try.py", line 6, in <module>
    gui.checkButton("BUTTON", "white", "helloworld")
  File "C:\...\easyfunc.py", line 55, in __init__
    checkbutton = Checkbutton(master, title=title, bg=bg, command=command, variable=var)
  File "C:\...\Python\Python37\lib\tkinter\__init__.py", line 2646, in __init__
    Widget.__init__(self, master, 'checkbutton', cnf, kw)
  File "C:\...\Python\Python37\lib\tkinter\__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: unknown option "-title"




CheckBox Label not in line with checkbox

What I am trying to do is get the check box inline with the centered text and get the label for the text box inline with the box....Code below:

                                <div class="row">
                                    <div class="col">
                                        <div class="description text-center mt-1 mb-3" id="lblBankAccount" style="display: block"><strong>Please fill out your Bank Account Information</strong></div>
                                        <div class="description text-center mt-1 mb-3" id="lblCreditCard" style="display: none"><strong>Please fill out your credit card information</strong></div>
                                        <div >
                                            <label><input type="checkbox" id="chkNoBankAccount" >I don't have a bank account</label> 
                                        </div>
                                    </div>
                                </div>

I have tried a variety of methods at this point and nothing is working - Not sure what top try next....

Thanks ion advance.




Starting a script from vb code won't work anywhere in imageButton_Click method

I am trying to call a script to uncheck all checked checkboxes in my gridview upon a button click. The button is an image button that also downloads images that correspond to the rows that are checked. This line of code works in other methods fine but for some reason I cannot figure out, won't work anywhere in this sub.

Protected Sub dwnld_Click(sender As Object, e As ImageClickEventArgs)
    Dim found As Boolean = False

    Using zip As New ZipFile()
        zip.AlternateEncodingUsage = ZipOption.AsNecessary
        zip.AddDirectoryByName("Drawings")
        For Each row As GridViewRow In gv1.Rows
            Dim c As CheckBox = TryCast(row.FindControl("cBox"), CheckBox)
            If c.Checked Then
                found = True
                Dim filepath = serv & row.Cells(1).Text & "B" & row.Cells(3).Text & ".TIF"
                zip.AddFile(filepath, "Drawings")
                'TryCast(row.FindControl("cBox"), CheckBox).Checked = False
            End If
        Next
        If found Then
            Response.Clear()
            Response.BufferOutput = False
            Dim zipname As String = [String].Format("Drawings_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss"))
            Response.ContentType = "application/zip"
            Response.AddHeader("content-disposition", "attachment; filename=" + zipname)
            zip.Save(Response.OutputStream)
            Response.End()
        Else
            If gv1.Rows.Count > 0 Then
                reSetup()
            Else
                initReSetup()
            End If
        End If
    End Using
End Sub

    ScriptManager.RegisterStartupScript(Page, GetType(Page), "Click", "clickb()", True)





Uncheck all checked checkboxes in gridview column

I have a column of checkboxes in my gridview and upon a button click all images that correspond to the data in the checked rows are downloaded. I would also like that button to uncheck all checked checkboxes but no matter what I try I cannot get it work.

I'm trying to get either of these scripts to work right now, I also cannot tell if I do not have the correct syntax in my vb code to call the first function

<script>
    function unCheck() {
        $('#<%=gv1.ClientID %>').find("input:checkbox").each(function () {
            if (this != false) {
                this.checked = false;
            }
        });
    }
</script>
<script>
    $("#dwnld").click(function () {
        $('#gv1').find("input:checkbox").each(function () {
            this.checked = false;
        });
    });
</script>

ScriptManager.RegisterStartupScript(Page, GetType(Page), "Script", "unCheck();", True)




Collapsible checkboxGroupInput in shiny

I have created a set of checkbox using renderUI and checkboxGroupInput. Here the result: enter image description here

What I would like to obtain now is something like this:

enter image description here

Where only the top results are shown with the possibility to expand the checkbox list.

Any suggestion on how to obtain this?

The code for the checkbox is the following:

Server.R:

    my_checkboxGroupInput <- function(variable, label,choices, selected, colors,perc){
    my_names <- choices
    log_funct("my_names",my_names,   verbose=T)
    if(length(names(choices))>0) my_names <- names(choices)
    log_funct("names(my_names)",my_names,   verbose=T)
    log_funct("choices",choices,   verbose=T)
     log_funct("selected",selected,   verbose=T)
    div(id=variable,class="form-group shiny-input-checkboxgroup shiny-input-container shiny-bound-input",
        HTML(paste0('<label class="control-label" for="',variable,'">',label,'</label>')),
        div( class="shiny-options-group",
             HTML(paste0('<div class="checkbox">',
                         '<label style="width: 100%">',
                         '<input type="checkbox" name="', variable, 
                         '" value="', choices, 
                         '"', ifelse(choices %in% selected, 'checked="checked"', ''), 
                         '/>',
                         #'<span ', ifelse(choices %in% selected, paste0('style=" background-color:',colors ,'; display: inline-block; white-space: nowrap; width: ',perc, '%;"'),''), '>',my_names,'</span>',
                         '<span ', paste0('style=" background-color:',colors ,'; display: inline-block; white-space: nowrap; width: ',perc, '%;"'),'>',my_names,'</span>',
                         '</label>',
                         '</div>', collapse = " "))
        )
    )
  }

  output$checkbox_cond <- renderUI({

    my_checkboxGroupInput("variable", "Variable:",choices = cond_plot()$Var1, 
                          selected=c(as.character(cond_plot()$Var1)[1],as.character(cond_plot()$Var1)[2]),
                          colors=c('#4e71ba'),
                          perc= cond_plot()$perc)
  })

The code is a modified version of the one in: how to make the checkboxgroupinput color-coded in Shiny




dimanche 23 juin 2019

How to pass checknodes ID through submit button html with function too

I'm trying to post the checknodes id into database through submit button. I'm trying several way but not get it. And how to make the submit button be function to save the id? Can anyone show the correct code? Here's to be more clearly: https://dojo.telerik.com/IYEvALiY/11




How to Retrieve from Checkbox Form Result with Adding [ in PHP?

For example I have Checkbox Form Result in MySQL like this: resultA, resultB, resultC, resultD, resultE

Now, I want to retrieve the results to be [resultA] [resultB] [resultC] [resultD] [resultE]

I have tried by EXPLODE and FOREACH but its result not so perfect. Is anybody can help me how to make it as I want?




How do I write checkbox state to database with flash and sqlite?

I'm getting the below error when trying to write a checkbox state from a form in my SQLite 3 database using Flask and Python3.

400 Bad Request: The browser (or proxy) sent a request that this server could not understand

My code is shown below:

App:

@app.route('/complete', methods=['POST'])
   def complete():
         todo = Todo.query.filter_by(id=request.form['name']).first()
         todo.complete = True
         db.session.commit()

HTML:

    <form action="" method="POST">
        <ul>
            
        </ul>
        <input type="submit" value="Update Items">
    </form>




samedi 22 juin 2019

Checkboxes selection menu for tourism guide

guyz. I did an Android app like "Tourism guide" and i have 8 categories and each category contains different places. And I need to do selection.. More exactly, in my category FOOD i have 10 places where 3 are restaurants, 4 fast food and 4 pubs where you can eat and I dont know how to make a selection using checkboxes and when you check restaurant will show you only the places that are restaurant and after that you can click on them for more details. I need help as soon as possible. Thank you!




what's wrong with this jQuery addClass

I'm new to jQuery and have been fine with some simple codes but this one is puzzling me.

I have a list of checkboxes and I need to count the number of checked ones and display the count in a textbox. I want to add different class according to the count.

If 1 or 2 then class .blue If 3 or more then class .red If 0 AND a "none of the above" checkbox is checked then class .green * The "none of the above" checkbox has to be checked to add the class .green. A value of "0" is not enough. I need the user to be aware and sure of the "none of the above".

I managed to make it work and to make the checked status toggle between the "none of the above"and the rest.

I'm still puzzled by the addClass malfunctioning as follows:

What I expect is: When I click 1 or 2 checkboxes, the class goes blue. If I click a third one then it goes red. If I unchecked one, then it goes back to blue. If unchecked all then no style. If checked the "none of the above" then it goes green. If I uncheck any checkbox then the class should go back to the previous status.

This is what I'm getting: I'm not getting the '.red' class when 3 or more are checked. If I uncheck any checkbox, the class stays the same. If I uncheck all and regardless of the "none of the above", it goes ".green"!

This is my code:

$('input:checkbox').change(function() {
  var a = $("input.ab:checked").length
  $(".count").val(a);
  var count = $(".count").val(a);
  var res = '0';
  var nota = $('input.nota:checked');

  if (a < 1 && nota) {
    var res = ('green');
  } else if (a < 3 && a > 0) {
    var res = ('blue');
  } else if (a => 3) {
    var res = ('red'); // not working !
  }
  count.addClass(res);
});
// toggle checked
$("input.ab").change(function() {
    $("input.nota").not(this).prop('checked', false);  
});

$("input.nota").on('change', function() {
    $(".count").val(0)
    $("input.ab").not(this).prop('checked', false);    
});

Html:

<div>
  <h4>Count checked, toggle, add class to each result</h4>
  <u>
    <li class='gr'> If "None of the above" is checked then: GREEN </li>
    <li class='bl'> If count = 1 or 2 then: Blue </li>
    <li class='rd'> If count 3 or more then: Red </li>
  </u>
  <p>
    <input type='checkbox' class='ab'>AB
  </p>
  <p>
    <input type='checkbox' class='ab'>ABC
  </p>
  <p>
    <input type='checkbox' class='ab'>ABDC
  </p>
    <p>
    <input type='checkbox' class='ab'>ABCDEF
  </p>
  <p>
    <input type='checkbox' class='nota'> None of the above (HAS TO be checked to be green)
  </p>
  <p>
    Count: <input type='text' class='count'>
  </p>
</div>

This is the jsfiddle : http://jsfiddle.net/A888/h83z0knf/

Thank you. Please remember I'm a newbie here and in jQuery so please ask me to clarify or fix or even delete my post before you down-vote me. I tried my best before posting.




Function called twice time when contain react-hook

I'm creating a form for sign-up. In this form there is a checkbox for terms and condition, when I click for accept I have no update.

//react hook
        const [check, setCheck] = useState({
        confirmPassword: null,
        terms: false
    })

//checkbox in formik form
<IonCheckbox color="primary" name="Terms" checked={props.values.terms} onIonChange={(e) => test(e) } onIonBlur={props.handleBlur} />


//handler for change
    const test = (e: any) => {
        console.log(e.target.checked)
        setCheck({ ...check, terms: e.target.checked });
        console.log(check)
    }

When I click the checkbox I got

`Signup.tsx:74 true
 Signup.tsx:73 test
 Signup.tsx:74 false
 Signup.tsx:76 {confirm_password: null, terms: false}
 Signup.tsx:76 {confirm_password: null, terms: false}`

It looks like you call twice the handler. I expect when I click I get the update of terms field.

Why does it behave so what is the problem? how can i solve?




add number value from radio checked to span, then add/remove number value from separate checkbox

i have a number of quantities that are available to select by radio, and i want the price of that to show up in the TotalPrice span. however i also have another checkbox below the quantities for a shipping option that i would like added onto the TotalPrice span on top of the quantity price.

<th scope="row">
<input class="form-check-input" type="radio" name="quantity" id="quantity1" value="1">1</th>
<td>FREE + $6.97 S&H</td>
</tr>
<tr style="text-align: center;">
<th scope="row">
<input class="form-check-input" type="radio" name="quantity" id="quantity2" value="2">2</th>
<td>FREE + $9.97 S&H</td>
</tr>
<tr style="text-align: center;">
<th scope="row">
<input class="form-check-input" type="radio" name="quantity" id="quantity4" value="4">4</th>
<td>FREE + $16.97 S&H</td>
</tr>
<tr style="text-align: center;">
<th scope="row">
<input class="form-check-input" type="radio" name="quantity" id="quantity6" value="6">6</th>
<td>FREE + $21.97 S&H</td>
</tr>
<tr style="text-align: center;">
<th scope="row">
<input class="form-check-input" type="radio" name="quantity" id="quantity8" value="8">8</th>
<td>FREE + $26.97 S&H</td>

<input class="form-check-input" type="checkbox" name="ship" value="Expedited" id="exp1">

<span id="TotalPrice"></span>

also, is it possible for the values (quantity, expedited & TotalPrice) to be sent thru and picked up via $_POST in php?




vendredi 21 juin 2019

Detecting checkbox status change with jQuery on checkboxes created via javascript

I'm receiving this html code via Ajax in the variable data. It contains Bootstrap 4 switches, which are basically checkboxes:

<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="3" name="details[]" id="control_id_detail_3"><label class="custom-control-label" for="control_id_detail_3">S</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="4" name="details[]" id="control_id_detail_4"><label class="custom-control-label" for="control_id_detail_4">M</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="5" name="details[]" id="control_id_detail_5"><label class="custom-control-label" for="control_id_detail_5">L</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="6" name="details[]" id="control_id_detail_6"><label class="custom-control-label" for="control_id_detail_6">XL</label></div>

Then, I'm adding that html content to a div called #attribute_holder with:

$('#attribute_holder').html(data);

So at the end, I have this code:

<div id="attribute_holder">
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="3" name="details[]" id="control_id_detail_3"><label class="custom-control-label" for="control_id_detail_3">S</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="4" name="details[]" id="control_id_detail_4"><label class="custom-control-label" for="control_id_detail_4">M</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="5" name="details[]" id="control_id_detail_5"><label class="custom-control-label" for="control_id_detail_5">L</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="6" name="details[]" id="control_id_detail_6"><label class="custom-control-label" for="control_id_detail_6">XL</label></div>
</div>

Now, I need to detect via jQuery when the checkboxes change their state. I'm using this code:

$('#attribute_holder input[type="checkbox"]').on('change', function(){
    console.log($(this).val() + ' changed state to: ' + $(this).is(':checked'));
});

This seems to work if the html is already burnt in the html when the page is loaded. But, if I load the same html via ajax, jQuery is not detecting the change event on the checkboxes. What am I missing? Thanks!




How to create a checkbox that goes to a certain link under specific conditions

So I am trying to create a function in which I have various checkboxes of territories. The only thing is that I have pages for only some of the territories. So when a user selects a territory and it has a link to a page, then on submit it will take the user to that page. If the checkbox does not have a link then it will go to contact page. But if they select more than one territory and one of them has a link, it should still take them to that same contact page. The second part is that I want the selections to be parsed to the url to go to the contact page which will be a contact form 7 form so it auto fills the territory they selected.

so far I have created a function which recognizes how many checkboxes have been selected. I tried to add links and identify if those links that were selected with the checkbox. Im not sure if it is recognizing it with its corresponding element.

Html

<a href="https://corporate.territory.place/advertising-sandiego" 
id="salesURL"><input type="checkbox" name="territories" value="San 
Diego, CA">San Diego, CA</a>
<a href="https://corporate.territory.place/advertising-orlando" 
id="salesURL"><input type="checkbox" name="territories" 
value="Orlando, FL">Orlando, FL</a>
<a href="#" id="nosalesURL"><input type="checkbox" 
name="territories" value="Miami, FL">Miami, FL</a><br>
<button onclick="printChecked()">Click here</button>



jquery

function printChecked(){
var items=document.getElementsByName('territories');
/*below list the value of the selections*/
  var selectedItems="";
    for(var i=0; i<items.length; i++){
        if(items[i].type=='checkbox' && items[i].checked==true)
            var itemz = selectedItems+=items[i].value+" ";}

    var n = $("input[name=territories]:checked").length;/*Counts 
number of box selected*/
    var salesUrl = 
document.getElementById("salesURL").getAttribute("href");
    var salesID = 
document.getElementById("salesURL").getAttribute('id');

 if( n >= 1 && salesID == "salesURL"){
$("#info").html("Selected only 1" + " " + salesUrl+" "+itemz);
 }else if(n >= 1 && salesID == "nosalesURL"){
 $("#info").html("Go to contact sales");      
       }else{
$("#info").html("none selected");
}
}

Here's a link to where I am building it out!

For some reason when I try to set the condition for more than one selected it gives me the result of the first condition. I want the function to recognize the checkbox and determine if they have a url. if more than one then go to this page. it only one selected and it has a url then go to another page. etc




How to fill some tricky forms automatically via javascript

I need to figure out how to fill automatically some forms on certain webpage (in order to automatize a lot of regular handwork of several persons) and I cannot realize it via traditional methods, which work perfectly on other pages. I have made a figure which helps me to explain the problem -- here it is. The language of the page is Russian, but I inserted the needed explanations. I need to state that I am a complete noob in javascript and all I can is to use built-in simple editor (Firefox) to run simple codes, however, that was enough until this task. Help me, please.

There are four types of form elements, and I managed to cope with the first one, of text type (case 1 in Figure). I've run the following code and voila. Analogical method worked for all text fields. I can also address the name of the desired field and it also works perfectly.

requestAnimationFrame(step00);
var razstart = null; 
function step00(timestamp) {
     var raz=Array.prototype.slice.call(document.querySelectorAll('input[type="text"], input:not([type])')).filter(function(a) {return a.offsetHeight > '5'});  

raz[0].value = 'Пручкина Анна Артемовна'; 

As for the other cases I have broken my brain trying to realize how to deal with them. I'm especially dissapointed by case 3, which seems to look like checkbox -- and I have managed to check/unchecked them via script on other cites. However, as far as I assume, this thing here is actually not a checkbox (I've learnt via alert output that its type is also text) and I have no idea how it works -- I have inserted its code -- and others' too -- and I can provide any additional information if needed.

Nothing of the following works:

document.getElementsByName("enf_start_staffw")[0].checked=true;
document.getElementsByName("enf_start_staffw")[0].value=1;
document.getElementsByName("enf_start_staffw")[0].click();

A probably important moment is that for cases 2-4 when you manually click an element/choose an option, a small indicator appears on webpage that says "Saving". Maybe this is somehow related to the solution of the problem, however, it also appears when you finish writing the text manually in case 1, which does not hinder the work of the script.

Also I have tried to emulate clicks on certain points of the page. It works for the redirecting links, but does not work for the form elements.

Looking forward for your help!




Qtreewidgetitem with checkbox

A checkbox is added correctly when I set the check state of a qtreewidgetitem, but I´m not able to check/uncheck it in my qtreewidget. What am I doing wrong?

QTreeWidgetItem* item =
    new QTreeWidgetItem(parent);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable |
               Qt::ItemIsSelectable);
item->setText(0, text);
item->setCheckState(1, Qt::Checked);




How to get know if a checkbox has been selected in a dynamic UI in codenameone

I have a container with dynamic UI components including checkboxes. How can I know the selection status of a particular component?

Using iSelected() doesn't work as it is always false because it seems to pick the last checkbox in the list which returns false since it is unslected.


I am able to get the checkbox at a particular indext in the parent component but once I have it there is no "iSelected" option on it. So I use a dirty way by tokenizing the string representing the component to get to the selected statsus. There must be a better way.

```System.out.println("Checkbox Data "+cnt_tablerow[Integer.parseInt(lbl_memberno.getName())].getComponentAt(0)); //Checkbox Data: CheckBox[x=0 y=0 width=63 height=152 name=524, text = , gap = 2, selected = true]

```String str_chkbox = StringUtil.tokenize(StringUtil.tokenize(cnt_tablerow[Integer.parseInt(lbl_memberno.getName())].getComponentAt(0), ']').get(0), '[').get(1);

```String str_status = StringUtil.tokenize(StringUtil.tokenize(str_chkbox, ',').get(3), '=').get(1).trim();

```if(str_status == "true"){}




jeudi 20 juin 2019

Spring Boot Checkbox Array not working as expected

I have an array of checkboxes all with the same names which I submit to a Spring Boot Controller. I build a Bootstrap DataTable using Jquery/Ajax using data which receive from the database and test if I should select the checkbox when the page loads. I do this by using this code:

if (data['isChecked'] == "1") {
   return "<input type='checkbox' name='fieldIdList' value='1_' checked>";
} else {
   return "<input type='checkbox' name='fieldIdList' value='1_'>";
}

This code loops, so the next checkbox value will be 2_ and the next 3_, etc, etc.

When the page loads the table displays 10 rows and my first 2 checkboxes are shown as selected. This is correct.

Now when I submit this form without changing the state of any of the checkboxes to my Controller code below:

@RequestMapping(value = "/admin/dataTable", method = RequestMethod.POST)
public String postDataTable(@RequestParam("fieldIdList") List<String> fieldIdList){
    return "";
}

I get 2 entries in my fieldIdList:

"1_"

"2_"

This is correct because only my first 2 checkboxes was checked. But when I uncheck any of the checkboxes and submit again, I get a funny result. In the example below, I unchecked the 2nd checkbox and then submitted the form again, my entries in my fieldIdList:

"1_"

"1_"

"1_"

"2_"

By unchecking the second checkbox and submitting, I suspected to get only 1 entry in my fieldIdList as "1_"

Also after I submit, the page is redirected the the previous page, so when I enter this page again, all the Lists are loaded as new, so there can be no previous values still stored in them.

Not sure if this is a Jquery/Ajax issue or Java issue or just a problem with the object between the chair and laptop :)

Thank you for your time.




Set all checkbox in Kendo Dropdowntree checked when load the page

I want to create kendo dropdowntree where when i load the page, all the checkbox is checked. Here is my code.

    @(Html.Kendo().DropDownTree()
                          .AutoWidth(true)
                          .Name("dropdowntree")
                          .DataTextField("Name")
                          .DataValueField("Id")
                          .CheckAll(true)
                          .HtmlAttributes(new { style = "width: 100%" })
                          .Events(events => events.Change("onChange"))
                          .Filter(FilterType.Contains)
                          .AutoClose(false)
                          .Checkboxes(checkboxes => checkboxes
                              .Name("checkedFiles")
                              .CheckChildren(true)
                          )
                          .DataSource(dataSource => dataSource
                            .Read(read => read
                            .Action("GetName", "CheckBox")
                        )
                        )
    )

I already doing some research and try the solution, but none if them work. For example, what i have try:

$(document).ready(function () {
   $("#dropdowntree input.k-checkbox").prop("checked", true);
})

This one also not work:

$(document).ready(function () {
    $("#dropdowntree").attr('checked', 'checked');
})

This one is work, but i need to set the value. What i need is it checked all by default, no need to set the value.

 $(document).ready(function () {
 var dropdowntree = $("#dropdowntree").data("kendoDropDownTree");
 dropdowntree.value(["1","2","3","4","5","6","7"]); 
 })

Other than all of these, i also try the solution in this link jquery set all checkbox checked and others solution. But still not work. I really need some advice. Thank you.




Python KivyMD: How is it possible to use on_active on MDCheckboxes?

I'm currently facing some problems with the MDCheckbox. When I used the default Kivy Checkbox, the on_active parameter in the kv code seemed to work pretty good. But now I am trying to use the KivyMD MDCheckbox module with an MDList and try to add a function to the Checkbox via the on_active parameter:

Part of the kv code

#:kivy 1.11.0
#:import MDCard kivymd.card.MDCard
#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox
#:import MDList kivymd.list.MDList
#:import OneLineAvatarIconListItem kivymd.list.OneLineAvatarIconListItem

<ListItemWithCheckbox@OneLineAvatarIconListItem>:
    MyAvatar:
        source: 'src/hdl.jpg'
    MyCheckbox:

<LayoutPy>
    orientation: 'vertical'

    FloatLayout:

        MDCard:
            size_hint: .8, .5
            pos_hint: {'center_x': 0.5, 'center_y': 0.5}

            BoxLayout:
                orientation: 'horizontal'
                spacing: 20
                name: 'lists'

                ScrollView:

                    MDList:
                        id: scroll

                        ListItemWithCheckbox:
                            id: ckbx1
                            text: 'Box 1'
                            active: False
                            on_active: root.printS('Text 1')


                        ListItemWithCheckbox:
                            id: ckbx2
                            text: 'Box 2'
                            active: False
                            on_active: root.printS('Text 2')

                        ListItemWithCheckbox:
                            id: ckbx3
                            text: 'Box 3'
                            active: False
                            on_active: root.printS('Text 3')

Part of the Python code

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivymd.theming import ThemeManager
from kivy.uix.image import Image
from kivymd.list import IRightBodyTouch, ILeftBody
from kivymd.selectioncontrols import MDCheckbox
from kivy.lang import Builder

class LayoutPy(FloatLayout):
    def __init__(self, **kwargs):
        super(LayoutPy, self).__init__(**kwargs)

    def printS(self, text):
        print(text)

class MyCheckbox(IRightBodyTouch, MDCheckbox):
    pass


class MyAvatar(ILeftBody, Image):
    pass

Builder.load_file(design.kv)

class KivyGUI(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = ("Teal")
    title = ("App")

    def build(self):
        c = LayoutPy()
        return c

if __name__ == "__main__":
    KivyGUI().run()

I think unlike normal Kivy, KivyMD needs an additional active parameter to add functions to an MDCheckbox. I've tried to set an active parameter with a boolean value of True/False (I tried both and nothing seemed to work). I changed some parts of the code to make it easier for you but if you want to take a look on the original source code you can see it here. (In the original source code the MDCheckboxes are on line 143.

Many thanks in advance!




How can I include an if condition into switch to deel with this code

I have these variables :

« PST_INFINCDEM » is select group = (indicent=0/ demande=1) « PST_INFBLOQ » is a checkbox = (O / N) « DT_READEM » with type date.

I want to calculate the « DT_READEM » deppending on three conditions: 1- if PST_INFINCDEM = demande then DT_READEM =CURRENT Date +10 days 2- if PST_INFINCDEM = incident AND PST_INFBLOQ =O THEN DT_READEM =CURRENT Date + 2 Days 3- if PST_INFINCDEM = incident AND PST_INFBLOQ =N THEN DT_READEM =current Date + 5 days

$(document).ready(function() {

$('select').change(function(){
   var item=$('select').val();
   var checkedItem = $("#PST_INFBLOQ").is(":checked");

    switch (item){
    case "1":
    var newdate = new Date();

                                  newdate.setDate(newdate.getDate() + 10);
    
                                  var dd = newdate.getDate();
                                  var mm = newdate.getMonth() + 1;
                                  var y = newdate.getFullYear();
                                  if(mm<10) mm='0'+mm;
                                  var someFormattedDate = dd + '/' + mm + '/' + y;
                                  //document.getElementById('DT_READEM').value = someFormattedDate;
                                $('#DT_READEM').val(someFormattedDate);
            break;
    case "0":
    
    
$('#checkedItem ').click(function (event) {
    if (checkedItem === false)
    {                            
    var newdate_5 = new Date();

    newdate_5.setDate(newdate.getDate() + 5);
    
                                  var dd = newdate_5.getDate();
                                  var mm = newdate_5.getMonth() + 1;
                                  var y = newdate_5.getFullYear();
                                  if(mm<10) mm='0'+mm;
                                  var someFormattedDate = dd + '/' + mm + '/' + y;
                                  //document.getElementById('DT_READEM').value = someFormattedDate;
                                $('#DT_READEM').val(someFormattedDate);
                                
    }                                 
else    if (checkedItem === true)
{
    var newdate_2 = new Date();
                               
                               newdate_2.setDate(newdate_2.getDate() + 2);
    
                                  var dd = newdate_2.getDate();
                                  var mm = newdate_2.getMonth() + 1;
                                  var y = newdate_2.getFullYear();
                                  if(mm<10) mm='0'+mm;
                                  var someFormattedDate = dd + '/' + mm + '/' + y;
                                  //document.getElementById('DT_READEM').value = someFormattedDate;
                                $('#DT_READEM').val(someFormattedDate);
}
})
    
break;
default: 
$('#DT_READEM').val(new Date().toLocaleDateString()).attr('disabled','disabled');
    }
})
})  

Resources
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div>
  <span> date </span>
  <input type="date" id="DT_READEM">
</div>
<div>
  <span> bloc </span>
  <input type="checkbox" id="PST_INFBLOQ ">
</div>
<div>
  <span> info </span>
 <select id="pet-select" id="PST_INFINCDEM ">
    
    <option value=1>demande</option>
    <option value=0>indicent</option>
   
</select>
</div>

The problem that the result that want is true just when i select "demande" if i select "indicent" nothing is change and the checkbox is not taken into considaration even I put a condition about it