jeudi 31 décembre 2020

How to CSS the 'unchecked' state of a checkbox switch?

I should note I have this working in codepen, and can use:

[type="checkbox"]:not(:checked) + label .span2 {display:none;}

to make my object disappear.

But when I try it on my WordPress site, it doesn't seem to recognize at all any such object. I can still access the checked state with

.switch input:checked~label .span1 {display:none;}

But I can't make my other thing disappear when it's unchecked (note: I can uncheck the box and affect changes using

.switch label {change}

I just can't make my stuff disappear when it's unchecked.

Here's my html:

<div class="switch">
  <input type="checkbox" checked>
  <label>
    <span class="span1">
      <span class="word1">
      hiiiiii sakdfjs sakdjf
      </span>
    </span>
    <span class="span2">
      <span class="word2">
        ho
      </span>
    </span>
  </label>
</div>

Just to specify, I want to make one thing disappear in the checked state and a different thing disappear in the unchecked state. This works on Codepen but not on my WordPress site. (I tried removing all the CSS lines that might effect it but I didn't succed that way, and the CSS sheet is really long as it's the WordPress 2020 theme).




How to Show a Series in a Chart if a Checkbox is Checked, How to Hide a Series if a Checkbox is Unchecked (VB.NET)

I have a chart that displays different data based on which user is using the program. In their interface, they can only see the series that includes their information in the chart TotalCompletedDetailsCHRT. They cannot see anyone else's information.

The exception to this general practice is the Detailing Lead. They will have access to see everyone else's information. Currently I have a checkbox that toggles the detailing lead view (which just hides one groupbox and shows another). Below is a screenshot of the checkbox, as well as it's code. enter image description here

For reference, "DetailingLead" is a username.

Private Sub AdminViewDetailingLead() Handles DetailingLeadViewCHKB.CheckedChanged

        If DetailingLead AndAlso DetailingLeadViewCHKB.Checked = True Then
            CareerCompletedDetailsGRPB.Visible = False
            DetailLeadGRPB.Visible = True
            DetailLeadGRPB.Location = New Point(611, 409)
        ElseIf DetailingLead AndAlso DetailingLeadViewCHKB.Checked = False Then
            CareerCompletedDetailsGRPB.Visible = True
            DetailLeadGRPB.Visible = False
        End If
    End Sub

This code successfully hides the unneeded groupbox, and displays the DetailingLead's Groupbox. The interface now looks like this: enter image description here

My problem is that even whenever the checkboxes are checked, I can only see the series/information associated with my username, not the other's. Below is the code I have for the checkboxes' logic.

Private Sub AdminViewTotalDetailsCHRT() Handles MyBase.Load

        If UserName = DetailingLead AndAlso BDStatsCHKB.Checked = True Then

            TotalCompletedDetailsCHRT.Series(1).Enabled = True
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Maximum = 12
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Interval = 1
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Maximum = 1000
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Interval = 50
        End If
        If UserName = DetailingLead AndAlso KBStatsCHKB.Checked = True Then

            TotalCompletedDetailsCHRT.Series(2).Enabled = True
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Maximum = 12
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Interval = 1
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Maximum = 1000
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Interval = 50
        End If
        If UserName = DetailingLead AndAlso MVStatsCHKB.Checked = True Then

            TotalCompletedDetailsCHRT.Series(0).Enabled = True
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Maximum = 12
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisX.Interval = 1
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Minimum = 0.0
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Maximum = 1000
            TotalCompletedDetailsCHRT.ChartAreas(0).AxisY.Interval = 50
        End If
    End Sub

Does anyone have any idea of to why the other series' wouldn't be displaying? Thanks for the input.




python selenium click checkbox one by one instead of all together

df3 = list(df2) for i in df3:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//html//body//div[2]//div//div[2]//div[1]//form//div//div[2]//div//div[2]//label[{}]//input".format(i)))).click()

I managed to click all selected checkbox by loop over a list but I would like to click the checkbox one by one instead of all together




How can I list the files on an FTP from a (stand-alone) .html file?

I am developing a self-contained (stand-alone) HTML form. In one part of the form, I would like to make it possible to select the name of a file that is on an FTP.

In my .html file, I am therefore trying to find a way to list the names of all the files on an FTP.

Based on what I have read so far, it seems there is no conventional way to do this as accessing an FTP should be done using server-side languages such as PHP for example, as explained here or here.

So I am trying to see if I can do this in a different way. An idea I had is to copy the content displayed on an FTP page into a JavaScript variable, as shown here.

I am using as an example the FTP from the German Climate Data Center because it is an open access FTP that doesn’t require any login information. In the code below, I am trying to place the content displayed on a page of that FTP into a <div> inside my .html file, and then display the <div> using console.log. However, as shown below, I haven’t been successful so far:

function start_FTP() {
  var server = "ftp-cdc.dwd.de/test/weather/radar/sites/sweep_vol_z/mem/hdf5/filter_polarimetric/";
  var ftpsite = "ftp://" + server;
  window.open(ftpsite);

  document.getElementById("FTP_content").innerHTML = '<object type="text/html" data=ftpsite ></object>';
  console.log(FTP_content);
}
<h2> List FTP content using JavaScript </h2>
<button type="button" id="FTP_button" name="FTP_button" onclick="start_FTP()">Select File Name</button>
<div id="FTP_content"> </div>

The <div> does not contain any useful information.

This is just a step towards my final goal, which is in fact to create a new window that lists the contents on the FTP page with a checkbox next to each line, such that the user can select the name of the file he needs.

Is this possible using JavaScript? If not, are there any other “tricks” that can be used to reach this goal using JavaScript only?




State not getting updated for Checkbox

I am using checkboxes to store user preferences and sending it to backend for further processing. I only wanted to store the checked values in my state object. But thats not getting updated. I tried with the Object keys method to determine the checked value. But i am unable to get the value to update my state. I am a newbiew in React, so excuse my for my doubt. I have provided a snippet below.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkedItems: {},
      count: 0,
      formObject: {
        subjects: []
      }
    }
  }
  
  onInputChange = (value, key) => {   
    const { formObject } = this.state;
    const {...formValues} =  formObject;
    formValues[key] = value;
    this.setState((prevState, currState) => {
        return {
            ...prevState,
            formObject: formValues
        };
    }, () => console.log(this.state.formObject));
  }
  
  handleChange = (event, formKey) => {
    const {name, checked} = event.target;
    const updatedCheckedItems = {...this.state.checkedItems, [name]: checked };

    this.setState({
        checkedItems: updatedCheckedItems,
        count: Object.values(updatedCheckedItems).filter((value) => value).length
    }, () => {this.onInputChange(Object.keys(updatedCheckedItems), 'subjects')});
  }
  
  render() {
  const checkedValues = {...this.state.checkedItems};
  const checkedCount =  Object.values(checkedValues).filter((value) => value).length;
  const checkboxes = [
      {
          name: "Math and economics",
          key: "mathsandeconomics",
          label: "Math and economics"
      },
      {
          name: "Science",
          key: "Science",
          label: "Science"
      },
      {
          name: "World languages",
          key: "World languages",
          label: "World languages"
      },
      {
          name: "Government and politics",
          key: "Government and politics",
          label: "Government and politics"
      },
      {
          name: "Art and design",
          key: "Art and design",
          label: "Art and design"
      },
      {
          name: "Technology",
          key: "Technology",
          label: "Technology"
      },
      ];
    return (
      <div className="App">
        <h1>Hello React</h1>
        {
          checkboxes.map((item, index) => (
            <label key={item.key}>
              <input type="checkbox" name={item.name} checked={this.state.checkedItems[item.name] || false}
              onChange={this.handleChange}
              disabled={!checkedValues[item.name] && checkedCount > 2} />{item.name}
            </label>
          ))}
        }
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>



HTML checkbox in React

I have two radio buttons based on which I want to show a list of checkboxes to the user. But the problem is that when user checks any checkbox in the first list, it automatically checks the boxes in the second list too.

Here are my radio buttons:

<input 
checked={optionLocal==='residential' ? 'checked' : ''}                                  
onClick={()=>{
setOptionLocal('residential')
}} 
type="radio" 
id="residential" 
name="option" 
value="residential"/>

<input 
checked={optionLocal==='commercial' ? 'checked' : ''} 
onClick={()=>{
setOptionLocal('commercial')
}} 
type="radio" 
id="commercial" 
name="option" 
value="commercial"/>

When I click one of them, it stores the state locally and based on that list is generated.

optionLocal === 'residential' ? (
                            residential.map((row,index)=>{
                                return(
                                    <li>
                                        <div className="d-flex flex-row align-items-baseline px-3">
                                            <input 
                                            type="checkbox" 
                                            id={'r-' + row} 
                                            name={'r-' + row} 
                                            value={'r-' + row}/>
                                        </div>
                                    </li>
                                )
                            })
                        ) : (
                            commercial.map((row,index)=>{
                                return(
                                    <li>
                                        <div className="d-flex flex-row align-items-baseline px-3">
                                            <input 
                                            type="checkbox" 
                                            id={'c-' + row} 
                                            name={'c-' + row} 
                                            value={'c-' + row}/>
                                        </div>
                                    </li>
                                )
                            })
                        )

Here is what is happening.

Image 1

Image 2




Why does an unchecked checkbox have a value of 'on'?

(Also replicated in JSfiddle)

Given an HTML checkbox:

<input type="checkbox">

The checkbox is displayed with no tick:

enter image description here

Logging the value of the element:

console.log(document.querySelector('input').value)

Logs on, even though the checkbox is unchecked.

Why is the value of the checkbox 'on', when the checkbox is unchecked?

How can I get the correct value?




Disable and Deselect Checkboxes by name in React

I have multiple checkboxes, But the condition is to disable the checkbox on specific name check. I have achieved that, but the problem is when you check on other checkboxes first and then check on the checkbox which you want to disable, the checkbox check is still present. I have published the code on stackblitz if you want to take a look. So on the below code, i want to disable all checkbox on click of "All ages". But when you select other checkbox and then select "All ages" checkbox the checked is still present and you can deselect that checkbox. How can i remove that checkbox checked after disabling.

StackBlitz




mercredi 30 décembre 2020

JQuery/JavaScript change in the checkbox

I have a simple div with multiple checkboxes in it. I want to look for any change in the checkbox to make an ajax query. This code is not able to see the changes in those checkboxes. What is the right way to do it?

$(document).on('change', '#listfilters checkbox', function(e) {
        if(this.checked) {
            alert("changed");
          // checkbox is checked
        }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="listfilters">
    <p>
    <input type="checkbox" id="showall" name="showall" value=0>&nbsp;
    <label for="showall">Show All</label>
    </p>
    <p>
    <input type="checkbox" id="showfl" name="showfl" value=0>&nbsp;
    <label for="showfl">Filtered</label>
    </p>
</div>



How to Save Multiple Checkbox Values to a string?

I use Rails 6.1 and the gem simple_form. I want save value of multiple checkbox in an object (string serialized or array). i don't find a simple solution.

table

    class CreateSpots < ActiveRecord::Migration[6.0]
  def change
    create_table :spots do |t|

      t.string :wind_direction

      t.timestamps
    end
  end
end

_form.html.erb

<%= simple_form_for (spot) do |f| %> 
  <%= f.input :wind_direction, as: :check_boxes, collection: Spot::DIRECTION %>
  <%= f.submit %>
<% end %>

model

  class Spot < ApplicationRecord
  DIRECTION = ['N','NW','W','SW','S','SE','E','NE']
  end

After submit the form, the output of wind_direction is Nil

ideally, i look for a string, i work with this format actually.

wind_direction: "[\"W\", \"NW\", \"N\", \"NE\", \"E\"]",

Thanks for any suggestions




How to select multiple checkboxes in Dusk test

I am using VueJS with bootstrap-vue, and using Laravel Dusk, I need to test a table inside a modal that uses a checkbox to select each row. In this particular case, there are multiple rows with checkboxes, and I need to select all of the checkboxes in the form and then submit the form. My test works fine with the modal in every way except checking the checkboxes; no matter what I try, I can't get the check() (or click()) method to check more than the first one. I've tried

->check("input[type=checkbox]")

and using the name

->check("input[name='my-custom-name']")

but I still only get the first item checked. Based on this, I tried something like

$checkboxes = $browser->driver->findElements(WebDriverBy::name('select-pursuit-restore[]'));
for ($i = 0; $i <= count($checkboxes); $i++) {
    $checkboxes[0]->click();
}

but even that only checks the first checkbox. What do I need to do to select all of the checkboxes in the table?




form with multiplie data with checkboxes

i have table of procuts (data come from database)

  <?php
    while($row3 = mysqli_fetch_array($result2)) {
     $prodname = $row3['name'];
     $supid = $row3['supplier'];
     $prodid = $row3['id'];
     $prodprice = $row3['price'];
  ?>
            <tr class='listtable'>
              <td><input type="checkbox" name="prod[]" id="prod[<?php echo $prodid; ?>]" value="<?php echo $prodid; ?>"><label for="prod[<?php echo $prodid; ?>]"><?php echo $prodname; ?></label>
              </td>
              <td><label for="prod[<?php echo $prodid; ?>]"><?php echo $prodprice; ?> NIS
              </td></label>
              <td><input type="text" name="qty" placeholder="Qty" minlength="1" maxlength="3" size="2">
              </td>
            </tr>
    <?php
    }
    ?>

i want to send the data of each row if the checkbox is selected... i can send the checkbox value (i sent the producs ID to get the data from the database for each one is selected but i cant send the Qty text box value (i want to send only the ones are checked)

<?php  
include "db.php";
  if(isset($_POST['submit'])){
      if(!empty($_POST['prod'])){
        foreach($_POST['prod'] as $pid){
          $proddetail = mysqli_query($con,"SELECT * FROM `products` WHERE id = $pid");
          while($prod = mysqli_fetch_array($proddetail)) {
            $pname = $prod['name'];
            $pprice = $prod['price'];
            echo $pname;
            echo $pprice;
            echo "<br>";
          }
        }
      } else {
        echo 'no items selected!';
      }
  }
?>  



align text and toggle button in html css

I have created a custom toggle button with html input checkbox and with custom css which looks like this enter image description here

As you can see the texts and toggle buttons are not aligned, I tried adding margin/padding/heights nothing worked. Here is the html and corresponding css ->

<h5 style="display:inline" class="switch">Company</h5>
<label class="switch">
  <input type="checkbox" id="company-survey-checker">
  <span class="slider round"></span>
</label>
<h5 style="display:inline">Survey</h5> 

And the css operating here is ->

<style>
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
</style>

Ideally the texts and toggle buttons should be on the same line but i am finding it difficult to achieve it , any help is much appreciated




mardi 29 décembre 2020

Can't get values for multiple checkboxes in html

I have a html table of all the items in in my sql table. Each item has a checkbox that, when selected, is supposed to give the value of the item name to the calculate route when I press the submit button. However, the submit button only submits one checkbox value even if multiple checkboxes are selected. How do I get it to submit the values of all the checkboxes that are selected, not just one checkbox.

<table style="width:100%" class="styled-table">
                <tr>
                <th>Selected</th>
                <th>Amount</th>
                <th>Name</th>
                <th>Typical values</th>
                <th>Unit of typical values</th>
                <th>Calories</th>
                <th>Carbs</th>
                <th>Fat</th>
                <th>Protein</th>
                <th>Salt</th>  
                <th>Sugar</th>
                </tr>

        <tr>
        <% availableFood.forEach(function(food_item){ %>
                <form method="POST" action="/topic7/mid-term/calculate"> 
                        <td><input type="checkbox" name="checkbox[]" value= <%= food_item.name %>></td>    
                        <td><input id="qty" type="text" name="qty" value="1" width="8" style="width: 30px;"/></td>
                        <td><%= food_item.name %></td>
                        <td><%= food_item.typical_values %></td> 
                        <td><%= food_item.unit_of_the_typical_value %></td>
                        <td><%= food_item.calories %></td>
                        <td><%= food_item.carbs %></td>
                        <td><%= food_item.fat %></td>
                        <td><%= food_item.protein %></td> 
                        <td><%= food_item.salt %></td> 
                        <td><%= food_item.sugar %></td>
        </tr>
                        <input type="submit" value="Calculate sum" />
        </form>
<% }) %>



Moving row to a completely different spreadsheet when checkbox is checked

Hi I have 2 spreadsheets, for example, one is called 'test' and the other 'test1'. I want when checkbox is checked for a row on spreadsheet 'test', the entire row moves to 'test1' spreadsheet. I used this script and it works perfectly if I want the row to move to another sheet in the 'test' spreadsheet.

function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if (src.getName() != "New" || r.columnStart != 6 || r.rowStart == 1) return;
  const dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Complete");
  src.getRange(r.rowStart,1,1,6).moveTo(dest.getRange(dest.getLastRow()+1,1,1,6));
  src.deleteRow(r.rowStart);
 }

But when I change it to this script so the row is moved from 'test' to 'test1' it does not work. I can't seem to figure out the solution. Can anyone help - thanks so much!

function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if (src.getName() != "New" || r.columnStart != 6 || r.rowStart == 1) return;
  const dest = SpreadsheetApp.getActiveSpreadsheet("19D-PzL- 
  YGdRQbXdGeILMeUbHFJkxeMFan0di7eSqK6E").getSheetByName("Sheet1");
  src.getRange(r.rowStart,1,1,6).moveTo(dest.getRange(dest.getLastRow()+1,1,1,6));
  src.deleteRow(r.rowStart);

}



Python pyqt5 program crashes when trying to get data from checkbox combo box

New to python so sorry for the terrible code but I'm trying to change something in my code when the user selects a checkbox from the combo box but the program crashes when I try. I can load the table fine but when I try to get the data in my LoadCombo(self): method the program crashes. Thanks for any advice

from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog, QTableView, QTableWidget, qApp
from PyQt5.QtCore import Qt, QModelIndex, QAbstractTableModel, QSortFilterProxyModel
import sys, os


class Ui_MainWindow(object):
def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(800, 600)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
    self.tabWidget.setGeometry(QtCore.QRect(90, 50, 691, 491))
    self.tabWidget.setObjectName("tabWidget")
    self.tab = QtWidgets.QWidget()
    self.tab.setObjectName("tab")
    self.verticalLayoutWidget = QtWidgets.QWidget(self.tab)
    self.verticalLayoutWidget.setGeometry(QtCore.QRect(70, 50, 491, 331))
    self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
    self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
    self.verticalLayout.setContentsMargins(0, 0, 0, 0)
    self.verticalLayout.setObjectName("verticalLayout")
    self.horizontalLayout = QtWidgets.QHBoxLayout()
    self.horizontalLayout.setObjectName("horizontalLayout")
    spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
    self.horizontalLayout.addItem(spacerItem)
    self.testcombo = CheckableComboBox(self.verticalLayoutWidget)
    self.testcombo.setObjectName("testcombo")
    self.horizontalLayout.addWidget(self.testcombo)
    spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
    self.testcombo1 = CheckableComboBox(self.verticalLayoutWidget)
    self.testcombo1.setObjectName("testcombo1")
    for i in range(3):
        self.testcombo1.addItem("Combobox Item " + str(i))
    self.horizontalLayout.addWidget(self.testcombo)
    self.horizontalLayout.addItem(spacerItem1)
    self.verticalLayout.addLayout(self.horizontalLayout)
    self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
    self.pushButton.setObjectName("pushButton")
    self.pushButton.clicked.connect(self.LoadTable)
    #self.testcombo.itemChecked.connect(self.LoadTable)
    self.verticalLayout.addWidget(self.pushButton)
    self.table = QtWidgets.QTableView()
    self.LoadTable()
    self.proxyModel = QSortFilterProxyModel()
    self.proxyModel.setSourceModel(self.model)
    self.table.setSortingEnabled(True)
    self.table.setModel(self.proxyModel)
    self.verticalLayout.addWidget(self.table)
    self.LoadCombo()
    self.tabWidget.addTab(self.tab, "")
    self.tab_2 = QtWidgets.QWidget()
    self.tab_2.setObjectName("tab_2")
    self.tabWidget.addTab(self.tab_2, "")
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.LoadComboBoxes()
    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.pushButton.setText(_translate("MainWindow", "Load Table"))
    self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1"))
    self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2"))

def LoadTable(self):
    #print(self.testcombo.currentData())
    #self.headerData(['Column 1test', 'Column 2test', 'Column 3', 'test'], Qt.Horizontal, Qt.DisplayRole)

    data = [self.testcombo.currentData()]
    #print(data)
    headers = []
    for x in self.testcombo.currentData():
        headers.append(x+'TESTING!')

    print(headers)
    #headers = self.testcombo.currentData()
    self.model = TableModel(data, headers)
    self.proxyModel = QSortFilterProxyModel()
    self.proxyModel.setSourceModel(self.model)
    #self.table.setSortingEnabled(True)
    self.table.setModel(self.proxyModel)
    #self.setCentralWidget(self.table)

def LoadCombo(self):
    #As soon as I uncomment the below the program crashes when I select a checkbox
    #print(self.testcombo.currentData())
    print('test')


def LoadComboBoxes(self):
    for i in range(6):
        self.testcombo.addItem("Combobox Item " + str(i))



class CheckableComboBox(QtWidgets.QComboBox, Ui_MainWindow):
def __init__(self, parent=None):
    super(CheckableComboBox, self).__init__(parent)
    self.view().pressed.connect(self.handleItemPressed)

    # once there is a checkState set, it is rendered
# here we assume default Unchecked
def addItem(self, item):
    super(CheckableComboBox, self).addItem(item)
    item = self.model().item(self.count()-1,0)
    #item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    item.setFlags(QtCore.Qt.ItemIsEnabled)
    item.setCheckState(QtCore.Qt.Unchecked)

def handleItemPressed(self, index):
    self.LoadCombo()
    item = self.model().itemFromIndex(index)

    # checking if item is checked
    if item.checkState() == Qt.Checked:

        # making it unchecked
        item.setCheckState(Qt.Unchecked)

        # if not checked
    else:
        # making the item checked
        item.setCheckState(Qt.Checked)

def itemChecked(self, index):
    item = self.model().item(i,0)
    return item.checkState() == QtCore.Qt.Checked

def currentData(self):
    # Return the list of selected items data
    res = []
    for i in range(self.model().rowCount()):
        if self.model().item(i).checkState() == Qt.Checked:
            res.append(self.model().item(i).text())
    return res



class TableModel(QtCore.QAbstractTableModel):

def __init__(self, data, headers):
    super(TableModel, self).__init__()
    self._data = data
    self.header_labels = headers

def data(self, index, role):
    if role == Qt.DisplayRole:
        # See below for the nested-list data structure.
        # .row() indexes into the outer list,
        # .column() indexes into the sub-list
        return self._data[index.row()][index.column()]

def headerData(self, section, orientation, role=Qt.DisplayRole):
    if role == Qt.DisplayRole and orientation == Qt.Horizontal:
        return self.header_labels[section]
    return QAbstractTableModel.headerData(self, section, orientation, role)

def rowCount(self, index):
    # The length of the outer list.
    return len(self._data)

def columnCount(self, index):
    # The following takes the first sub-list, and returns
    # the length (only works if all rows are an equal length)
    return len(self._data[0])


if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())



How to save selected input from a drop-down box with checkboxes? My drop-down box is okay but the checkboxes are not working

Hi, I am trying to run a GUI based on wx. I made checkboxes in a drop-down list. But the checkboxes are not working. I want the checkboxes to work and save the selected input option names somewhere. Here is the code. With these selected input option names (one or more than one) I will filter a big string later. Thank you in advance :)

import wx import wx.stc from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin

class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin): def init(self, parent): wx.ListCtrl.init(self, parent, wx.ID_ANY, style=wx.LC_REPORT | wx.SUNKEN_BORDER) CheckListCtrlMixin.init(self) ListCtrlAutoWidthMixin.init(self) self.SetSize(-1, -1, -1, 50)

def OnCheckItem(self, index, flag):
    item = self.GetItem(index)
    if flag:
        what = "checked"
    else:
        what = "unchecked"

    print(f'{item.GetText()} - {what}')

class ListViewComboPopup(wx.ComboPopup):

def __init__(self):
    wx.ComboPopup.__init__(self)
    self.lc = None

def AddItem(self, txt):
    self.lc.InsertItem(0, txt)


def Init(self):
    self.value = -1
    self.curitem = -1

def Create(self, parent):
    self.lc = CheckListCtrl(parent)
    self.lc.InsertColumn(0, '', width=90)
    return True

def GetControl(self):
    return self.lc

def OnPopup(self):
    wx.ComboPopup.OnPopup(self)

def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
    return wx.ComboPopup.GetAdjustedSize(
        self, minWidth, 110, maxHeight)

class MyForm(wx.Frame):

def __init__(self):
    wx.Frame.__init__(self, None, title="Popup Menu Tutorial")
    panel = wx.Panel(self)
    comboCtrl = wx.ComboCtrl(panel, wx.ID_ANY, "Select filter")    
    popupCtrl = ListViewComboPopup()
    comboCtrl.SetPopupControl(popupCtrl)
    popupCtrl.AddItem("mango")
    popupCtrl.AddItem("cat")
    popupCtrl.AddItem("dog")
    popupCtrl.AddItem("tiger")
    popupCtrl.AddItem("three")
    popupCtrl.AddItem("hat")
    popupCtrl.AddItem("hot")
    popupCtrl.AddItem("sweden")
    popupCtrl.AddItem("kth")



Display custom checkbox field state on WooCommerce thankyou page

Based on my previous question + the answer to the question

How to save from WooCommerce checkout a custom checkbox field state?

I have an additional checkbox on WooCommerce checkout page, but when the order is complete I don't see the additional field on the thankyou page. My checkbox save value 1 or 0 in meta_data when checkbox is checked or unchecked

$order->update_meta_data( 'ritiro_sede', $value );

I would like to see word SI if checkbox is checked and word NO if checkbox is unchecked, but this function not work:

Does anyone have any idea what might be wrong?

add_action( 'woocommerce_thankyou', 'my_custom_checkout_field_display_order_data_ritiro_sede', 10, 1 );
add_action( 'woocommerce_view_order', 'my_custom_checkout_field_display_order_data_ritiro_sede', 10, 1 );
function my_custom_checkout_field_display_order_data_ritiro_sede( $order ){ 
    $ritiro_sede = get_post_meta( $order_id, 'ritiro_sede', true );
    if( $ritiro_sede == 1 )
        echo '<p><strong>Ritiro In sede: </strong> <span style="color:red;">SI</span></p>';
    if( $ritiro_sede == 0 )
        echo '<p><strong>Ritiro In sede: </strong> <span style="color:red;">NO</span></p>';
    //echo '<p>'. __('Ritiro in Sede: ') . get_post_meta($order->get_id(), 'ritiro_sede', true .'</p');
    //echo '<p>'. __('Ritiro in Sede: ','theme_name') . get_value($order->get_the_id(), 'ritiro_sede', true .'</p>');       
}



lundi 28 décembre 2020

PayPal's JavaScript API is forcing “Shipping same as billing address”?

Sandbox

First be advised there is a testing sandbox provided by PayPal for you to try these code samples.

What I have tried

return actions.order.create({
  purchase_units: [{
    amount: { value: '88.44' },
    shipping: {
      name: { full_name: 'Ship Name' },
      address: {
        address_line_1: 'Ship Address',
        address_line_2: '',
        admin_area_2: 'Ship City',
        admin_area_1: 'SC',
        postal_code: 'SHP ZIP',
        country_code: 'US',
      },
    }
  }],
  payer: {
    name: { given_name: 'Bill', surname: 'Name' },
    address: {
      address_line_1: 'Bill Address',
      address_line_2: '',
      admin_area_2: 'Bill City',
      admin_area_1: 'MS',
      postal_code: 'BIL 0H0',
      country_code: 'US',
    }
  },
})

Reproducing the issue

Click the PayPal checkout button

Then, in the popup, click Pay with Credit or Debit Card

You will notice the correct billing option is present. Billing Address is Bill Name/Address

However, the Shipping Address is hidden behind the checkbox. Shipping same as billing address

This could lead to the user accidentally shipping the product to the wrong address!

How can I fix this?

That checkbox should ideally be unchecked because we are clearly passing a different address in the source code above.

As a side note

If the user does uncheck the box, they do get the correct address.




get array of checkboxes checked, and only if seletced in a specific order, then go to URL

First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.

I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...

  1. I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.

  2. I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.

  3. If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.

I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)

Thanks in advance for any help, or links to a topic that could point me in the right direction.

Here's my html code.

    <form name="checklist" method="post" action="My-Page.php">
      <label>
        <input type="checkbox" value="8">
        <img src="btn_8.png"></label>
      <label>
        <input type="checkbox" value="3">
        <img src="btn_3.png"></label>
      <label>
        <input type="checkbox" value="9">
        <img src="btn_9.png"></label>
      <label>
        <input type="checkbox" value="2">
        <img src="btn_2.png"></label>
      <label>
        <input type="checkbox" value="5">
        <img src="btn_5.png"></label>
      <label>
        <input type="checkbox" value="4">
        <img src="btn_4.png"></label>
      <label>
        <input type="checkbox" value="7">
        <img src="btn_7.png"></label>
      <label>
        <input type="checkbox" value="1">
        <img src="btn_1.png"></label>
      <label>
        <input type="checkbox" value="6">
        <img src="btn_6.png"></label>
      <input type="submit" value="Open">
    </form>

Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error (I have an error script, but it's in jquery, and part of a much larger script I have which is for emailing me a list of things).

var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
  array.push(checkboxes[i].value)
}

the error snipit:

jQuery("#ValidCheckbox").validate({
expression: "if (isChecked(SelfID)) return true; else return false;",
message: "Select at least one item " });



dimanche 27 décembre 2020

JQuery check only one checkbox per checkbox line

I have multiple checkbox lines on my page, with this template:

<div class="row">
  <div class="col">
    <input type="checkbox" id="ft_checkbox" name="ft_checkbox" value="CSV" checked>
    <label for="ft_checkbox">CSV</label>
    &nbsp;
    <input type="checkbox" id="ft_checkbox" name="ft_checkbox" value="JSON" >
    <label for="ft_checkbox">JSON</label>
    &nbsp;
    <input type="checkbox" id="ft_checkbox" name="ft_checkbox" value="PDF" >
    <label for="ft_checkbox">PDF</label>
    &nbsp;
    <input type="checkbox" id="ft_checkbox" name="ft_checkbox" value="XLSX" >
    <label for="ft_checkbox">XLSX</label>
  </div>
</div>

To allow only one checkbox to be checked I do:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  
  $(document).ready(function(){
    $('input:checkbox').click(function() {
      $('input:checkbox').not(this).prop('checked', false);
    });
  });
  
</script>

However this makes all lines dependent from each other. If I check one box on line one, it will uncheck all boxes accross the whole document. I would like to apply this function for each line / parent div instead. So I allow one bow to be checked per line.




python tkinter checkboxes get ticked at once

why do both checkboxes get checked when I only click one? The checkboxes on the right and in a different Frame, as well as the ones on the left. The variables are also different for each checkbox. Anyone has any idea what might cause this? https://imgur.com/a/bQkrMsk




samedi 26 décembre 2020

How to save from WooCommerce checkout a custom checkbox field state?

I have a problem with the update_post_meta function. I have a user submitted value, which I pass via $_POST and then saving to post meta.

All is working fine, but when the value is '0' the post meta is not updated.

This is My code:

// Add custom checkout field: woocommerce_review_order_before_submit
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field_ritiro_sede' );
function my_custom_checkout_field_ritiro_sede() {
    echo '<div class="cw_custom_class"><h3>'.__('Ritiro presso sede CER S.r.l. &nbsp').'</h3>';
    echo '<div id="my_custom_checkout_field">';
    woocommerce_form_field( 'ritiro_sede', array(
        'type'      => 'checkbox',
        'class'     => array('input-checkbox'),
        'label'     => __('SI'),
    ),  WC()->checkout->get_value( 'ritiro_sede' ) );
    echo '</div>';
}

// Save the custom checkout field in the order meta, when checkbox has been checked
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta_ritiro_sede', 10, 1 );
function custom_checkout_field_update_order_meta_ritiro_sede( $order_id ) {

    if ( ! empty( $_POST['ritiro_sede'] ) )
        update_post_meta( $order_id, 'ritiro_sede', $_POST['ritiro_sede'] );
    if ( isset( $_POST['ritiro_sede'] ) )
        update_post_meta( $order_id, 'ritiro_sede', $_POST['0'] );
    
}

Does anyone have any idea what might be wrong?




How to valid checkbox in a form

I have a basic question but i can't find the solution .

how can i force my user to check the box : accept the condition ? (j'acceptes les conditions d'utilisations = i agree terms & conditions )

here is a pictures of my form : My form

here is my HTML:

    <section id="formDom">
        <form class="column g-3 needs-validation" novalidate>
            <div class="col-md-4">
                <label for="validationCustom01" class="form-label">Nom</label>
                <input type="text" class="form-control" placeholder="Dupont" id="firstName" required>
                <div class="valid-feedback">
                    Ok
                </div>
            </div>
            <div class="col-md-4">
                <label for="validationCustom01" class="form-label">prénom</label>
                <input type="text" class="form-control" placeholder="Jean" id="lastName" required>
                <div class="valid-feedback">
                    Ok
                </div>
            </div>
            <div class="col-md-4">
                <label for="validationCustomUsername" class="form-label">Adresse mail</label>
                <div class="input-group has-validation">
                    <span class="input-group-text" id="inputGroupPrepend">@</span>
                    <input type="email" class="form-control" id="email" aria-describedby="inputGroupPrepend"
                        placeholder="jeandupont@gmail.com" required>
                    <div class="invalid-feedback">
                        Adresse mail requise
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <label for="validationCustom01" class="form-label">Ville</label>
                <input type="text" class="form-control" placeholder="Paris" id="city" required>
                <div class="valid-feedback">
                    Ok
                </div>
            </div>
            <div class="col-md-4">
                <label for="validationCustom03" class="form-label">Adresse</label>
                <input type="text" class="form-control" placeholder="1 rue de Paris" id="adress" required>
                <div class="invalid-feedback">
                    adresse réquise
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
                    <label class="form-check-label" for="invalidCheck">
                        J'accepte les conditions d'utilisations
                    </label>
                    <div class="invalid-feedback">
                        Vous devez accepteer les conditions d'utilisations
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <button id="buyBtn" class="btn btn-primary basket-btn" type="submit">Acheter</button>
            </div>
        </form>
    </section>

Actually the user is forced to fill the form but he can submit without check the box ( accept condition )

Here is the JS :

        function validForm() {
            const form = document.querySelector('.needs-validation');
            form.addEventListener('submit', function (event) {
                event.preventDefault();
                event.stopPropagation();
                cameraIds = getBasket().map(item => { return item.id });
                const contact = {
                    email: document.getElementById("email").value,
                    firstName: document.getElementById("firstName").value,
                    lastName: document.getElementById("lastName").value,
                    city: document.getElementById("city").value,
                    address: document.getElementById("adress").value,
                }

                createOrder(contact, cameraIds, (order, error) => {
                    if (error) {
                        alert('Merci de remplir le formulaire');
                    } else {
                        localStorage.clear();
                        location.assign(`confirmation.html?id=${order.orderId}`)
                    }
                    form.classList.add('was-validated');
                })
            })
        }
        validForm();

PS : i'm using BOOTSTRAP but i think you got it ^^




I am trying to Reduce check box width in grid but unable to reduce

I am trying to Reduce check box width in grid but unable to reduce

enter image description here




vendredi 25 décembre 2020

save checkbox status after page reload

help to make the checkbox status persist after reloading the page, thanks!

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js" type="text/javascript"></script>


<input type="checkbox" name="enable" id="enable" />Enable
<input type="text" id="name" name="name" disabled />


<script>

window.onload=function(){
    document.getElementById('enable').onchange=function(){
        var txt = document.getElementById('name');
        txt.disabled = !this.checked;
    };
};

</script>



Is there any way to make Bokeh's CheckboxGroup scrollable?

I am trying to make a Bokeh dashboard where the user can select what they want plotted from a very long list of options. I am using CheckboxGroup like so:

 product_select = CheckboxGroup(labels = sorted(df['products'].unique()))

The list of products is very long, so I'd like to be able to limit its height to something reasonable and make the list scrollable. I can't seem to figure out how. If I just add a "height" parameter for product_select above, it does nothing.

I also tried wrapping product_select into a widgetbox of a given height - nothing worked.

Help would be appreciated!




jeudi 24 décembre 2020

Google Scripts: When checkbox true, copy row from sheet A to sheet B. When checkbox false, delete copied row from sheet B

I'm very new to Google Scripts and should really be learning the basics first, but jumped straight into trying to solve a problem for a friend. Have found this code online that is the perfect solution for what I want to achieve, however, the following snippet of code seems to be causing problems and not executing its expected function:

} else if (s.getName() == "Tab1" && r.getColumn() == 1 && r.getValue() == "") {
    // Remove the row from "Tab2" when the checkbox in "Tab1" is unchecked 
    var prop = PropertiesService.getDocumentProperties();
    var targetRow = prop.getProperty(row);
    ss.getSheetByName("Tab2").deleteRow(targetRow);
    Logger.log("Deleted the " + targetRow + "row from " + s.getName());
    prop.deleteProperty(row);

The full code can be seen below:

function onEdit(event) {
// assumes source data in sheet named "Tab1"
// target sheet of move to named "Tab2"
// getColumn with check-boxes is currently set to colu 1 or C
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
var row = r.getRow();
var numColumns = s.getLastColumn();
Logger.log(r.getValue());

if (s.getName() == "Tab1" && r.getColumn() == 1 && r.getValue() == true) {
    // Create the record in "Tab2"
    var prop = PropertiesService.getDocumentProperties();
    var targetSheet = ss.getSheetByName("Tab2");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 2);
    s.getRange(row, 2, 1, numColumns).copyTo(target, { contentsOnly: true });
    // Insert checkbox cell (already checked)
    targetSheet.getRange(target.getRow(), 1).insertCheckboxes().check();
    prop.setProperty(row, target.getRow());
} else if (s.getName() == "Tab1" && r.getColumn() == 1 && r.getValue() == "") {
    // Remove the row from "Tab2" when the checkbox in "Tab1" is unchecked 
    var prop = PropertiesService.getDocumentProperties();
    var targetRow = prop.getProperty(row);
    ss.getSheetByName("Tab2").deleteRow(targetRow);
    Logger.log("Deleted the " + targetRow + "row from " + s.getName());
    prop.deleteProperty(row);
} else if (s.getName() == "Tab2" && r.getColumn() == 1 && r.getValue() == false) {
    // Remove the row from "Tab2" when the checkbox is unchecked and unchecks in "Tab1"
    var prop = PropertiesService.getDocumentProperties();
    s.deleteRow(row);

    // Look the corresponding row in "Tab1"
    var keys = prop.getKeys();
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (prop.getProperty(key) == row) {
            ss.getSheetByName("Tab1").getRange(key, 1).setValue(false);
            prop.deleteProperty(key)
            break;
        }
    }
}

}

Everything is working exactly as I would expect it to (see use cases below), except for when the checkbox in Tab1 is unchecked on row X and the associated row in Tab2 (via PropertiesService) is not deleted... but it should be.

Use Cases:

  1. Checkbox on row X in Tab1 is true - copy row to Tab2 on next available line [WORKING in code above]
  2. Checkbox on row X in Tab1 is then made false (having the row already been copied into Tab2) - delete associated row in Tab2 [NOT WORKING in code above]
  3. Checkbox on row X in Tab2 is made false - delete row in Tab2 and make checkbox of associated row in Tab1 false [WORKING in code above]

Ideally, the code above would be even cleverer and each row would have a unique identifier (this could be added in column A for example) and work more like a relational database, so the code is not dependent on the order of rows being maintained e.g. if the user wanted to insert a new row in between existing rows in the future.

Thank you for any help in advance!




mercredi 23 décembre 2020

Spring Controller interprets checkboxes wrongly after two submits

Disclaimer: I'm not very experienced in coding and learned most of it by myself. There might be a very simple answer to this.


I have a html form consisting of two checkboxes (A) and (B) which submits to a spring controller. The Controller validates that both checkboxes are set. For each checkbox not set an error is set to the BindingResult. If any checkbox is not set the page is reloaded and the binding result errors are shown.

My problem: Two following submits with different boxes checked can be detected as "both have been checked".

Reproduction

First submit

  • Check only one checkbox (A) of the two checkboxes
  • Delete the other checkbox (B) using F12 debug editor in Chrome
  • Submit

Result: Browser network analysis tab shows that only one checkbox (A) is submitted as expected. As a result in the controller the value for checkbox (A) is true and value for the missing checkbox (B) is false. So far so good.

Second submit With the following steps I get the alleged problem:

  • Check the previously deleted checkbox (B)
  • Delete the previously checked checkbox (A) using F12 debug editor in Chrome
  • Submit

Result: In the controller now both values for the checkboxes (A) and (B) are true while I would expect only (B) to be true

Simplified Code

html form

<form th:action="@{${URL_FEEDBACK_START}}" th:field="${participant}" th:object="${participant}" method="post">
    <input type="hidden" th:field="*{project}" />
    <input type="checkbox" id="priceGameAccepted" th:field="*{priceGameAccepted}" class="form-check-input" required="required" />
    <input type="checkbox" id="dataPrivacyAccepted" th:field="*{dataPrivacyAccepted}" class="form-check-input" required="required" />
    <div class="form-group mb-0">
        <div>
            <button type="submit" id="submit" class="btn btn-primary">
                Zum Feedback!<br /><i class="fas fa-step-forward"></i>
            </button>
        </div>
    </div>
</form>

controller

@PostMapping(path = "/submit")
public String submit(Model model,
        HttpSession session,
        @ModelAttribute(SessionAttributeHelper.PROJECT) Project project,
        @ModelAttribute(SessionAttributeHelper.PARTICIPANT) @Valid Participant participant,
        BindingResult bindingResult) {

    try {
        validateOptionalPriceGameAccepted(project, participant);
        validateDataPrivacyAccepted(participant);
        
            [... here would be the following code]

    } catch (DataPrivacyNotAcceptedException e) {
        bindingResult.addError(new FieldError("participant", "dataPrivacyAccepted", e.getMessage()));
        return backToForm(model, project);
        
    } catch (PriceGameNotAcceptedException e) {
        bindingResult.addError(new FieldError("participant", "priceGameAccepted", e.getMessage()));
        return backToForm(model, project);
    }
}

validation methods

private void validatePriceGameAccepted(Project project, Participant participant) throws PriceGameNotAcceptedException {
    boolean priceGameStatementAccepted = participant.isPriceGameAccepted();
    if(project.isPricegame() && ! priceGameStatementAccepted) {
        throw new PriceGameNotAcceptedException();
    }       
}

private void validateDataPrivacyAccepted(@Valid Participant participant) throws DataPrivacyNotAcceptedException {
    boolean dataPrivacyStatementAccepted = participant.isDataPrivacyAccepted();
    if(! dataPrivacyStatementAccepted) {
        throw new DataPrivacyNotAcceptedException();
    }
}

software Java 11 with Spring and Thymeleaf template engine, which might be not the problem here.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.1</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

Thoughts

Is there some spring web or data feature that I don't see or understand?




Mute Function for React App on iOS Mobile Devices

I recently added a checkbox to my app that functions as a toggle switch for the mute function I created. It works fine on all desktop browsers (Chrome, Safari, Mozilla, and Edge) and on Android devices, but for some reason, it will not work on mobile iOS devices (iPhone 12 iOS v14.1, and iPad iOS v14.1).

Here is my code, minus excess for readability.

const Header = () => {
  
  ...
  
  const [mute, setMute] = useState(false);
  const location = useLocation();

  ...
  
  const toggleMute = (check: boolean) => {
    setMute(check);
    if (check) audioFiles[`${location.pathname.substr(1)}_${gender}`].volume = 0;
    else audioFiles[`${location.pathname.substr(1)}_${gender}`].volume = 1;
  };
  
  return (
    <div>
      <AppBar position="fixed">

        ...

        <div>
          <input
            type="checkbox"
            name="mute"
            id="mute"
            onClick={(event) => toggleMute(event.currentTarget.checked)}
            checked={mute}
            disabled={location.pathname.endsWith('home')}
          />{' '}
          Mute
        </div>

        ...

      </AppBar>
    </div>
  );
}

I can click on the checkbox and it will read as checked, but the mute toggle doesn't seem to trigger.

I tried using onChange both instead of and with the onClick, but it didn't make a difference that I could see.

NOTE: The audio files are saved in an array, accessible throughout the app, and named based on the location and the gender the user selects.

Why would this work everywhere else, but not on mobile iOS?

I can provide more code if needed.




Toggle not working for material ui check boxes when printed in loop

I am trying to print checkboxes of 4 per a row, where row and values of these checkboxes comes dynamically (row count may vary )

below is my jsx code

matrix.map((row, index) => (
                  <TableRow key={index}>
                    <TableCell align="left">
                      {row.roleDescription}
                    </TableCell>
                    <TableCell align="right">
                      <FormControlLabel
                        control={
                          <Checkbox
                            onChange={(e) =>
                              setChecked({
                                ...checked,
                                [e.target.name]: e.target.checked,
                              })
                            }
                            name={row.roleCode + `_readAccess`}
                            checked={(e) => checked[e.target.name]}
                            color="primary"
                          />
                        }
                        label="Read"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <FormControlLabel
                        control={
                          <Checkbox
                            value={
                              row.writeAccess === null ? 0 : row.writeAccess
                            }
                            onChange={(e) => {}}
                            name="readAccess"
                            color="primary"
                          />
                        }
                        label="Write"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <FormControlLabel
                        control={
                          <Checkbox
                            value={
                              row.checkerAccess === null
                                ? 0
                                : row.checkerAccess
                            }
                            onChange={(e) =>
                              setMatrixForm({
                                ...setMatrixForm,
                                checkerAccess: e.target.checked,
                              })
                            }
                            checked={
                              row.writeAccess &&
                              row.writeAccess !== "" &&
                              row.writeAccess === 1
                                ? true
                                : false
                            }
                            name="checkerAccess"
                            color="primary"
                          />
                        }
                        label="Checker"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <FormControlLabel
                        control={
                          <Checkbox
                            checked={
                              row.readAccess &&
                              row.readAccess !== "" &&
                              row.readAccess === 1
                                ? true
                                : false
                            }
                            name="readAccess"
                            color="primary"
                          />
                        }
                        label="Maker"
                      />
                    </TableCell>
                  </TableRow>
                ))}

After fetching the matix data I am setting state variable const[checked, setChecked] = useState([]) as below

.then((rec) => {
    if (rec.status === 200) {
      let chk = [];

      rec.data.data.map((item, idx) => {
        var obj = {};
        obj[item.roleDescription + `_readAccess`] = item.readAccess;
        chk.push(obj);
        obj[item.roleDescription + `_writeAccess`] = item.writeAccess;
        chk.push(obj);
        obj[item.roleDescription + `_checkerAccess`] = item.checkerAccess;
        chk.push(obj);
        obj[item.roleDescription + `_makerAccess`] = item.makerAccess;
        chk.push(obj);
      });

      setChecked(chk);



    }
  })

what I have tried, is since my rows which are changing dynamically I created state variable entries with as rowName + one of check box label , so when onChange triggered on CheckBox it should change the state and check box need to be toggeled.

but Check box are not getting toggled,

Pelse help. thx




mardi 22 décembre 2020

Kivy: how to update a bool outside class

The bool is currently updated when I click on and off the checkbox however when I click the button it will always print the default value I define at the start. How can I update a bool that is outside the class, so that when I click the button and call the function, it updates the bool?

Also, how can I call a function like this when clicking the button, that is outside of the class?

Thanks

someBool = False


def someFunction():
    print(someBool)



class MyGridLayout(GridLayout):
    def __init__(self, **kwargs):
        #grid layout constructor
        super(MyGridLayout, self).__init__(**kwargs)

        #set columns for the layout
        self.cols = 2

        self.add_widget(Label(text="checkbox"))
        self.checkbox= CheckBox(active = False)
        self.add_widget(self.checkbox)

        #this will bind the label and checkbox
        self.checkbox.bind(active = self.checkboxActive)

        self.button= Button(text="Button")
        self.button.bind(on_press=someFunction)
        self.add_widget(self.button)

    def checkboxActive(self, checkbox, value):
        if value:
            someBool = True
        else:
            someBool = False


class MyApp(App):
    def build(self):
        return MyGridLayout()


if __name__ == '__main__':
    MyApp().run()



-ASP DOT NET CORE- I want to have access to the list of CheckBoxes (Value) from my View on my Controller's public async Task

In my view I have a code similar to this:

@model C.Models.CM
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div class="form-group">
                <label asp-for="Date" class="control-label"></label>
                <input asp-for="Date" class="form-control" />
                <span asp-validation-for="Date" class="text-danger"></span>
            </div>

            <div class="row">
                <select data-placeholder="Select Item" asp-for="IdItem" class="form-control" asp-items="ViewBag.Items"></select>
            </div>

            <div class="form-group">
                <input id="cboAll" type="checkbox" value="CheckAll / unCheck" /> All<br />
                @foreach (var cdos in ViewBag.Modelon.Cdos)
                { 
                    <input id=@cdos.Id type="checkbox" value=@cdos.Id class="w3-check" />@cdos.Name<br />
                }
            </div>

            <div class="form-group">
                <input id="cboAll" type="checkbox" value="CheckAll / unCheck" /> All<br />
                @foreach (var ctres in ViewBag.Modelon.Ctres)
                {
                    <input id=@ctres.Id type="checkbox" value=@ctres.Id class="w3-check" />@ctres.Name<br />
                }
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

The important thing to understand here is that, this Code generates an amount N of CheckBox which depend on data inserted on the Database, in addition to other attached information in the view, the view looks like this:

My View

So, as you see the amount of CheckBox goes from 1 to N. My problem is the following, I can't understand how to obtain the CheckBox group data in my controller. I don't even know if this information is actually being sent to the controller. I have the following code in my controller:

        public async Task<IActionResult> Create(List<string> slct)
    {
        System.Diagnostics.Debug.WriteLine("test");
        foreach (string value in slct)
        {
            System.Diagnostics.Debug.WriteLine(value);
            };
        System.Diagnostics.Debug.WriteLine("test");

        return RedirectToAction(nameof(Index));
    } 

I would like that my code does certain things depending on the information that comes from the CheckBoxs, right now I was trying to see if all the data from the View was being sent as a slct List, but that isn't the case because this code doesn't print anything in the debug screen except for the "test".

I've done my research, and people recommended the following links to learn how to load related data in the controller.

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-5.0 https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/update-related-data?view=aspnetcore-5.0

The problem is that no matter how much I read the tutorials, I can't understand them or solve how to apply them to my case, because they work with a much more complex example, and the fact that the code I need to use is of the type await _context.Model.Include(a => a.Thing1).Include(b => b.Thing2) .ThenInclude(c => c.Whatiscwhatisbwat??) certainly doesn't help (the writing of that code is very confusing for me and I am having problems understanding what it does).

So, Ok someone could help me with an explanation somewhat simpler than the one from the tutorials, to solve this? In the method that I mention from the controller, I want to have access to the two groups of CheckBoxs from the View and their selected values, in any format (like a List, Array, etc), I know that I must implement an include code but I don't know how to do it, or if there is a simpler solution.




How to find the nex checkbox check in a form

I am trying to do something may be easy for some of you, but I spend hours to do it.

I have a form with checkbox as the following

<form class="form-style" id="st-21">
  <label style="margin-right:10px">
    <input type="checkbox" data-type="2" data-sensor="1" data-family="2" name="b1" style="margin-right:10px" checked="checked">
      Température bas(C)
    </label>
  <label style="margin-right:10px">
    <input type="checkbox" data-type="2" data-sensor="4" data-family="2" name="b4" style="margin-right:10px" checked="checked">
      Température haut(C)
   </label>
  <label style="margin-right:10px">
    <input type="checkbox" data-type="5" data-sensor="21" data-family="4" name="ba" style="margin-right:10px" checked="checked">
      Batterie(V)
  </label>
  <label style="margin-right:10px">
    <input type="checkbox" data-type="6" data-sensor="18" data-family="5" name="an" style="margin-right:10px">
      Vitesse du vent(km/h)
  </label>
  <label style="margin-right:10px">
    <input type="checkbox" data-type="7" data-sensor="19" data-family="5" name="wd" style="margin-right:10px">
      Direction du vent(Degré)
  </label>
  <label style="margin-right:10px">
    <input type="checkbox" data-type="8" data-sensor="20" data-family="6" name="wd" style="margin-right:10px">
      Radiation solaire (W/m2)
  </label>
</form>

Only two of them can be selected. I check a third checkbox, it must unselect the next checked checkbox

I do not know if it's a good start, but I would start with

$(".form-style").on('change',function() {
        var sList=[];
        var i = 0;
        $(this).find('input:checkbox').each(function () {
          if($(this).is(':checked'))
          {
            sList[i] = parseInt($(this).data("type"));
          }
        });
});

If look at all checkbox in my form, and add an index in sList array, when it found a checkbox checked.

If I check a new checkbox, Q1: is there way to detect which checkbox has been checked.

It look at the checkboxes, and as I checked a new checkbox, I added the following

$(".form-style").on('change',function() {
        var sList=[];
        var i = 0;
        $(this).find('input:checkbox').each(function () {
          if($(this).is(':checked'))
          {
             if(sList.length > 1){ 
                // HOW CAN I REMOVE THE NEXT CHECKED CHECKBOX
             }
            sList[i] = parseInt($(this).data("type"));
          }
        });
});

But from that point, I need to remove the next checkbox which has been checked. in order to have always two checked.

Could help me to find the next checked checkbox, or tell me how can I make it matter

Many thanks




If two parent checkbox checked and i check child checkbox values respectively then id of both checkbox should be store in database in Codeigniter

enter image description here

If two parent checkboxes checked and I checked their child checkbox values respectively then id of both parent and child checkbox should be store in database. This code is storing same data two times. But I want to store checkboxes value one time. Thanks for consideration!!

View:

<div>
    <div class="form-group" >
        <label class="control-label col-xs-12 col-sm-3 no-padding-right"
            for="last_name">Assign Inspection:</label>
        <div class="col-xs-12 col-sm-9">
            <div class="clearfix">
                <?php foreach($aInspection as $a)
                {?> 
                    <input type="checkbox" name="inspection_element_id[]" class="checkbox"  value = "<?php echo $a->id;?>"  />
                    <label><?php echo $a->name;?></label>
                    
                <?php
                } 
                ?>

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

jQuery / AJAX Code:

 <script type='text/javascript'>
    $(document).ready(function(){
    $(".checkbox").click(function(){
    if($(this).is(':checked'))
    {
    var value=$(".checkbox:checked").val();
    loadPagination(value);
    }
    else
    {
    console.log("NO");
    $('#dvDatatype').empty();
    }
    });
    function loadPagination(pagno){
    console.log('pagno',pagno)
    $.ajax({
    url: '<?=base_url()?>index.php/Inspection/show_inspection/'+pagno,
    type: 'get',
    dataType: 'json',
    data:{pagno:pagno},
    success: function(data){
    createTable(data);
    }
    });
    }
    function createTable(result)
    {
    console.log(result);
    for(index in result)
    {
    console.log(index); 
    var id = result[index].id;
    var ins_id = result['inspection_id'];
    var datatype=result[index].datatype_name;
    var input;
    input+= '<input type="hidden" name="inspection_id[]" value ="'+ins_id+'">';
    input+= '<input type="checkbox" name="datatype_id[]" value ="'+id+'">';
    input+='&nbsp;<label>'+datatype+'</label>';
    input+='<br>';    
    }
    $('#dvDatatype').append(input);
    }
    });
    </script>

Controller:

function show_inspection($pageno)
{
$data['datatype'] = $this->dtModel->get_all_datatype();
$data['inspection_id'] = $pageno;
echo json_encode($data['datatype']);
}
function add()
{   
    $data['designation'] = $this->dModel->get_all_designation();
    $data['aInspection'] = $this->iModel->get_all_inspection_element(); 
    $data['datatype'] = $this->dtModel->get_all_datatype(); 
    $this->load->library('form_validation');
    $this->form_validation->set_rules('designation_id','Designation ID','required');
    
    if($this->form_validation->run())     
    {   
        
        $params = array(
            'designation_id' => $this->input->post('designation_id'),
            'assigned_date'=>$this->input->post('assigned_date'),
            'completion_date'=>$this->input->post('completion_date'),               
        );
        
        $inspection_id = $this->Tbl_inspection_model->add_inspection($params);
        

        $checkbox = $this->input->post('inspection_element_id');
        $checkbox1 = $this->input->post('datatype_id');
        foreach ($checkbox as $a) 
        {
            foreach ($checkbox1 as $b)  
            {
            
            $params_checkbox1 = array(
                'inspection_element_id'=>$a,
                'datatype_id'=>$b,
                'frequency'=>$this->input->post('frequency'),
                'inspection_id'=>$inspection_id,
            );
            $this->Tbl_inspection_model->add_inspection_id($params_checkbox1);
            }
        }
        $this->session->set_flashdata('type', 'success');
        $this->session->set_flashdata('msg', 'Inspection Added Successfully!');
       redirect('inspection/index');
    
    }
    else
    {            
        $data['_view'] = 'inspection/add';
        $this->load->view('layouts/main',$data);
    }
}

Model:

function add_inspection_element($params)
{
    $this->db->insert('tbl_inspection_element',$params);
    return $this->db->insert_id();
}

Tbl_inspection:

|Inspection Element ID| |   Datatype ID  | 
|  (Parent Checkbox)  | |(Child Checkbox)|
|_____________________| |________________|
|         4           | |        3       |
|         4           | |        5       |
|         6           | |        8       |
|         6           | |        12      |



How does one, from a checkbox group and preferably with jQuery, collect array data and does assign this data to a hidden target element's value?

I have a group of equally named checkboxes ...

<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />

and a hidden form element ...

<input type="hidden" class="target" name="target[]" value="" />

Using jQuery, I want to copy all checked checkbox values in form of a value-list in its stringified array literal notation to the hidden target element's value.

I have tried the following ...

$(".checkbox").each(function(idx, val) {

  $('input[name="target['+idx+']"]').val(this.value);
});

... without success. How can I generate and assign the correct result?




Checkbox inside a spinner validation

I have multiple checkboxes inside a spinner. How to validate it when nothing is selected.

if(spinner_inperson.getSelectedItem()!="select"){
        //Toast.makeText(spinner_crop_sown.this, "Unesite ime", Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), "Please select Inperson Spinner Dropdown", Toast.LENGTH_LONG).show();
        return false;
    }

Here is the sample code which I tried




Django 3.1.4: Get checkbox values in a function in views.py

I successfully did it for input text and now I would like to do it with checkboxes. I don't want to store checkbox values in a database. I just want to get it in a function in views.py I was not able to find how to do it. Thank you for your help!




lundi 21 décembre 2020

Hide and Show dropDown on checkbox check/uncheck

I have an issue, I need to show and hide DropDown/Selects field based on Checkbox's state. Means when checkbox state is checked I need to show Dropdown and when I uncheck it should hide. I have attached a code of this component below. As you can see I have 3 Dropdowns created already, but I need to hide/show them by checking/unchecking one single checkbox

import React, { useState, useEffect } from "react";
import { Button } from "../../components/Button";
import { Checkbox } from "../../components/Checkbox";
import { FormBuilder } from "../../components/FormBuilder";
import { Grid, GridCell, GridRow } from "../../components/Grid";
import { LinearProgress } from "../../components/LinearProgress";
import { Select } from "../../components/Select";
import { TextField } from "../../components/TextField";
import { Name } from "../../models/Name";
import { Option } from "../../models/Option";
import { DynamicForm } from "../../models/DynamicForm";
import "./index.css";
import { Organization } from "../../models/Organization";
import { request } from "../../api";
import { serialize } from "class-transformer";
import { CodingTemplate } from "../../models/CodingTemplate";
import { useHistory } from "react-router-dom";
import { useRef } from "react";

const NUMBER_OF_STEPS = 3;
const screen = {
  first: 1,
  second: 2,
  third: 3,
};

const FormDetails = ({ dynamicForm }: { dynamicForm: DynamicForm }) => {
  const check1 = useRef();

  return (
    <div>
      <h4 style=>Данные формы</h4>
      <Grid>
        
        <GridRow>
          <GridCell span={5}>
            <Checkbox
              label="CHECKBOX"
              onChange={(value) => (dynamicForm.needExtraApprove = value)}
              defaultChecked={dynamicForm.needExtraApprove}
            />
          </GridCell>
        </GridRow>
        <GridRow>
          <GridCell span={4}>             
              <Select<Option>
                required
                //defaultValue={dynamicForm.departmentHash}
                label="Select to show/hide"
                type={Option}
                //api="/state_schedule/departments-with-journals/"
                defaultOptions={defaultOptions}
                //onChange={(value: Option) => dynamicForm.departmentHash = value}
              />
            }
          </GridCell>
          <GridCell span={4}>
            <Select<Option>
              required
              //defaultValue={dynamicForm.departmentHash}
              label="Select to show/hide"
              type={Option}
              //api="/state_schedule/departments-with-journals/"
              defaultOptions={defaultOptions}
              //onChange={(value: Option) => dynamicForm.departmentHash = value}
            />
          </GridCell>
          <GridCell span={4}>
            <Select<Option>
              required
              //defaultValue={dynamicForm.departmentHash}
              label="Select to show/hide"
              type={Option}
              //api="/state_schedule/departments-with-journals/"
              defaultOptions={defaultOptions}
              //onChange={(value: Option) => dynamicForm.departmentHash = value}
            />
          </GridCell>
        </GridRow>
      </Grid>
    </div>
  );
};

const FormFields = ({ dynamicForm }: { dynamicForm: DynamicForm }) => (
  <div>
    <h4 style=>ASD</h4>
    <FormBuilder dynamicForm={dynamicForm} />
  </div>
);

export default () => {
  const [step, setStep] = useState(1);
  const [dynamicForm, setDynamicForm] = useState<DynamicForm>(
    new DynamicForm()
  );
  let progress = parseFloat(((step - 1) * (1 / NUMBER_OF_STEPS)).toFixed(2));
  const onBackButtonPress = () => {
    if (step > 0) {
      setStep((prev) => prev - 1);
    }
  };

  const onNextButtonPress = () => {
    event.preventDefault();

    if (step < screen.third) {
      setStep((prev) => prev + 1);
    } else {
      console.log("submit!");
      //submit
    }
    // if (step < screen.third) {
    //   setStep((prev) => prev + 1);
    // } else {
    //   console.log("submit!");
    //   //submit
    // }
  };

  const history = useHistory();
  const onSubmitTest = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      console.log(dynamicForm);
      await request("/service-desk/forms/", {
        method: "POST",
        body: serialize(dynamicForm),
      });

      history.push({
        pathname: "/service-desk/application-form",
      });
    } catch (error) {
      console.log(error);
      alert("ERROR");
    }
  };

  let content = <SubDivision dynamicForm={dynamicForm} />;
  let nextBtnLabel = "NEXT";
  if (step === screen.second) {
    content = <FormDetails dynamicForm={dynamicForm} />;
  } else if (step === screen.third) {
    content = <FormFields dynamicForm={dynamicForm} />;
  }

  return (
    <form onSubmit={onSubmitTest} noValidate={step === screen.third}>
      <LinearProgress progress={progress} determinate />
      {content}
      <div className="request-btn-container">
        <Button
          label="BACK"
          disabled={step == 1}
          onClick={onBackButtonPress}
        />
        {step === 3 ? (
          <Button label="SAVE" raised type="submit" />
        ) : (
          <Button
            label="NEXT"
            disabled={step == 3}
            onClick={onNextButtonPress}
          />
        )}
      </div>
    </form>
  );
};

. Thank you for any tip or advice!




Content of the page back to normal (as it was before) when the checkbox input is unchecked

SO I wanted to change few contents of the page when the checkbox input is checked and bring everything back to it was before when the checkbox is unchecked.

    <div class="switch">
        <input type="checkbox" name="checkbox" id="checkbox" onchange="darkmode(this)" />
    </div>

    <section id="section">
    <p>This is a line</p>
    </section>
    <script>
        function darkmode(checkboxElem) {
          if (checkboxElem.checked) {
            document.body.style.backgroundColor = "black";
            document.getElementById("checkbox").style.borderColor = "white";
            document.getElementById("section").style.color ="white"; 
          }else {
            document.body.style.backgroundColor = "white";
            document.getElementById("checkbox").style.borderColor = "black";
            document.getElementById("section").style.color ="black"; 
          }
        }   
    </script>

I figured I can do that by giving value to every content that was changed. In the 'else' statement I will have to give every content it's the value of 'as it was before' Doing this will take a lot of time and I will have to write everything twice (in CSS and Javascript).

If there is a way to bring everything to default when the checkbox is unchecked without without giving every element their pervious value. Please, let me know.

Thank you




check and uncheck the checkbox by row

Good Day all...I'm having a multiple row which is fetched from my DB by foreach loop.

And I have 2 checkboxes in each row, What I'm trying is... If I check the 1st checkbox mean automatically the 2nd checkbox need to check.

for that I'm using ID to select that 2nd checkbox, Now because of that id is same for every row, if I select 1st row ,1st checkbox mean it's selecting all the second check box. But what I need is to get that particular selected row's 2nd checkbox need to be checked. Anyone Help. Sorry for not sharing any live demo like jsfiddle. I hope u guys understand my problem.

<thead>
<th><input type="checkbox" id="select_all"></th>
</thead>

<?php foreach ($category_details as $key => $category_detail): ?>
<tr>
<td>

  <input type="checkbox" class="checkbox" id="select_img" name="ids[]" value="<?php echo $category_detail['id'];?>"/>
  <input type="checkbox" class="checkbox checkimg" name="imgs[]" value="<?php echo  $category_detail['category_image'];?>"/>

</td>

<td>...</td> <!-- etc -->
</tr>
<?php endforeach ?>
    $(document).ready(function(){
    $('#select_all').on('click',function(){
        if(this.checked){
            $('.checkbox').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkbox').each(function(){
                this.checked = false;
            });
        }
    });

    $('#select_img').on('click',function(){
        if(this.checked){
            $('.checkimg').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkimg').each(function(){
                this.checked = false;
            });
        }
    });

    $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#select_all').prop('checked',true);
        }else{
            $('#select_all').prop('checked',false);
        }
    });
});



Risk matrix data collection on mobile

Complete noob here. I'm trying to build a risk matrix data collection tool with Google Sheets that can record each time a user tap a checkbox, with a prompt confirming the recording of said data. Checkbox has to uncheck itself but still record the data.

function onEdit(e) {
 if(e.range.getSheet().getName()=='Sheet1') {
    if(e.range.getA1Notation()=='B3' && e.value=="TRUE") {
      SpreadsheetApp.getUi().alert('You've clicked B3. Your intervention has been recorded Unlikely - Minor impact');
      e.range.setValue("FALSE");
    }
  }else{
    return;
  }
}

How can I add code to record each time that cell (B3 in the example) has been checked? Thanks in advance




Jquery Switchery checkbox disable created new checkbox on page

i struggle to disable the Switchery checkbox but it creates me another Switchery checkbox on page . i first define the checkbox which is working great:

<div class="form-group">
    <label class="col-md-2">
        Additional Options
    </label>
    <div class="col-md-3">
        <div class="">
            <label>
                <input type="checkbox" id="foo1"
                       name="foo1" class="js-switch"/>
            </label>
        </div>
    </div>
</div>

now after the page loaded, i dynamically want to disable the checkbox so I do :

var foo1=  document.getElementById('foo1')
var switchery = new Switchery(foo1);
switchery.disable();

it disable the checkbox BUT it creates me new checkbox near the one i defined already i don't understand why enter image description here




Styling a checkbox label [closed]

I am trying to style my checkbox label and having a heck of a time with it. It seems like no matter what i try the checkbox label is taking all CSS elements applied to the entire site, even when i use "!important". Any ideas?

Trying to simply reduce the line-height most importantly.

But the CSS i want is not being applied how i would expect




Is there a way to select a TextBox input if a checkbox is ticked? VBA Excel

As you can see in the below image, I have several checkboxes representing measures and the last two are supposed allow for additional measures. The textboxes on the front allow the user to specify the name of their measure.

enter image description here

I was able to successfully send the name (caption) of the ticked checkboxes to a Listbox using the following code:

Dim ctrl As Control

For Each ctrl In Me.Controls
    If TypeName(ctrl) = "CheckBox" Then
        If ctrl.Value = True Then
            ListBox1.AddItem ctrl.Caption
        End If
    End If
Next ctrl

However, if the user selects the "Additional measures" checkbox I want what they inputted in the textboxes to be added to the list box, instead of the checkbox caption.

Is there any way I can do that?




How to calculate the value of checked box?

I have table which contain following data structure,

#table

ID    payroll_cat_name payroll_cat_code category_type   amount
1     Provident Fund    PF               dedution        1000
2     Basic Pay         BC               earning         35000
3     Travelling        TA               earning         6500
4     Home Allowance    HM               earning         12000
5     Tax               TX               dedution        500

I am fetching this all data with this code below,

 <?php
 include "../db.php";
$select_payroll_category = "SELECT * from payroll_category";
$employee_payroll_result = mysqli_query($con,$select_payroll_category);
?>
<table>
    <thead style="color: #222426;">
        <tr>
            <th>
                <div class="form-check">
                    <input type="checkbox" class="form-check-input checkAll">
                    <label class="form-check-label">ID</label>
                </div>
            </th>
            <th>Category name</th>
            <th>Category code</th>
            <th>Category Type</th>
            <th>Category Amount</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        while ($row = mysqli_fetch_array($employee_payroll_result)) {
            echo "<tr style='color:#222426;'>
                    <td>
                    <div class='form-check'>
                    <input type='checkbox' name='payroll_group' value=".$row["amount"]."class='form-check-input'>
                    <label class='form-check-label' style='color:#fff;'>".$row["payroll_cat_id"]."</label>
                    </div>
                    </td>
                    <td>".$row["payroll_cat_name"]."</td>
                    <td>".$row["payroll_cat_code"]."</td>
                    <td>".$row["category_type"]."</td>
                    <td>".$row["amount"]."</td>
                    
                  </tr>";
                    }
                    ?>
                        
                    </tbody>
                </table>
                <button id="button">save</button>
                <p id="result"></p>

Now On buttonclick I want to calculate the amount based on category_type,

If the category is earning then it will add the amount ,

And if the category is dedution then it will subtract the amount,

Using jquery, I want to perform this

Following is my jquery code which I have tried,

        $(document).ready(function(){
              $("#button").click(function(){
            var favorite = [];
           $.each($("input[name='payroll_group']:checked"), function(){
                favorite.push($(this).val());
            });
           var total = 
            console.log("My favourite sports are: " + favorite);
            $('#result').html(favorite);

        }); 
        })
    </script>

By using this code I m getting 1000,35000,6500 the value of amount Which I have ticked in checkbox