mercredi 31 mars 2021

React Native checkbox handle

I have country codes from a file, I render it like that, it returns all country names and codes perfectly.

               <TouchableOpacity 
           style={st.oneCode}
           onPress={selectItem}>
              <View
                 style={[
                    st.filterCheckMarkWrapper,
                    check === false &&
                       st.filterCheckmarkInactiveColor,
                 ]}>
                 {check === true && (
                    <View style={st.filterCheckmark} />
                 )}
              </View><Text style={st.CodeText}>
                 {item.countryName}: +{item.phoneCode}
              </Text>
           </TouchableOpacity>

but when check is true, all of the text are checked, how can i fix it?




Localstorage on AMP

I have created a theme using AMP and in an area there is a form with checkboxes to browse articles depending on their taxonomies (in this case the taxonomies are styles)

I have made an example that I want to stay checked after refresh but it is not working

<amp-script src="<?php ABSPATH; ?>/wp-content/themes/Amptheme1/template-parts/templates-tptf/ville/checkbox-action.js">
    <div class="container">
       <input type="checkbox" id="test7" class="linput" name="style[]"
         value="Streetwear/Sportwear"/><label class="lelabel" for="test7"> 
          <h6>Streetwear/Sportwear</h6> 
         </label>
         <button type="button" onClick="save()">save</button>
    </div>
</amp-script>

and for the JS

function save() {   
var checkbox = document.getElementById("test7");
localStorage.setItem("test7", checkbox.checked);    
}

//for loading
var checked = JSON.parse(localStorage.getItem("test7"));
document.getElementById("test7").checked = checked;



Converter to Bool

I have a normal Checkbox, where I want to set the IsChecked property to a Binding resource. The resource is a self written class myClass, which can be null or referenced (means not null).

The Checkbox should be NOT checked, if the assigned object myObject (out of myClass) is null
and checked, if it is not null.

What do I have to write in the IsChecked="..." property in my xaml file?




mardi 30 mars 2021

Checkbox and Radio input error in JavaScript and JQuery task list

Why does my Priority checkbox return 'on' as a result after selecting either the 'Important' or 'Unimportant' checkbox? Why does it not return either 'Important' or 'Unimportant'? Also, why does my Category radio selection only return the correct selection the first time I input and click the add button - on every subsequent attempt, the return is blank for Category. All the other input options work correctly.

var $addButton = $(".btn-primary");
var $removeButton = $(".btn-danger");
var $todoList = $(".uncomplete");
var $doneList = $(".completed");

//Take Text Input and Add <li> to To Do List
 $addButton.on("click", function(){
  
  //Creating object Variables 
  var $sort = $(".sort").val();
  var $newTask = $(".newTask").val();
  var $taskDescr = $(".taskDescr").val();
  var $taskDate = $(".taskDate").val();
 // var $category= $(".category").val();
  var $category= $("input[type='radio'][name='category']:checked").val();
  //var $importance = $("input[type='checkbox'][name='importance']:checked").val();
  var $importance = $('<input type="checkbox" name="importance"/>').val();
  var $newTaskString = $sort + ", " + $taskDescr + ", " + $newTask + ", " + $taskDate + ", " + $category + ", " + $importance + "  "; 
  var $todoList = $(".uncompleted");
  
   //call append method on $todoList
   
  $todoList.append("<li>" + $newTaskString + "<button><span> Done</span></button><button><span> Remove</span></button></li>").addClass("todo");
  
  //add styles to button added to DOM by append  
  var $span = $(".todo button span");
  var $button = $(".todo button");
  $button.addClass("btn btn-success");
  $span.addClass("glyphicon glyphicon-ok"); 
  $("input").val("");
   
 })
 
 //When Success button Clicked, remove task from to do list and append to completed tasks
 
  var $doneButton = $(".btn-success");

   $(".uncompleted").on("click", ".btn-success", function(){
   var $completedTask = $( this ).parent("li").text();
   $(this).parent("li").remove();
   $doneList.append("<li>" + $completedTask + "<button><span> Remove</span></button></li>").addClass("done");
   $(".done button").addClass("btn btn-danger");
   $(".done button span").addClass("glyphicon glyphicon-remove");
   
 })
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list-wrap" contenteditable="false"> 
    <div class="list-inner-wrap">
      <h2 class="title">ToDo List</h2>
      <h3 class="title">Add Task</h2>
      
      <label for="sort">Sort Order:</label><input type="text" class="sort" name="sort" id="sort" value="" placeholder="A,B,C,etc.">
      <br>
      <label for="task-name">Task Name:</label><input type="text" class="newTask" name="task-name" id="task-name" value="" placeholder="My task...">
      <br>
      <label for="task-descr">Task Descr:</label><input type="text" class="taskDescr" name="task-descr" id="task-descr" value="" placeholder="Buy milk...">
      <!--<h4>Date</h4>-->
      <br>
      <label for="task-date">Start Date:</label><input type="text" class="taskDate" name="task-date" id="task-date" value="" placeholder="dd/mm/yyyy">
      <br>

      <form method="POST" action="..." name="radiodemo" id="radiodemo" onsubmit="getCategory();">
        <label for="category"> Category:</label>

        <input type="radio" id="grocery" name="category" value="Grocery" class="category" checked="checked">
        <label for="grocery">Grocery</label>
        <input type="radio" id="work" name="category" value="Work" class="category">
        <label for="work">Work</label>
        <input type="radio" id="chores" name="category" value="Chores" class="category">
        <label for="chores">Chores</label>
        <input type="radio" id="finance" name="category" value="Finance" class="category">
        <label for="finance">Finance</label>
      <br>
    </form>
    
      <label for="importance">Priority:</label>&nbsp &nbsp Important<input type="checkbox" class="importance" name="important" id="important" value="Important">
      <label for="importance"></label>Unimportant<input type="checkbox" class="importance" name="unimportant" id="unimportant" value="Unimportant">
      <br>
      
      <button class="btn btn-primary">
    <span class="glyphicon glyphicon-plus"> Add</span>
  </button>

      <br>

      <h3 class="title">To Do</h2>
        <h6><i>Click task item to edit or modify</i></h6>
        
      <ul class="uncompleted" id="id01"><!--contenteditable="true"-->
               
        <li>Need to be completed task
          <button class="btn btn-success"><span class="glyphicon glyphicon-ok"> Done</span>
          </button>

          <button class="btn btn-danger"><span class="glyphicon glyphicon-remove"> Remove</span>
          </button>

          <br>
        
        </li>
      </ul>



Checkbox select the whole row laravel 7

I am trying to create a menu with food and price ,when I Choose the food that I want ( using checkbox ) I want to receive also the price of that specific choosen food.

PS: I am using laravel 7 (without jquery), I can receive the food after checking it but not its price. So My question how to select the whole row with one checkbox.enter image description here

view:

<form action="" method="post">
                      @csrf
                      @method('post')
                      <input type="hidden" name="restaurantname" value="Restaurant A">
                      <div class="form-group">
                          <div class="card-header">
                              <div class="row">
                                  <div class="form-group col-md-4">
                                      
                                  </div>
                                  <div class="form-group col-md-4">
                                      
                                  </div>
                                  <div class="form-group col-md-4">
                                      
                                  </div>

                              </div>



                          </div>

                          <div id="row-1">
                              <div class="row">
                                  <div class="form-group col-md-4">
                                      <input type="checkbox" name="salade[]" value="salade1" id="chk-1" />Salade1
                                  </div>
                                  <div class="form-group col-md-4">
                                      <input type="checkbox" value="30" id="price" name="price[]"> 30 Dh
                                  </div>
                                  <div class="form-group col-md-4">
                                      <input type="checkbox" value="1" name="qt[]"> 1
                                      <input type="checkbox" value="2" name="qt[]"> 2
                                      <input type="checkbox" value="3" name="qt[]"> 3
                                      <input type="checkbox" value="4" name="qt[]"> 4

                                  </div>
                              </div>
                          </div>
                          <br>

                          <div id="row-2">
                              <div class="row">
                                  <div class="form-group col-md-4">
                                      <input type="checkbox" name="salade[]" value="salade2" />Salade2
                                  </div>

                                  <div class="form-group col-md-4">
                                      <input type="checkbox" value="40" id="price2" name="price[]"> 40 Dh
                                  </div>
                                  <div class="form-group col-md-4">
                                      <input type="checkbox" value="1" name="qt[]"> 1
                                      <input type="checkbox" value="2" name="qt[]"> 2
                                      <input type="checkbox" value="3" name="qt[]"> 3
                                      <input type="checkbox" value="4" name="qt[]"> 4

                                  </div>
                              </div>

                          </div>
                      </div>

controller : I just wanna see them , not inserting them in DB, not yet


  public function add(Request $request)
  {
      echo ($request->restaurantname);

      $checked_array= $request->salade;

      if ($checked_array) {
          foreach ($checked_array as $c) {
              echo ($c);
          }
      }
}



How to show checked checkbox form update in Codeigniter 4

I have a problem to showing checked checkbox in form update,

my views:

<?php foreach($pertanyaan as $p) { ?>
<form action="<?= base_url('SAdmin/PertSurvei/edit/'.$p['id_pert']); ?>" method="post">
<div class="form-group row">
          <label class="col-sm-4 col-form-label">Animals</label>
          <div class="col-sm-8">
            <div class="form-check">
              <label class="form-check-label">
                <input type="checkbox" name="animals[]" alt="Checkbox" value="Chicken" class="form-check-input" <?php if (in_array("Chicken", $p)) echo "checked";?>>
                Chicken
              </label>
            </div>
            <div class="form-check">
              <label class="form-check-label">
                <input type="checkbox" name="animals[]" alt="Checkbox" value="Cow" class="form-check-input" <?php if (in_array("Cow", $p)) echo "checked";?>>
                Cow
              </label>
            </div>
            <div class="form-check">
              <label class="form-check-label">
                <input type="checkbox" name="animals[]" alt="Checkbox" value="Pig" class="form-check-input" <?php if (in_array("Pig", $p)) echo "checked";?>>
                Pig
              </label>
            </div>
          </div>
        </div>
</form>
<?php }?>

my controller:

public function edit($id_pert)
    {
        $data = array(
            'id_pert'       => $id_pert,
            'pertanyaan'    => $this->pertModel->detailPertanyaan($id_pert),
            'pertanyaan'    => $this->request->getVar('pertanyaan'),
            'id_unit'       => $this->request->getVar('id_unit'),
            'animals'      => implode(", ", ($this->request->getVar('animals'))),
            'id_kat'        => $this->request->getVar('id_kat')
        );
        $this->pertModel->editPertanyaan($data);
        return redirect()->to(base_url('SAdmin/pertSurvei'));
    }

im using modal bootstrap for form update. Does anyone know where the problem is? what should i do?




updating db with multiple checkbox value witch ID hidden sometimes fails

Before I had text type input, I simply put 1 for active and 0 to deactivate, everything works perfect like this, but I want to change the appearance of the app by checkbox.

When deactivating all and sending it works fine, also when turning off everything inserts well, but for example, I have 3 IDs (1,2,3), if I turn off the ID2 it actually turns off the ID3, I don't understand what happens.

This is what my table looks like

id - option - value

1 - option1 - 1
2 - option2 - 0
3 - option3 - 1

Code:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $item_Count = count($_POST["id"]);

  for($i = 0; $i < $item_Count; $i++) {

    DB::update('app_options', array(
      'active' => $_POST["active"][$i],
    ), "id = %s", $_POST["id"][$i]);

  }
}
?>

<form method="POST">
  <?php

  $results = DB::query("SELECT * FROM app_options");

  foreach ($results as $row) { ?>

    <input type="hidden" name="id[]" value="<?php print($row['id']);?>">

    <input class="form-check-input" type="checkbox" name="active[]" id="active" value="1" <?php if (isset($row['active'])){echo "checked";} ?> >

  <?php } ?>

  <button type="submit" class="btn btn-primary btn-block">submit</button>
</form>

There are many questions with answers, but none use the hidden input that I need, I hope you can help me, thank you very much!




lundi 29 mars 2021

Submit single form with multiple checkboxes

I made a website with PHP. I did all my tasks but still have problem in this. I wrote this code to be able to delete multiple CheckBoxs in the Control Panel,

It works but only deletes one box.

function SelectDelete()
{
        $a = new mysqli("localhost", "root", "", "gamsite");
        if($a->connect_error)
        {
                die("something went worng".$a->connect_error);
        }
        $tmp=$a->query("SELECT * FROM game");
        if($tmp->num_rows>0)
        {
             while($record=$tmp->fetch_assoc())
             {
                ?>

<form  method="post">
<table class="table table-dark">

  <thead>
    <tr>
    <th scope="col"></th>
    <th scope="col"></th>
    <th scope="col"></th>
      <th scope="col">ID</th>
      <th scope="col">Name</th>
      <th scope="col">Download</th>
      <th scope="col">Image</th>
      <th scope="col">video</th>
      <th scope="col">subgame</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row"></th>
      <th scope="col"></th>
      <input type="hidden" name="act" value="SelectDelete">
      <td>
      <input type="checkbox" name="check[]" value="<?php echo $record['id']; ?>">
      </td>
      <td  name="id"><?php echo $record['id']; ?></td>
      <td name="name"><?php echo $record['name']; ?></td>
      <td name="download"><?php echo $record['download']; ?></td>
      <td name="image"><?php echo $record['image']; ?> </td>
      <td name="video"><?php echo $record['video']; ?></td>
      <td name="subgame"><?php echo $record['subgame']; ?></td>
      <th scope="col"><th scope="col">
    <button type="submit" name="delete" class="btn btn-danger" onclick="location.reload()">Delete</button>
    </th> 
    </tr>
   
  </tbody>
  
</table>
</form>

                 <?php
             }
        }
        else
        {
         echo "There is no data";
        }
if(isset($_POST['delete']))
{
        if(isset($_POST['check']))
        {
             foreach($_POST['check'] as $delete_id)
             {
                $a = new mysqli("localhost", "root", "", "gamsite");
                if($a->connect_error)
                {
                        die("something went worng".$a->connect_error);
                }
                $a->query("DELETE FROM game WHERE id='$delete_id'" );                  
             }   
        }
    }
}

I did try everything to make it work but nothing worked. Watched a couple of video in YouTube but I have to change my code structure .




How to keep state of the checkbox after the reload the page in angular 9?

I am trying to check the multiple checkboxes, when the page reloads, the state is restored to default (unchecked) and I've been buzzing my head with this. by the way I stored the checked value in the local storage but I do not know how to map it to the HTML checkbox for checked when the page reloads. please help me.

.html

<tbody>
            <tr *ngFor="let p of pmDetails1">
              <td>
                <input type="checkbox" name="" [value]="p.id" (change)="getEmployeeId($event,p.id)">
              </td>
              <td>
                 
              </td>
              <td>
                
              </td>

            </tr>
          </tbody>

.ts

ngOnInit() {
this.userService.getAllUsers().subscribe((x: IEmployee[]) => {
    this.pmDetails1 = x;
});

    this.selectedItem = new Array<number>();
    this.selectedEmployee = new Array<number>();
    console.log("localStorage", localStorage.getItem("selected"));
    this.selectedItem = JSON.parse(localStorage.getItem("selected"));
  }

//onSaveEmployee is a function for the button to the confirm that I checked,
 onSaveEmployee() {
    localStorage.setItem("selected",JSON.stringify(this.selectedEmployee));
  }
 getEmployeeId(e:any,id:string){
    if(e.target.checked){
      this.selectedEmployee .push(id);
   }
 else{
      this.selectedEmployee = this.selectedEmployee.filter(m => m!=id);
  }
 }

IEmployee interface

export interface IEmployee {
id: number;
firstName: string;
jobTitle: any;
lastName: String;
}



How to get the value of each checkbox inside foreach in angular 9 reactive forms

I have a checkbox in each row of primeng ptable and also a click function in each checkbox. The code is given below :

<ng-template let-productList>
  <input type="checkbox" (change)="updateStatus(productList.product_id, $event)">
</ng-template>

In component.ts :

updateStatus(productid: any, e: any) {
      console.log(productid)
  }

When I click any checkbox am getting only the first productid in updateStatus function. how can I solve this issue in reactive form?




checkbox value id not getting

I tried to store my checkbox value ID to database but i am getting error count(): Parameter must be an array or an object that implements Countable in. please anyone to help me figure out my problem this is what I am trying to

The HTML:

<input type="checkbox" name="chk1[ ]" value="<?php echo $rows['AMOUNT'] .' - '. $rows['ID'] .' ';?>">&nbsp<?php echo $rows['DESCRIPTION'];?></input>

PHP:

<?php
if(isset($_POST['Save'])){
    
    $checkbox = $_POST['chk1'];
    $check = implode(", AND ", $checkbox);
    $value = explode(", AND ", $check);
    $AMOUNT = trim($value[0]);
    $FEE_ID = trim($value[1]);
    
for($i=0;$i<count($FEE_ID);$i++){
$stmt = $conn->prepare("INSERT INTO fee_checked (FEE_ID) VALUES (?)");
$stmt->bind_param("i",  $FEE_ID[$i]);
$stmt->execute();
}
}
?>

Please Any help would be greatly appreciated. Thanks ahead of time!




dimanche 28 mars 2021

jquery get checkboxes either checked or have a specific data

I have a form with many checkboxes, some of which have a specific data property (say data-myname). Now, on click of a button, I need to get the collection of checkboxes that are either checked or have the property data-myname (checked or not) and use inside $.each(filteredCollection, function(){.....}).

I looked at using .map and .filter, but due to my limited understanding of these functions, I am not able to get the right sequence of conditions to be used.

Any help will be greatly appreciated.




How to prevent unnecessary renders when checking a checkbox?

I'm trying to create performant checkbox tree component. I have a parent level state to hold list of checked checkbox IDs =>

const [selected, setSelected] = useState([]);

and when toggling a checkbox its ID is added or removed to/from that array. I'm passing boolean to each checkbox which controls the checked state =>

checked={selected.includes(hole.id)}

Checkbox -input is separated to a own CheckboxNode component.

When not using React.memo for the CheckboxNode component I can always see each checkbox from the same parent triggering console.log() even only one is clicked/toggled

When using React.memo with following check I see 1-3 renders when toggling the checkboxes =>

const areEqual = (prev, next) => prev.checked === next.checked;

Also the visual states changes really peculiarly and the component feel really buggy.

How could I achieve great performance and getting rid of extra renders in a setup like this? I added the code here so anyone can take a better look: https://codesandbox.io/s/shy-frog-4wjrg?file=/src/CheckboxNode.js




Excel VBA generated checkboxes not aligning with cells

I would like to create a column of 100 checkboxes to select rows.
I can create the checkboxes but as they go further down the sheet the checkboxes slowly diverge from the desired rows. Checkbox labeled for row 101 - chkbox101 ends up in row 102. checkbox labeled chkbox101 in row 102

Dim cBox As CheckBox

Dim cell As Range

For Each cell In Range("a2:a101")
  Set cBox = ActiveSheet.CheckBoxes.Add(cell.Left, cell.Top , cell.Width, cell.Height)
     
  cBox.Text = "CHKBX " & cell.Row
                
       
Next cell



Perform CurrentCellChanged only on mouse click datagridview c #

The problem is that I programmatically change the checkbox in the datagridview, which triggers the CurrentCellChanged event, which should only perform when I click on that checkbox with my mouse. How do I make it so that the CurrentCellChanged event only perform when the field changes with a mouse click?




Ninja form Select-All Unselect-All checkbox button not working

I am working on multi-select ninja form. In the first step there are 8 checkbox options and client want a button for Select all unselect all. I am trying to checked all checkbox option on button click using jquery but in Ninja form checkbox only post values when some one click on it. By jquery, checked all checkbox option did not pass any values on form submit.
https://prnt.sc/10xygiq




samedi 27 mars 2021

How to insert selected value from select option using checkbox in PHP?

how to insert select option value in database using checkbox?When I click checkbox and click enroll ,select option doesn't inserting selected value when i choose more then two.I have 3 options(Regular,Retake,Recourse) in "examtype" table but when I choose more then one subject select option not working perfectly. Here is my code... here is my select option image

 <?php
if (isset($_POST['enroll'])){
if (!empty($_POST['chk1'])) {
foreach($_POST['chk1'] as $checkbox1){
  if (isset($_POST['exam_type'])){
foreach($_POST['exam_type'] as $checkbox2 )

$values = explode("|" , $checkbox1);
$values1 = explode("|" , $checkbox2);
$course_id= $values[0];
$semester= $values[1];
$course_name= $values[2];
$exam_type=$values1[0];

$sql="INSERT INTO pendingcourse(course_id,semester,course_name,exam_type) VALUES('$course_id','$semester','$course_name','$exam_type')";
$stmt = $connect->prepare($sql);
$stmt->execute();
$checkbox1='';
$checkbox2='';

}
}
header("location:coursetable.php");
}
}
?>

<?php
$stmt = $connect->query("SELECT course_id,semester,course_name FROM coursetable Where semester = '1st' ");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row)
{
   $course_id = $row['course_id'];
  $semester = $row['semester'];
   $course_name = $row['course_name'];

?>
                    <tr>
                        <td scope="row"> <?php echo $course_id?></td>
                        <td > <?php echo $semester ?></td>
                        <td ><?php echo $course_name ?></td>
                        <td>
                        
                        <select name="exam_type[]" class="form-select form-select-sm" aria-label=".form-select-sm example">
                            <?php 
                              $stmt1 = $connect->query("SELECT * from examtype");
                              $rows1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
                              foreach($rows1 as $row1) { ?>
                                    <option><?php echo $row1['exam_type']; ?></option>
                                    <?php 
                                    }
                            ?>
                        </select>
                    
                     
                        </td>  
                        <td>     
                        <input type="checkbox" name="chk1[]" value="<?php echo $row['course_id']?>|<?php echo $row['semester']?>|<?php echo $row['course_name']?>">
                            <label class="form-check-label" for="flexCheckDefault">
                            </label>  
                        </td>
                        <td></td>
                      </tr>                     
 <?php
}
?>
                    </tbody> 
              </table>
          </div>
        </div>
      </div>
    </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-md-2 col-xs-6 offset-md-5">
    
    <button type="submit" name="enroll" class="btn btn-warning mt-2">Enroll</button>



Detect the source of CheckChanged of a checkbox in Xamarin Forms

The CheckedChanged event of a CheckBox is fired when the page is loading up (on data binding), in addition to the user actually checking/unchecking.

Is there a way to detect whether CheckedChanged event was fired by a user action or otherwise?

In WinForms/WPF, I used to define a boolean variable like Loading = true; and then used to set Loading = false; once page load is finished. Then, the CheckedChanged event would check if Loading is false to execute the logic. Here's how I used to do it:

private void CheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
    if (Loading == true) return;

    //execute logic...
}

With async functions all over, I am unable to fit the Loading trick correctly. Is there a better way?




vendredi 26 mars 2021

Material Ui Data Grid

I want to prevent the material Ui Datagrid multiple checkbox section. When I select the checkbox section the particular row should be select and the other rows are remain unselected. I tried the disableMultipleSelection option but it would not work.

<DataGrid
              rows={cycle}
              columns={columns}
              pageSize={10}
              checkboxSelection
              disableMultipleSelection
              onRowSelected={({ data, isSelected }) => {
                setDisplay(isSelected);
                setCycleId(data.key);
                setCycleImg(data.storageRef);
              }}
            />
```[enter image description here][1]


  [1]: https://i.stack.imgur.com/odmXY.png



How to center custom checkbox in table with Bootstrap

I have tried to center the first column that contains in header delete all and in lines checkbox with Bootstrap 4 but without success, I have tried text-center CSS class but its not working can someone help:

The example code is available in jsfiddle her :

http://jsfiddle.net/5duvfs3b/

I use the Bootstrap 4 And the html code is here:

            <div class="content-wrapper">
                <div class="content-body">
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <form class="list list-customer" method="POST"
                                      action="#">
                                    <div class="table-responsive pt-0">
                                        <table class="list-items dt-column-search table table-striped table-bordered dataTable">
                                            <thead class="list-header">
                                            <tr>
                                                <th class="p-0 text-center">
                                                    <button type="button" data-multi="1"
                                                            onclick=""
                                                            class="act-delete-all btn btn-icon btn-flat-dark btn-sm waves-effect"
                                                            tabindex="1" aria-label="Delete" title="Delete selected entries">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14"
                                                             viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                                             stroke-linecap="round" stroke-linejoin="round"
                                                             class="feather feather-trash-2">
                                                            <polyline points="3 6 5 6 21 6"></polyline>
                                                            <path
                                                                d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                                            <line x1="10" y1="11" x2="10" y2="17"></line>
                                                            <line x1="14" y1="11" x2="14" y2="17"></line>
                                                        </svg>
                                                    </button>
                                                </th>
            
                                                <th class="customer-code sorting">
                                                    <a class=" " tabindex="1"
                                                       href="#">
                                                        Code<span class="float-right mr-1">
             </span>
                                                    </a>
                                                </th>
            
                                            </tr>
                                            <tr class="list-search">
                                                <th class="dt-checkboxes-cell dt-checkboxes-select-all">
                                                    <div class="custom-control custom-checkbox">
                                                        <input class="custom-control-input" type="checkbox" id="checkboxSelectAll"
                                                               tabindex="">
                                                        <label class="custom-control-label" for="checkboxSelectAll"></label>
                                                    </div>
                                                </th>
                                                <th class="customer-code">
                                                    <input class="form-control form-control-sm" type="text" tabindex=""
                                                           placeholder="Search..." name="filter[val][3]" value="">
                                                </th>
                                            </tr>
                                            </thead>
                                            <tbody>
            
                                            <tr class="list-item " data-label="Test user">
            
                                                <td class="dt-checkboxes-cell">
                                                    <div class="custom-control custom-checkbox">
                                                        <input class="custom-control-input dt-checkboxes" type="checkbox" id="4"
                                                               name="id[]" value="4" tabindex="1">
                                                        <label class="custom-control-label" for="4"></label>
                                                    </div>
            
                                                </td>
            
                                                <td class="customer-code"><a class="items-field custom-link"
                                                                             href="#"
                                                                             tabindex="1">demo@example.com</a>
                                                </td>
                                            </tr>
                                            <tr class="list-item " data-label="test@test.com">
            
                                                <td class="dt-checkboxes-cell">
                                                    <div class="custom-control custom-checkbox">
                                                        <input class="custom-control-input dt-checkboxes" type="checkbox" id="2"
                                                               name="id[]" value="2" tabindex="1">
                                                        <label class="custom-control-label" for="2"></label>
                                                    </div>
            
                                                </td>
            
                                                <td class="customer-code"><a class="items-field custom-link"
                                                                             href="#"
                                                                             tabindex="1">test@test.com</a>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
            
                                    </div>
                                </form>
            
            
                            </div>
                        </div>
                    </div>
                </div>
            </div>



How Can I Make field required if checkbox is checked in Android Studio?

I would like to make a 2 Text Box field(Edit Text) required shown if a checkbox is checked and be required. I used this code Check box logic to can checked but I want after I checked 'Recycle Center' then the Text box is shown in so the user can't continue if he doesn't fill the text box. the code below:

`//CheckBox logic

    asRecycleCenter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if(compoundButton.isChecked()){
                asCustomer.setChecked(false); }
        }
    });

    asCustomer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if(compoundButton.isChecked()){
                asRecycleCenter.setChecked(false); }
        }
    });

`




script wont work at least i think its the script

im working with coffee cup form builder and I cant get the scripts to work when i enter them in html mode is it something I'm doing wrong or is it the form builder - after a user selects 2 checkboxes the remainder of the boxes should become unavailable (well that's the ideal scenario) i have listed the html and script I'm using - I hope it helps, thanks robert

<!DOCTYPE HTML>
<html>
  
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="common/js/form_init.js" id="form_init_script"
    data-name="">
    </script>
    <link rel="stylesheet" type="text/css" href="theme/default/css/default.css"
    id="theme" />
    <title>
    </title>
  </head>
  
  <body><style>#docContainer .fb_cond_applied{ display:none; }</style><noscript><style>#docContainer .fb_cond_applied{ display:inline-block; }</style></noscript><form class="fb-toplabel fb-100-item-column selected-object" id="docContainer"
action="" enctype="multipart/form-data" method="POST" novalidate="novalidate"
data-form="preview">
  <div class="fb-form-header" id="fb-form-header1" style="min-height: 0px;">
    <a class="fb-link-logo" id="fb-link-logo1" target="_blank"><img title="Alternative text" class="fb-logo" id="fb-logo1" style="display: none;" alt="Alternative text" src="common/images/image_default.png"/></a>
  </div>
  <div class="section" id="section1">
    <div class="column ui-sortable" id="column1">
      <div class="fb-item fb-three-column fb-100-item-column" id="item1">
        <div class="fb-grouplabel">
          <label id="item1_label_0">Check options</label>
        </div>
        <div class="fb-checkbox">
          <label id="item1_0_label"><input name="checkbox1[]" id="item1_0_checkbox" type="checkbox" data-hint="" value="Check 1" /><span class="fb-fieldlabel" id="item1_0_span">Check 1</span></label>
          <label id="item1_1_label"><input name="checkbox1[]" id="item1_1_checkbox" type="checkbox" value="Check 2" /><span class="fb-fieldlabel" id="item1_1_span">Check 2</span></label>
          <label id="item1_2_label"><input name="checkbox1[]" id="item1_2_checkbox" type="checkbox" value="Check 3" /><span class="fb-fieldlabel" id="item1_2_span">Check 3</span></label>
        </div>
      </div>
      <div class="fb-item fb-100-item-column" id="item2">
        <div class="fb-html">
          <div id="item2_div_0">
            <script>var checks = document.querySelectorAll(".check");
var max = 1;
for (var i = 0; i < checks.length; i++)
  checks[i].onclick = selectiveCheck;
function selectiveCheck (event) {
  var checkedChecks = document.querySelectorAll(".check:checked");
  if (checkedChecks.length >= max + 1)
    return false;
}</script>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="fb-captcha fb-item-alignment-center" id="fb-captcha_control"
  style="display: none; cursor: default;">
    <img src="editordata/images/recaptcharecaptchav2-light.png" />
  </div>
  <div class="fb-item-alignment-left fb-footer" id="fb-submit-button-div"
  style="min-height: 0px;">
    <input class="fb-button-special" id="fb-submit-button" type="submit" data-regular="url('file:///C:/Users/Robert/AppData/Local/Temp/FormBuilder/theme/default/images/btn_submit.png')"
    value="Submit" />
  </div>
</form>
</body>



React Checkboxes conflict in Filter

I have a e-commerce project and filter page. In the filter page I have a few brands with checkbox inputs to filter by brands when checkbox checked. When brands input checked I manipulete the url for saving checked brands in case of page reload like (http://localhost:3000/product-list?categories=2&brands=1,12). My problem is when I checked my brand with id 12, id 1 and id 2 brands also checked.

enter image description here

My checkbox componenet

import React from "react";
import "./CheckBox.style.scss";
import { withRouter } from "react-router-dom";

class CheckBox extends React.Component {
  constructor(props) {
    super(props);
    this.checkboxRef = React.createRef();
  }

  componentDidUpdate(prevProps) {
    if (
      this.props.location.search !== prevProps.location.search &&
      this.checkCategoryChanges(
        this.props.location.search,
        prevProps.location.search
      ) &&

      
      this.checkboxRef.current.checked
    ) {
      this.checkboxRef.current.checked = false;
    }
  }

  checkCategoryChanges(currentUrl, prevUrl) {
    let items =
      currentUrl.charAt(0) === "?"
        ? currentUrl.slice(1).split("&")
        : currentUrl.split("&");

    for (const item of items) {
      if (
        (item.indexOf("categories") !== -1 && prevUrl.indexOf(item) === -1) ||
        (item.indexOf("categories") !== -1 && items.length === 1)
      ) {
        return true;
      }
    }
    return false;
  }

  isChecked() {
    const mainUrlAsArray = window.location.href.split("?");
    if (mainUrlAsArray.length === 2) {
      const url = mainUrlAsArray[1];
      let checkedItems =
        url.charAt(0) === "?" ? url.slice(1).split("&") : url.split("&");

      for (const item of checkedItems) {
        if (
          item.indexOf(this.props.urlKey) !== -1 &&
          item.split("=")[1].indexOf(this.props.value) !== -1 
        ) {
          return true;
        }
      }
      return false;
    }
  }

  runOnChange(e) {
    const checkboxData = {
      value: this.props.value,
      urlKey: this.props.urlKey,
      isChecked: e.target.checked,
      type: this.props.type ? this.props.type : "checkbox",
    };
    this.props.onChange(checkboxData);
  }

  render() {
    return (
      <label className="checkbox-group">
        <input
          ref={this.checkboxRef}
          defaultChecked={this.isChecked() ? true : undefined}
          value={this.props.value}
          onClick={(e) => this.runOnChange(e)}
          type={this.props.type ? this.props.type : "checkbox"}
          className="checkbox"
          name={this.props.name}
        />
        <span className="checkBoxLabel">{this.props.text}</span>
      </label>
    );
  }
}

export default withRouter(CheckBox);



Frontend does not change after calling function that selects all checkboxes in a WPF

I have a problem in a WPF .NET Core 3.1 that I am writing. There is a 'Main Page', where the user can input some filters that will be used to search for some files by an external webAPI; so far so good. The response from the webAPI is an XML with the list of the files available and the user must choose which of these files download. To do so, I have a 'popup box' where the user can read all the available files and selected the desired ones by checkboxes. I have to add some buttons to select / deselect all the files and here lies the problem: the files are selected but the fronted does not notice and keep showing them as unchecked.

In the main page, parsing the XML I generate a List of these objects:

public class righeNoteSpese {
        public Boolean selezionato { get; set; }
        public Boolean isOK { get; set; }
        public String errore { get; set; }
        // Other String fields...

        public righeNoteSpese() {
           selezionato = false;
           isOK = true;
           errore = String.Empty;
        }
    }

and I call the popup with

ListaXML l = new ListaXML(lr);
await this.ShowChildWindowAsync(l.listaXML);

where lr is the list of rows I found.

The code behind of the popup is

public partial class ListaXML : ChildWindow
{
    public List<righeNoteSpese> Elenco = new List<righeNoteSpese>();

    public ListaXML()
    {
        InitializeComponent();
    }

    public ListaXML(List<righeNoteSpese> listF) {
        InitializeComponent();

        this.DataContext = this;
        
        Elenco = listF;
        
        selFiles.ItemsSource = listF;

        /* If not commented the foreach works and all the rows are checked!
        foreach (righeNoteSpese r in Elenco)
        {
            if (r.isOK)
            {
                r.selezionato = true;
            }
        }*/
    }

    private void All_Click(object sender, RoutedEventArgs e)
    {
        foreach (righeNoteSpese r in Elenco) {
            if (r.isOK)
            {
                r.selezionato = true;
            }
        }
    }
}

The XAML of the popup is

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Button Name="Btn1" Width="100" Content="Select All"  Grid.Row="0" Grid.Column="0" Margin="10 15 10 15" Click="All_Click" />
    <DataGrid Name="selFiles" AutoGenerateColumns="False" CanUserAddRows="false" HorizontalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Auto" AlternatingRowBackground="LightGray" Grid.Row="1" Grid.ColumnSpan="4">
        <DataGrid.Columns><DataGridTextColumn Header="Errore" Width="200" Binding="{Binding errore, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding isOK}" Value="False">
                                <Setter Property="Background" Value="Red"/>
                                <Setter Property="FontStyle" Value="Italic" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding selezionato}" Value="True">
                                <Setter Property="Background" Value="SpringGreen"/>
                                <Setter Property="Foreground" Value="Black"/>
                                <Setter Property="FontWeight" Value="Bold"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>

            <DataGridTemplateColumn Width="SizeToHeader" IsReadOnly="True" Header="Select">
                <DataGridTemplateColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding isOK}" Value="False">
                                <Setter Property="Background" Value="Red"/>
                                <Setter Property="FontStyle" Value="Italic" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding selezionato}" Value="True">
                                <Setter Property="Background" Value="SpringGreen"/>
                                <Setter Property="Foreground" Value="Black"/>
                                <Setter Property="FontWeight" Value="Bold"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGridTemplateColumn.CellStyle>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding selezionato, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="2,0,2,0" IsEnabled="{Binding isOK, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <!-- Other columns... -->

        </DataGrid.Columns>
    </DataGrid>


</Grid>

If I check manually a checkbox everything works, the background changes and the change is passed back to the main page. If I use the button the values are changed and passed back to the main page but there is no change in the frontend but if I execute these same instructions when I call the page everything is OK. What am I missing? Thank you for your help.




Is there any way to check only the required checkboxes?

I am trying to only select limited items which has DOM as below:

Account

For selecting all the items, I used following code:

it('Select all items', ()=>{
    cy.get('#WallTransportationModeId').select('Wallbee-Road')
    cy.get(':nth-child(n) > .checkbox-wrap > .wb-checkbox > label').click({ multiple: true, force: true })
    cy.get('#btn-save-transportation-layout-setup').click()
  
})
   

All the items are selected as well. But now I need to only select 10 first items.




Java PDFBox - How to know if a radio button or a checkbox is checked?

I would like to extract data from a PDF form. I saw that PDFBox can do that but is it possible to get a radio button/checkbox value ? Or does it work only with text field ?

Thanks !




jeudi 25 mars 2021

How to loop through check boxes and assign enumeration values when boxes are checked?

I have a group of check boxes, to be precise there are 3 boxes. It works for me when using if statement but I wonder there is a way to loop through check boxes and assign enumeration values when a box is checked or more.

The code looks like this:

if (chkTomato.Checked && !chkLettuce.Checked && !chkCarrot.Checked)
{
    cart.VegChosen = Veggies.Tomato;
}
else if (!chkTomato.Checked && chkLecctuce.Checked && !chkCarrot.Checked)
{
    cart.VegChosen = Veggies.Lecctuce;
}
else if (!chkTomato.Checked && !chkLecctuce.Checked && chkCarrot.Checked)
{
    cart.VegChosen = Veggies.Carrot;
}
else if (chkTomato.Checked && chkLettuce.Checked && chkCarrot.Checked)
{
    cart.VegChosen = Veggies.All;
}
else if (chkTomato.Checked && chkLettuce.Checked && !chkCarrot.Checked)
{
    cart.VegChosen = Veggies.TomatoAndLettuce;
}
else if (chkTomato.Checked && !chkLettuce.Checked && chkCarrot.Checked)
{
    cart.VegChosen = Veggies.TomatoAndCarrot;
}
else if (!chkTomato.Checked && chkLettuce.Checked && chkCarrot.Checked)
{
    cart.VegChosen = Veggies.LettuceAndCarrot;
}
else
{
    cart.VegChosen = Veggies.None;
}

I want to find out a way to loop it in case there are more than just 3 check boxes, the if statement would be very long.

Thank you!




How submit values from multiple checkboxes and send mutation with useMutation Apollo client

I am using useMutation hook from Apollo Client

Currently on my mapped buttons after pressing the button my mutation is fired off and works all fine.

const MyComponent = ({ myId, selections }: Props) => {
  const [addTodo] = useMutation(ADD_TODO);

  return (
    <div>
      <ul>
        {todos.map(({ id, label }) => (
          <li key={id}>
            <button
              type="button"
              onClick={() => {
                addTodo({
                  variables: {
                    myId,
                    toId: id,
                  },
                  refetchQueries: [{ query: anotherQuery, variables: { myId } }],
                });
              }}
            >
              {label}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
};

Now I have to change my buttons into checkboxes (since the user can submit/mutate multiple values). When submitting the form <form onSubmit={(e) => {}} I have to submit my mutation addTodo (with one or more selected values.

How do I collect all selected values and pass them to my form onClick handler?




mercredi 24 mars 2021

Doesn't JavaScript button onClick event when you get a global variable?

I made a simple click event. But if I use js dom to make it a global variable, it doesn't seem to work. Is there a genius here who can explain the reason easily to me?

This is html file very very simple!

 <form>
      <input type="radio" name="a" id="ck1" /> 수신동의
      <input type="radio" name="a" id="ck2" /> 수신차단
      <input type="button" value="서비스 등록" onclick="checkHandle()" />
 </form>

This is JS file.

let ck1 = document.getElementById("ck1").checked;
let ck2 = document.getElementById("ck2").checked;
function checkHandle() {
  console.log(ck1);
  if (ck1 === false && ck2 === false) {
    alert("광고 수신 동의에 대해 선택해주세요.");
  } else {
    alert("서비스를 등록합니다.");
  }
}

or

function checkHandle() {
let ck1 = document.getElementById("ck1").checked;
let ck2 = document.getElementById("ck2").checked;
  console.log(ck1);
  if (ck1 === false && ck2 === false) {
    alert("광고 수신 동의에 대해 선택해주세요.");
  } else {
    alert("서비스를 등록합니다.");
  }
}

To be exact again what I want to say, I would like to ask you why declaring the ck1, ck2 variable declaration within the checkHandle function is different from declaring it as a global variable. Please explain it easily.

For your information, it didn't work properly when I declared it a global variable.




mat checkbox inside scrollable div causing issue

I have mat checkboxes inside a scrollable div. When scrolling the div the check boxes are not rendering properly. If the focus is removed from the div the checkboxes are appearing fine.

Here is the sample of the problem: mat-checkbox issue




MFC Tri-state CheckBox — how to change the order of the states?

How to change the order of tri-state MFC CheckBox control?

Now when I click it has the followins states order: BST_INDETERMINATE > BST_UNCHECKED > BST_CHECKED > cycle

But I need the following: BST_INDETERMINATE > BST_CHECKED > BST_UNCHECKED > cycle




checkboxes implementation in grid view in unqork platform

How to add checkboxes in grid view in unqork platform can anybody help on this




mardi 23 mars 2021

Stop CheckBox moving when changing text

I have a WinForms project that has several CheckBoxes with the text to the left of the tick box.

I have to change the text of some of them at runtime, but annoyingly the tick box moves when I do this.

I've tried changing various alignment options, but haven't found the right one yet. Any ideas? Thanks.




Selection of products priced with checkbox Jquery

I'm in a form... I need an intelligent control in Jquery for add and subtract the value of the checkboxes to dinamically have the total after every check or uncheck. Sorry form my english.. thank you

 <!-- checkboxes -->
                        <div class="form-check custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="form-check-input custom-control-input" data-validation-required-message="Campo obbligatorio" id="maglia" value=10>
                            <label class="custom-control-label" style="color:black" for="maglia">....</label>
                        </div>
                        <div class="form-check custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="form-check-input custom-control-input" data-validation-required-message="Campo obbligatorio" id="short" value=10>
                            <label class="custom-control-label" style="color:black" for="short">....</label>
                        </div>
                        <div class="form-check custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="form-check-input custom-control-input" data-validation-required-message="Campo obbligatorio" id="calzettoni" value=10>
                            <label class="custom-control-label" style="color:black" for="calzettoni">...</label>
                        </div>
                        <div class="form-check custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="form-check-input custom-control-input" data-validation-required-message="Campo obbligatorio" id="pinocchietti" value=10>
                            <label class="custom-control-label" style="color:black" for="pinocchietti">..../label>
                        </div>
                        <div class="form-check custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="form-check-input custom-control-input" data-validation-required-message="Campo obbligatorio" id="kway" value=10>
                            <label class="custom-control-label" style="color:black" for="kway">...</label>
                        </div>
                        <!-- / checkboxes -->
                    </div>
                    <div class="col-md-6 mb-2">
                        <div class="form-group">
                            <p>Totale : <input type="text" value=0 readonly id="totale"> € </p>
                            <input type="hidden" value="Sacchetta porta kit" id="capo">
                        </div>
                    </div>



How to make an if..else statement that will return true if your checkbox is being clicked?

I recently having a problem with this if else statement

So both have a specific id name which is "premium" and "regular"

I wanted to make an if else statement using jquery that will return able my input's

Here is what my checkbox need to do,

  • if my checkbox is being checked I wanted the input to be enabled
  • else nothing happen because it is already disabled.
$("#PreCap").prop('disabled', true);
$("#PreA").prop('disabled', true);

$("#RegCap").prop('disabled', true);
$("#RegA").prop('disabled', true);


//var premium = document.querySelector("#premium").checked;
// var regular = document.getElementById("regular");

$('#premium').val();

if ($("#premium").is(":checked")) {
  $("#PreCap").prop('disabled', false);
  $("#PreA").prop('disabled', false);
} else if (regular.checked === true) {
  document.getElementById("RegCap").disabled = false;
  document.getElementById("RegA").disabled = false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="form-check-input" id="premium">
<label class="form-check-label" type="checkbox" for="premium">Premium Air Conditioner</label>
<input type="number" id="PreCap" class="form-control" placeholder="Seat Capacity">

<input type="checkbox" class="form-check-input" id="regular">
<label class="form-check-label" type="checkbox" for="regular">Regular Air conditioner</label>
<input type="number" id="RegCap" class="form-control" placeholder="Seat Capacity">

Note: I am using bootstrap 5 and jquery-3.5.1.min.js




Loop through all unchecked Checkboxes (foreach or for-loop, Windows Forms)

I would like to compress the executable code segment (see below). How to do this with a foreach or for-loop?

private void UncheckCheckBox() 
{
   CheckBox[] Three = new [] 
   {
     checkBox1,
     checkBox2,
     checkBox3
   };

   checkBox1.Tag = "str1";
   checkBox2.Tag = "str2";
   checkBox3.Tag = "str3";

   if (!checkBox1.Checked) 
   {
     listBox4.Items.Remove(checkBox1.Tag);
   }
   if (!checkBox2.Checked) 
   {
     listBox4.Items.Remove(checkBox2.Tag);
   }
   if (!checkBox3.Checked) 
   {
     listBox4.Items.Remove(checkBox3.Tag);
   }
}



lundi 22 mars 2021

two checkbox and if else condition redirect to another page

I am using react js and I am looking for function that handle the checkboxes and if first checkbox is checked it will go to specific page. else if the second checkbox is checked it will redirect to another page. Anyone have idea? this is my code

<h4>Do you study in the weekend? </h4>
         <MDBCol md="4" className="mb-3">
            <div className="custom-control custom-checkbox pl-3">
              <input
                className="custom-control-input"
                type="checkbox"
                value=""
                id="yes"
                required
                checkCheckBox = {this.handleCheckBox}
                

              />
              <label className="custom-control-label" htmlFor="yes">
Yes </label>        
            </div>
          </MDBCol>

          <MDBCol md="4" className="mb-3">
            <div className="custom-control custom-checkbox pl-3">
              <input
                className="custom-control-input"
                type="checkbox"
                value=""
                id="no"
                required
                checkCheckBox = {this.handleCheckBox}

              />
              <label className="custom-control-label" htmlFor="no">
No</label>        
            </div>
          </MDBCol>



Bokeh, python callback in CustomJS issue

I use Bokeh to be able to modify my figure with checkboxes. This code makes appear a figure hbar, and the checkbox modified the number of date represented. (the number of color per bar) (see Figure). My code works but I would like to use a callback with CustumJS and not in python to save my html. But I can't write the callback in Java, can you help me?

Thanks :)

import pandas as pd
from bokeh.layouts import column, grid, row
from bokeh.models import (Button, CheckboxGroup, ColumnDataSource, CustomJS,
                          Grid, HoverTool, LabelSet, Legend, LegendItem
from bokeh.plotting import ColumnDataSource, curdoc, figure, output_file, show
from bokeh.transform import stack
from matplotlib import pyplot as plt

output_file("stacked.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
LABEL = ["2015", "2016", "2017"]
C = ["#c9d9d3", "#718dbf", "#e84d60"]

data = {'2015': [2, 1, 4, 3, 2, 4],
        '2016': [5, 3, 4, 2, 4, 6],
        '2017': [3, 2, 4, 4, 5, 3]}
df = pd.DataFrame(data=data)
df.index = fruits
source = ColumnDataSource(df)

p = figure(plot_width=800, plot_height=400,
           y_range=list(df.index.drop_duplicates().tolist()))
renderers = []
col_acc = []
legend = []
for col in LABEL:
    r = p.hbar(y='index', left=stack(*col_acc), right=stack(col, *col_acc),
               height=0.9, color=C[int(LABEL.index(col))], source=source)
    col_acc.append(col)
    renderers.append(r)
    print(r, col, col_acc, stack(*col_acc))

legend_items = [LegendItem(label=LABEL[i], renderers=[renderers[i]])
                for i in range(len(LABEL))]
p.add_layout(Legend(items=legend_items), 'right')

checkbox_group = CheckboxGroup(labels=LABEL, active=list(range(len(LABEL))))


def update_plot(new):
    Col_a = []
    for i in range(len(LABEL)):
        if i in new:
            renderers[i].visible = True
            renderers[i].glyph.left = stack(*Col_a)
            renderers[i].glyph.right = stack(LABEL[i], *Col_a)
            Col_a.append(LABEL[i])
        else:
            renderers[i].visible = False
    p.legend.items = [legend_items[i] for i in checkbox_group.active]


checkbox_group.on_click(update_plot)

group = column(checkbox_group, p)
layout = row(group)
curdoc().add_root(layout)
show(layout)

enter image description here




Copy range and paste it to another Spreadsheet using checkbox as trigger

I am a begginer in this and I don't understand what's the problem with my code. I pretend to move row by row to another SpreadSheet when the user clic the checkbox used as trigger onEdit().

function onEdit(e){

    var range = e.range;
  //Source sheet
    var ss = e.source;
    var sn = ss.getActiveSheet().getName();
  //Destination sheet
  var es = SpreadsheetApp.openById('GoogleSheetID');
  var csh = es.getSheetByName('SheetName');
  
  //Aprobación
  var move = range.offset(0,-2).getValue(); //It's a column that have the value approved/rejected

    if(move == "Approved" && sn == 'SheetName' && e.value == "TRUE"){
    var abc = ss.getRange(2,5,1,12).getValues();
  //Copy matched ROW numbers to j
  j.push(1);
  csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(abc);
    }
}

Thank you for your help!




dimanche 21 mars 2021

Warning: You provided a `checked` prop to a form field without an `onChange` handler

I'm getting this warning with my JS React code.

Warning: You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly.

My code is working exactly as intended, so the warning isn't causing any functionality issues, but still, I'd like to resolve it.

Here's my code:

<View style=>
  <View style=>
    <Form.Group>
      <Form.Label>Availability</Form.Label>
      <div onChange={ (e) => this.handleInput(e, "listing")}>
        <Form.Check checked={(this.state.listing.availability === "募集中")} type="radio" value="募集中" name="availability" label="募集中"/>
        <Form.Check checked={(this.state.listing.availability === "契約済")} type="radio" value="契約済" name="availability" label="契約済"/>
      </div>
    </Form.Group>
  </View>
  <View style=>
    <Form.Group>
      <Form.Label>Property Type</Form.Label>
      <div onChange={ (e) => this.handleInput(e, "property")}>
        <Form.Check checked={(this.state.property.property_type === "一戸建て")} type="radio" value="一戸建て" name="property_type" label="一戸建て"/>
        <Form.Check checked={(this.state.property.property_type === "アパート")} type="radio" value="アパート" name="property_type" label="アパート"/>
      </div>
    </Form.Group>
  </View>
  <View style=>
    <Form.Group>
      <Form.Label>Interest</Form.Label>
      <div onChange={ (e) => this.handleInput(e, "property")}>
        <Form.Check checked={(this.state.property.interest === "Extremely")} type="radio" value="Extremely" name="interest" label="Extremely"/>
        <Form.Check checked={(this.state.property.interest === "Kinda")} type="radio" value="Kinda" name="interest" label="Kinda"/>
        <Form.Check checked={(this.state.property.interest === "Nah")} type="radio" value="Nah" name="interest" label="Nah"/>
      </div>
    </Form.Group>
  </View>
 </View>

I have certain reasons for formatting things this way, but I'm totally open to suggests. Really, I just want get rid of the warning with changing this code as little as possible.

I saw there were other questions addressing this issue, but I couldn't find a solution that works with my code.




Blocking a series of checkboxes with Jquery

I have a web page that can contain several series of checkboxes. I want to limit the number of possible checkboxes for each of these series. PS: Some checkboxes can already be checked when the page is loaded depending on what the user has clicked during his previous visits.

Currently, the code I have is not efficient because it takes all the checkboxes of the whole page and on top of that, it acts only after checking a checkbox. This means that the user can select more and more checkboxes.

As you can see in the code, there can be multiple form, so multiple row of checkbox, each one is independ from the other one.

Thanks for your purpose !

<form id="<?php echo $id_apps; ?>_form">
                <span class="nav-link-inner--text"> APP1:
                <label class="custom-toggle">
                    <input type="checkbox" id="<?php echo $id_apps; ?>_checkbox_APP1" <?php if($APP1_choice == "yes") { echo 'checked';}?> >
                    <span class="custom-toggle-slider rounded-circle" label="APP1" data-label-off="No" data-label-on="Yes"></span>
                </label>
                </span><br>
                <span class="nav-link-inner--text"> APP2:
                    <label class="custom-toggle">
                        <input type="checkbox" id="<?php echo $id_apps; ?>_checkbox_APP2" <?php if($APP2_choice == "yes") { echo 'checked';}?> >
                        <span class="custom-toggle-slider rounded-circle" label="APP2" data-label-off="No" data-label-on="Yes"></span>
                    </label>
                </span><br>
...
....

...

// Same thing with another id_apps

<form id="<?php echo $id_apps; ?>_form">
                <span class="nav-link-inner--text"> APP1:
                <label class="custom-toggle">
                    <input type="checkbox" id="<?php echo $id_apps; ?>_checkbox_APP1" <?php if($APP1_choice == "yes") { echo 'checked';}?> >
                    <span class="custom-toggle-slider rounded-circle" label="APP1" data-label-off="No" data-label-on="Yes"></span>
                </label>
                </span><br>
                <span class="nav-link-inner--text"> APP2:
                    <label class="custom-toggle">
                        <input type="checkbox" id="<?php echo $id_apps; ?>_checkbox_APP2" <?php if($APP2_choice == "yes") { echo 'checked';}?> >
                        <span class="custom-toggle-slider rounded-circle" label="APP2" data-label-off="No" data-label-on="Yes"></span>
                    </label>
                </span><br>
...
....

<script>


var max_limit = "<?php echo $nbr_apps; ?>"; // This is the limit of checkbox that comes from php, each form comes with a limit
$(document).ready(function (){
    $("input:checkbox").click(function() {
    var bol = $("input:checkbox:checked").length >= max_limit;     
    $("input:checkbox").not(":checked").attr("disabled",bol);
    });
});
</script>



Text within Checkbox is not updated with localized String

I'm seeing a strange bug with my android application, where I've a checkbox which is associated with a dialog (ie' which shows up in UI as part of dialog).

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical"
              >
    <FrameLayout
        android:layout_width="@dimen/dialog_width"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/checkbox1"            
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="?android:attr/textColorPrimary"
            android:button="@null"
            android:text="@string/textcontent"
            android:textSize="@dimen/checkbox_text_size"
            android:layout_gravity="end|center_vertical"
            android:gravity="end"/>
    </FrameLayout>
</LinearLayout>

When the language is set as Japanese ie' when the locale is set to JP - the jp resource corresponding to the string is not shown in UI.

Note: Tried debugging this issue with UIAutomatorViewer - I could see the japanese value for the string textcontent is replaced within the layout - but the value seen on the screen is english. I'm not sure why this discrepancy is observed.

Some help here would be appreciated !!




Get value checkbox from datagrid

How can i get some data like a data to checkbox but from column gender in datagrid ? Etc. Datagrid show Name : Andi Address : Jakarta Gender : Male (result input from checkbox)




samedi 20 mars 2021

Jquery - How do you get checkbox values from closest parent only?

I am working on a school assignment and we are starting to learn Jquery

I am looking to collect the values from a set of check boxes but only the ones that fall within the div that the button that triggers the function is contained within.

So far I have been able to get the values, but if any of the boxes are checked in the other divs those values are added as well because they need to all share the same name. I am trying to avoid duplicating code.

This is my Jquery code:

$(document).ready(function() {
    $('button').on('click', function() {
        var destination = $(this).closest('.destinations'); //this selects the div the button is in but I can't figure out how to apply it to the checkbox value gathering
        var base_price = $(destination).find('.base_price').text();
        var add_ons = [];
        $.each($("input[name='add_on']:checked"), function(){ //I player around with using the variable destination somewhere here but am thinking there needs to be another step
            add_ons.push($(this).val());
        });
        $(this).remove();
        console.log(base_price)
        console.dir(add_ons) //the values are successfully added but I can't figure out how to isolate based on the the variable 'destination'
        });
    });

Any assistance will be greatly appreciated




Loop Foreach PHP With Specific Separator From Checkbox

can you help me

I have output like this

enter image description here

I want the output like this

enter image description here

This my script

$p_modules = $_POST['modules'];
$total_modules = count($p_modules);

$i = 0;
$module_name = "";

foreach($p_modules as $modules) {
    $i++;

    $exp_module = explode("-", $modules);

    if(count($exp_module) == 1) {
        $module_name .= ($total_modules != $i) ? $modules.", " : $modules."";
    }
    else {
        list($main_module, $sub_module) = $exp_module;

        if($total_modules != $i) {
            $module_name .= $modules.";";
        }
        else {
            $module_name .= $modules."";
        }
    }
}

echo json_encode(array("success"=>true, "desc"=>$module_name));

My output :
meals-transaction;meals-order;meals-manage_orders;meals-report;meals_order, employees, modules, user-profile;user-change_password;user-logout;tes

I want :
meals-transaction;meals-order;meals-manage_orders;meals-report, meals_order, employees, modules, user-profile;user-change_password;user-logout, tes

Any tricks to make it?

Many Thanks!




Print the name of a checkbox in ion-textarea if checked. on IONIC

im trying to print the name of checked checkboxes in an ion-texarea. The app ask for the name, the genre(masculine, femenine) and description(tall, small, smart, ugly, etc.), at the bottom there's an ion-textarea to print a sentence like, Name is a genre and She/He is description of checked checkboxes. ex. John is a Man and he is Tall, Smart, and Ugly.

Image of the App

the html code i have is:

<ion-item>
      <ion-label color="primary">Genre</ion-label>
      <ion-list>
        <ion-item *ngFor="let genre of genre"> 
          <ion-label></ion-label>
          <ion-checkbox slot="end" [(ngModel)]="genre.isChecked"></ion-checkbox>
        </ion-item>
      </ion-list>
    </ion-item>
    <ion-list-header>
    <ion-label color="primary">Descripcion</ion-label>
  </ion-list-header>
 
<div>
  <ion-col><ion-button expand="full"  (click)="gen(); result()" >Criticar</ion-button></ion-col>
  <ion-textarea [ngModel]="critica"></ion-textarea>
</div>

the typescript code is:

export class HomePage {
nombre:string;
genero:any;
critica:any;

genre: any=[
    {name:'Masculino', isChecked: false},
    {name:'Femenino', isChecked: false}
];

gen(){
    this.genero=this.genre.filter(value => {return value.isChecked});

  result(){
    this.critica = this.genero;



How to initialize radiogroup when v-radio is active and disabled

i’m using vuetify and vue js 2.6 I have one v-radio-group which contain 5 v-radio and i have 2 v-checkbox, i use those checkboxes to enable/disable radioboxes: 1- Problem one : How to initialise v-radio-group when one of the radioboxes is disabled and active. 2- i want to toggle the Checkboxes, just one of the two should be checked and not both

I appreciate every help and respond to my request thanks… hier is the code:

<template>
  <div> 
    <v-radio-group v-model="radiogroup">
      <v-radio label="Radio 1" value="radio1"></v-radio>
      <v-radio label= "Radio 2"value="radio2"></v-radio>
      <v-radio
        label="Radio 3"
        value="radio3"
        :disabled="check2 || check1"
      ></v-radio>
      <v-radio
        label="Radio 4"
        value="radio4"
        :disabled="check2"
      ></v-radio>
      <v-radio
        label="Radio 5"
        value="radio5"
        :disabled="disableradio"
      ></v-radio>
    </v-radio-group>
    <v-checkbox label="Check 2" v-model="check2"></v-checkbox>
    <v-checkbox label="Check 1" v-model="check1"></v-checkbox>
  </div>
</template>
<script>
export default {
  data() {
    return {
      disableradio: true,
      check1: false,
      check2: false,
      radiogroup: "radio1",
      },
    },
};
</script>



JQuery script to total values from input boxes, checkboxes and option values from select element

I'm trying to write what I think must be a simple JQuery script to display a running sum total of options selected by a user in an order form. I have assigned values to all the checkboxes, radio buttons and option values from my drop downs and now want to display the sum total in a div so a user can see the total.

Image of input form

Here is the form code:

<form class="input-form" name="textinput" id="input_form" method="POST">
  <table id="formtable">
    <tr id="mainrow">
      <td id="inputcell">
        <label for="propertyaddress">Covered Property Address</label>
        <input type="text" id="propertyaddress" name="propertyaddress" required>
        <label for="mailingaddress">Mailing Address (If Different)</label>
        <input type="text" id="mailingaddress" name="mailingaddress">
        <label for="buyername">Buyer Name(s)</label>
        <input type="text" id="buyername" name="buyername" required>
        <label for="buyeremail">Buyer Email Address</label><br>
        <input type="text" id="buyeremail" name="buyeremail" required><br>
        <label for="buyerphone">Buyer Phone</label><br>
        <input type="text" id="buyerphone" name="buyerphone"><br>
        <label for="titlecompany">Title Company</label><br>
        <input type="text" id="titlecompany" name="titlecompany"><br>
        <label for="escrowofficer">Escrow Officer Name</label><br>
        <input type="text" id="escrowofficer" name="escrowofficer"><br>
        <label for="escrowofficeremail">Escrow Officer Email Address</label><br>
        <input type="text" id="escrowofficeremail" name="escrowofficeremail"><br>
        <label for="escrowofficerphone">Escrow Officer Phone</label><br>
        <input type="text" id="escrowofficerphone" name="escrowofficerphone"><br>
        <label for="referringagent">Agent Name and Agency</label><br>
        <input type="text" id="referringagent" name="referringagent" required><br>
        <label for="referringagentphone">Agent Phone</label><br>
        <input type="text" id="referringagentphone" name="referringagentphone" required><br>
        <label for="referringagentemail">Agent Email Address</label><br>
        <input type="text" id="referringagentemail" name="referringagentemail" required><br>
      </td>

      <td id="radiocell">
        <table>
          <tr>
            <td class="centercolumntd">
              <label for="closingdate"><u>Closing Date</u></label><br>
              <input type="date" id="closingdate" name="closingdate" required><br><br>
              <label for="hometype"><u>Type of Home</u></label><br><br>
              <input type="radio" id="Single Family" name="hometype" value="singlefamily" required><label for="Single Family">Single Family</label><br>
              <input type="radio" id="Townhome/Condo/Mobile Home" name="hometype" value="towncondomobile"><label for="Townhome/Condo/Mobile Home">Townhome/Condo/Mobile Home</label><br>
              <select form="input_form" name="multitype" id="duplex_triplex_fourplex" value="Multi-Flat Warranty Options" class="selectboxes">
                <option value="" selected disabled hidden>Duplex/Triplex/Fourplex</option>
                <option value="duplex_gold">Duplex Gold - $720</option>
                <option value="duplex_platinum">Duplex Platinum - $855</option>
                <option value="duplex_diamond">Duplex Diamond - $945</option>
                <option value="triplex_gold">Triplex Gold - $1040</option>
                <option value="triplex_platinum">Triplex Platinum - $1235</option>
                <option value="triplex_gold">Triplex Diamond - $1365</option>
                <option value="triplex_gold">Fourplex Gold - $1360</option>
                <option value="triplex_platinum">Fourplex Platinum - $1615</option>
                <option value="triplex_gold">Fourplex Diamond - $1785</option>
              </select>


            </td>
            <td class="centercolumntd">
              <label for="warrantytype"><u>Select Warranty Type</u></label><br>
              <input type="radio" id="Gold" name="warrantytype" value="400" required><label for="Gold">Gold - $400</label><br>
              <input type="radio" id="Platinum" name="warrantytype" value="475"><label for="Platinum">Platinum - $475</label><br>
              <input type="radio" id="Diamond" name="warrantytype" value="525"><label for="Diamond">Diamond - $525</label><br>
              <input type="radio" id="Sellers" name="warrantytype" value="Sellers"><label for="Sellers" value="0">Sellers Warranty - $0</label><br>
              <select form="input_form" name="multiyear" id="multiyear" value="Multi Year Warranties" class="selectboxes">
                <option value="0" selected disabled hidden>Multi-Year Warranties</option>
                <option value="760" id="2yr_Gold">2yr. Gold Warranty - $760</option>
                <option value="1120" id="3yr_Gold">3yr. Gold Warranty - $1120</option>
                <option value="903" id="2yr_Platinum">2yr. Platinum Warranty - $903</option>
                <option value="1330" id="3yr_Platinum">3yr. Platinum Warranty - $1330</option>
                <option value="998" id="2yr_Diamond">2yr. Diamond Warranty - $998</option>
                <option value="1470" id="3yr_Diamond">3yr. Diamond Warranty - $1470</option>
              </select>
              <select form="input_form" name="newconstruction" id="newconstruction" value="New Construction Warranties" class="selectboxes">
                <option value="" selected disabled hidden>New Construction Warranties</option>
                <option value="400" id="2yr_nc_gold">2yr. Gold New Constr. - $400</option>
                <option value="520" id "3yr_nc_gold">3yr. Gold New Constr. - $520</option>
                <option value="660" id="4yr_nc_gold">4yr. Gold New Cons"tr. - $660</option>
                <option value="475" id="2yr_nc_plat">2yr. Platinum New Constr. - $475</option>
                <option value="618" id="3yr_nc_plat">3yr. Platinum New Constr. - $618</option>
                <option value="784" id="4yr_nc_plat">4yr. Platinum New Constr. - $784</option>
                <option value="525" id="2yr_nc_diam">2yr. Diamond New Constr. - $525</option>
                <option value="683" id="3yr_nc_diam">3yr. Diamond New Constr. - $683</option>
                <option value="866" id="4yr_nc_diam">4yr. Diamond New Constr. - $866</option>
              </select><br>

            </td>
          </tr>
        </table>

        <label for="warrantynotes"><u>Warranty Notes - Any instructions or information about the order or payment arrangements</u></label><br>
        <input type="text" id="notes" name="warrantynotes"><br><br>

        <label for="options"><u>Options</u></label><br>

        <div class="warranty_option_container">
          <div class="wty_option_child">
            <input type="checkbox" id="greenplus" name="optiontype[]" value="70"><label for="greenplus">$70 Green Plus</label><br>
            <input type="checkbox" id="termite" name="optiontype[]" value="75"><label for="termite">$75 Subterranean Termite Treatment</label><br>
            <input type="checkbox" id="freezer" name="optiontype[]" value="50"><label for="freezer">$50 Freezer-Standalone</label><br>
            <input type="checkbox" id="wetbar" name="optiontype[]" value="25"><label for="wetbar">$25 Wet Bar Refrigerator/2nd Fridge</label><br>
            <input type="checkbox" id="poolspa" name="optiontype[]" value="150"><label for="poolspa">$150 Pool/Spa Combo</label><br>
            <input type="checkbox" id="addpoolspa" name="optiontype[]" value="150"><label for="addpoolspa">$150 Additional Pool or Spa</label>
          </div>

          <div class="wty_option_child">
            <input type="checkbox" id="saltpool" name="optiontype[]" value="300"><label for="saltpool">$300 Salt Water Pool w/Spa Combo</label><br>
            <input type="checkbox" id="wellpump" name="optiontype[]" value="100"><label for="wellpump">$100 Well Pump</label><br>
            <input type="checkbox" id="septicpump" name="optiontype[]" value="75"><label for="septicpump">$75 Septic /Ejector Pump/Tank Pumping</label><br>
            <input type="checkbox" id="waterline" name="optiontype[]" value="90"><label for="waterline">$90 External Water Line Repair</label><br>
            <input type="checkbox" id="waterlineandsewer" name="optiontype[]" value="195"><label for="waterlineandsewer">$195 External Water/Sewer Line Repair</label><br><br>
          </div>
        </div><br>

        <div class="warranty_option_container">
          <div class="wty_option_child" id="wty_option_child1">
            <h2>Warranty Total:</h2>
          </div>
          <div class="wty_option_child" id="wty_option_child2">
            <h2></h2>
          </div>
        </div>



checkbox jquery using ajax to send data and save in php not inserting

I tried to serialize rather to push the elements value but still I get the array with inserting each value 9 times in database. please anyone to help me figure out my problem this is what I am trying to

The HTML:

    <form name="chkl" id="chkl" method="post">  
                
<input type="checkbox" class="get_value" name="chk1[ ]" value="<?php echo $rows['ID'];?>">&nbsp<?php echo $rows['DESCRIPTION'];?></input><br>

<input type="submit" name="Submit" id="chk1" value="Submit"> 

JS:

<script>
 $('#chk1').click(function(){  
$('input[type=checkbox]').each( function() {
          $.post('fee_checked_save.php', $( ".get_value" ).serialize(), function(data){
          if(data == 1){
             $('#result').html(data);  
          }
      });
});
});
</script>

PHP:

<?php  
    
  $checkbox1 = $_POST['chk1'];
    if(isset($_POST['chk1']))  
    {  
    for ($i=0; $i<count ($checkbox1);$i++) {  
    $query = "INSERT INTO fee_checked(FEE_ID) VALUES ('".$checkbox1[$i]. "')";  
   $result = mysqli_query($conn, $query);
    }  
    echo "Record is inserted";  
    }  
    ?>  

Any help would be greatly appreciated. Thanks ahead of time!




vendredi 19 mars 2021

Select multiple options in checkboxes in Streamlit

I am new to Streamlit. I want to make a multiple-choice user input (checkboxes). But I want to select a maximum of 3 options out of 4 options.

I have tried with the dropdown feature of multiselect.

import streamlit as st
option = st.multiselect('Select three known variables:', ['initial velocity (u)', 'final velocity (v)', 'acceleration (a)', 'time (t)'])  

It works. But I think it won't be user-friendly for my case. Also, here I couldn't limit the selections to 3 out of 4. The user can select all 4 options here. But I want the code such that if the 4th one is selected, the previous selection (3rd option) will be automatically un-selected. I prefer the looks of the checkboxes such as the radio buttons:

import streamlit as st
option = st.radio('Select three known variables:', ['initial velocity (u)', 'final velocity (v)', 'acceleration (a)', 'time (t)'])  

But using radio, I can't select multiple options. How can I edit it such that I can display it as checkboxes and only 3 options can be selected?




JS checkbox and text

in this code i can only use Checkbox but when i use text input i do not get any response

https://pastebin.com/sYEnkM9h

in this line

     $("input[type=checkbox]:checked").each(function(index,element){
                checkarr.push($(element).val());
            });



Vba - Checkbox Issue

I have sheet named "Reference & Joins" where All Column ("A") data are autofilltered to Column E then filtered data are copied to another Colmun (Column F) So the check box on the other sheet is checked or unchecked based on F2 Cell value of the other sheet

Problems i face are as below notes and snpahsot from the error

  1. Check box is not check automatically untill i delete the related Cell value manually and copy the desired data manually

  2. debug message as below snapshot while deleting data from this cell or resetting data

  3. also how to edit check box code in the sheet module to add another check box located in the same sheet

enter image description here

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
  
 Dim CheckDest As Worksheet
 Set CheckDest = ThisWorkbook.Worksheets("BSS Mobile MainPage")

  If Not Intersect(Target, Range("F2")) Is Nothing Then
    If Target.Value = "Scratch Cards" Then
       CheckDest.CheckBoxes("Rwa").Value = True
    Else
       CheckDest.CheckBoxes("Rwa").Value = False
    End If
  End If
End Sub



Submit checkbox form in WordPress

I have a PHP checkbox form to send to WordPress after a submit button

But I don't know how to go about it, do you have a clue to enlighten me?

Thanks you.

Form

<div class="container mt64">
<?php
    $active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
    if (in_array( 'interparking_marketing_questions/interparking_marketing_questions.php', $active_plugins)) :
        ?>
        <div class="marketing_bloc bloc-checkout grey-background p-3 mb-4">
            <div class="form-group titre-white align-items-center d-flex justify-content-between align-content-between pr-3 pl-3 pt-2 pb-2"><h2 class="title2"><?php echo __("Aidez-nous à mieux vous servir","interparking_aeroparker_offers"); ?></h2></div>
            <?php echo do_shortcode("[interparking_marketing_questions]"); ?>
            <div class="form-row">
                <div class="col-sm-12 md-checkbox">
                    <input id="consent_newsletter_interparking_1" type="checkbox" name="consent_newsletter_interparking_1" class="consent_newsletter_ipk_action">
                    <label for="consent_newsletter_interparking_1"><?php echo __("J'accepte de recevoir les offres marketing d'Interparking","interparking_aeroparker_offers") ?></label>
                </div>
                <div class="col-sm-12 md-checkbox">
                    <input id="consent_newsletter_partners_1" type="checkbox" name="consent_newsletter_partners_1" class="consent_newsletter_partners_action">
                    <label for="consent_newsletter_partners_1"><?php echo __("J'accepte de recevoir les offres marketing des partenaires d'interparking","interparking_aeroparker_offers") ?></label>
                </div>
            </div>
        </div>
        <div class="d-flex justify-content-start"><button class="btn-research"><?php echo __("Envoyer mes réponses","interparking_aeroparker_offers") ?></button></div>
<?php endif; ?>
</div>



Display the values of checkboxes in React

I have mutltiple checkboxes in a React app but I cant seem to display their "true" values. I just want to display which ones are flagged.

Thanks for the help :)

Julie

<label>Which features does your bubble have?
            <span> Wifi
            <input 
            type="checkbox"
            onChange={handleChange}
            value={wifi}
            />
import React, { useState } from "react";
import NewBubbleForm from "./NewBubbleForm";

function NewBubble(props) {
  const [name, setName] = React.useState("");
  const [postcode, setPostcode] = React.useState("");
  const [workstations, setWorkstations] = useState(0);
  // const [isChecked , setIsChecked] = useState(false)
  const [wifi, setWifi] = React.useState(true);
  const [petfriendly, setPetfriendly] = React.useState(true)
  const [kitchen, setKitchen] = React.useState(true);
  const [quietspace, setQuietspace] = React.useState(true);
  const [wheelchair, setWheelchair] = React.useState(true);
  const [smoking, setSmoking] = React.useState(true);
  


  function handleChange(event) {
    // console.log('event: ', event)
    console.log(event.target.checked);
    switch (event.target.name) {
      case "name":
        setName(event.target.value);
        break;
      case "postcode":
        setPostcode(event.target.value);
        break;
      case "workstations":
        setWorkstations(event.target.value);
        break;
      case "wifi":
        setWifi(event.target.checked);
        break;
      case "petfriendly":
        setPetfriendly(event.target.value);
          break;
      case "kitchen":
        setKitchen(event.target.value);
        break;
      case "quietspace":
        setQuietspace(event.target.value);
        break;
      case "wheelchair":
        setWheelchair(event.target.value);
        break;
      case "smoking":
        setSmoking(event.target.value);
        break;
      default:
        break;
    }
  }

  function handleSubmit(event) {
    event.preventDefault();
    console.log(
      `A request has been logged: 
        From ${name} ${postcode} with ${workstations} spots and WIFI ${wifi}
        `
    );
    let newBubbleData = {name, postcode, workstations, wifi, petfriendly, kitchen, quietspace, wheelchair, smoking}
    props.showNewBubble(newBubbleData);
    console.log("New bubble" , newBubbleData)
    setName("");
    setPostcode("");
    setWorkstations("");
    setWifi("");
    setPetfriendly("")
    setKitchen("")
    setQuietspace("")
    setWheelchair("")
    setSmoking("")
    // the submission event would then add the new bubble to the backend tables
    // the map would then be returned with the new bubble on it
  }

  return (
    <div className="NewBubble">
      <form onSubmit={handleSubmit}>
        Create a new Bubble
        <NewBubbleForm
          name={name}
          postcode={postcode}
          workstations={workstations}
          handleChange={handleChange}
          wifi={wifi}
          petfriendly={petfriendly}
          kitchen={kitchen}
          quietspace={quietspace}
          wheelchair={wheelchair}
          smoking={smoking}

        />
        <button id="buttonCreateBubble" type="submit">
          {" "}
          Create a bubble{" "}
        </button>
      </form>
    </div>
  );
}

Here is the APP receiving the info

function App() {
  // const history = useHistory();
  const [bubble, setBubble] = useState([{name: "Julie", workstations: ""}]);
  let history = useHistory();

  function showNewBubble(newBubbleData) {
    // event.preventDefault();
    console.log("New bubble is back to app", newBubbleData)
    setBubble(newBubbleData)
    history.push("/new-bubble-created");
  }

  
  return (
    <div>
      <Navbar />
      <Routes 
      showNewBubble={()=>showNewBubble}
      bubble={bubble}
      />
    </div>
  );
}

export default App;

And here is the final component where I display my checked box The props.bubble.wifi does not display anything even if its value in the console is true!

import React from 'react';
import MapBubbles from "./MapBubbles"
// import MapBubbleForm from "./MapBubbleForm";


function MapWithNewBubble(props) {

    console.log("This is props.value.wifi" , props.bubble.wifi)
    return (
        <div className="NewBubble">
           <h2>Your new bubble has been created</h2>
           <p>Welcome {props.bubble.name}</p>
           
            <p> You have {props.bubble.workstations} workstations to offer and {props.bubble.wifi}</p>
            <MapBubbles />
        </div>
    );
}

export default MapWithNewBubble;