jeudi 31 mars 2022

Why isn't the "Checkbox hack" working on my 3d element?

My "checkbox hack" isn't doing anything when in the toggled state.

I have a 3d cube that is rotating and I want it to sorta spin and get bigger when it is clicked on, so I tried using the checkbox hack in order to change the animation when it is in the toggled state. However, regardless of what I do (i.e. change background color of elements, change font size, change scale of .cube, etc.) Absolutely nothing happens when the label is in toggle state. Can someone help me figure out what I did wrong?

Here is my current code.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  width: 100vw;
  height: auto;
}

body {
  width: 100%;
  height: 100%;
  background-color: antiquewhite;
  color: #333;
  font-size: 100px;
}

.cube {
  transform-style: preserve-3d;
  transform-origin: right;
  top: calc(50%);
  left: calc(50%);
  position: absolute;
  animation: rotateCube 8s infinite linear;
}

label {
  position: absolute;
  top: calc(50% - 1em);
  left: calc(50% - 1em);
  height: 2em;
  width: 2em;
  z-index: 10;
}

#toggle {
  position: absolute;
  opacity: 1;
}

.face {
  height: 2em;
  width: 2em;
  background-color: whitesmoke;
  position: absolute;
  margin: -1em;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 1px 1px 2px #555, inset -1px 0px 2px #555;
}

.face span {
  font-size: 50px;
}

.front {
  transform: translateZ(1em);
}

.right {
  transform: rotateY(90deg) translateZ(1em);
}

.back {
  transform: rotateY(180deg) translateZ(1em);
}

.left {
  transform: rotateY(-90deg) translateZ(1em);
}

.top {
  transform: rotateX(90deg) translateZ(1em);
}

.bottom {
  transform: rotateX(-90deg) translateZ(1em)
}

input:checked~.face {
  background-color: blue;
  animation: rotateCube2 8s forwards;
}

@keyframes rotateCube {
  0% {
    transform: rotateY(0deg) rotateX(-15deg);
  }
  50% {
    transform: rotateY(360deg) rotateX(15deg)
  }
  100% {
    transform: rotateY(720deg) rotateX(-15deg)
  }
}

@keyframes rotateCube2 {
  50% {
    transform: rotateY(90deg) rotateX(90deg);
  }
  100% {
    transform: rotateY(180deg) rotateX(180deg);
  }
}
<div class="cube-button">
  <input type="checkbox" id="toggle">
  <label for="toggle"></label>
  <div class="cube">
    <div class="face front"><span>Click Me</span></div>
    <div class="face left"></div>
    <div class="face right"></div>
    <div class="face back"></div>
    <div class="face top"></div>
    <div class="face bottom"></div>
  </div>
</div>



How to change state to unchecked/false when tapping on a checkbox in indeterminate state. React MUI Checkbox

I have a header checkbox that should act as a select all or deselect all. I also have an indeterminate state for it when some records are selected but not all.

The behavior I want is:

When the user taps on the header checkbox while it is in the indeterminate state, it should deselect all the records. But instead, it is selecting all.

<Checkbox
    indeterminate={numSelected > 0 && numSelected < rowCount}
    checked={rowCount > 0 && numSelected === rowCount}
    onChange={onSelectAllClick}
/>

numSelected is the number of rows selected.

Description Image of Behavior




How to change state to unchecked/false when tapping on a checkbox in intermediate state. React MUI Checkbox

I have a header checkbox that should act as a select all or deselect all. I also have an intermediate state for it when some records are selected but not all.

The behavior I want is:

When the user taps on the header checkbox while it is in the intermediate state, it should deselect all the records. But instead, it is selecting all.

<Checkbox
    indeterminate={numSelected > 0 && numSelected < rowCount}
    checked={rowCount > 0 && numSelected === rowCount}
    onChange={onSelectAllClick}
/>

Description Image of Behavior




mercredi 30 mars 2022

How can I tell state of checkbox in Google Docs via api?

If I create a Google document with a checklist, how do I tell whether an item is checked or unchecked? When I diff the document json, it is the same in either state (except for revision number).

Starting with a blank document, sample code to create a checkbox:

    List<Request> requests = new ArrayList<>();  
    //Checkbox
    requests.add(new Request().setInsertText(new InsertTextRequest()
            .setText("\n\n")
            .setLocation(new Location().setIndex(1))));
    requests.add(new Request().setInsertText(new InsertTextRequest()
            .setText("MARK\n")
            .setLocation(new Location().setIndex(2))));
    requests.add(new Request().setCreateParagraphBullets(
            new CreateParagraphBulletsRequest()
                    .setRange(new Range()
                            .setStartIndex(2)
                            .setEndIndex(3))
                    .setBulletPreset("BULLET_CHECKBOX")));

    BatchUpdateDocumentRequest batchUpdateDocumentRequest = new BatchUpdateDocumentRequest();
    BatchUpdateDocumentResponse response = service.documents().batchUpdate(documentId, batchUpdateDocumentRequest.setRequests(requests)).execute();

`

I can click or unclick the checkbox, but the document remains unchanged when I look at it via:

Document document = service.documents().get(documentId).execute(); l.info(document.toPrettyString());

Anyone have experience with this?




Why my value of array is changing when I'm setting state of other object in react?

'''
const [dataToAdd, setDataToAdd] = useState({
    name: '', gender: '', email: '', imgUrl: '', website: '', skills: ''
});

const handleEnrollClick = () => {
    console.log(skillsAdd.toString())
    setStudentData([...studentData, dataToAdd]);
    setDataToAdd({ name: '', gender: '', email: '', imgUrl: '', website: '', skills: '' });
}

const onChange = (e) => {
    setDataToAdd({ ...dataToAdd, [e.target.name]: e.target.value });
}

let skillsAdd = []
const onChangeRadio = (e) => {
    if (e.target.checked) {
        skillsAdd.push(e.target.value);
    } else if (!e.target.checked) {
        skillsAdd.splice(skillsAdd.indexOf(e.target.value), 1);
    }
    
    console.log(skillsAdd)
    // setDataToAdd({...dataToAdd, skills: skillsAdd.toString()});
}
'''

There are 3 checkboxes, 'JAVA', 'HTML' and 'CSS'. The logic in 'if' and 'else if' adds and removes these values of checkboxes i.e 'JAVA', 'HTML' and 'CSS' in the array 'skillsAdd' which works perfectly fine. But when I'm setting the state of 'dataToAdd' by using function 'setDataToAdd' then the 'skillsAdd' array changes totally. Following is the output:

Output when 'setDataToAdd' is commented and all three checkboxes i.e 'JAVA', 'HTML' and 'CSS' are checked: ['java', 'html', 'css']

Output when 'setDataToAdd' is not commented and all three checkboxes i.e 'JAVA', 'HTML' and 'CSS' are checked: ['css']

When 'setDataToAdd' is written then it should only affect 'dataToAdd', but it is affecting 'skillsArray'. How is this possible ?




mardi 29 mars 2022

Kivy CheckBox Activate Outside Designated Area

I have been playing around with this post's code in changing the background image of the CheckBox inorder to ultimately change the boarder/padding - found another post, but seems that there has not been an update(?). Aside from that, I've noticed that when I create a CheckBox, the "area" that has been designated to hold the CheckBox can be used to activate/deactive the CheckBox (see image below).

from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
from kivy.app import App
from kivy.lang import Builder

sm = Builder.load_file('main.kv')


class TestApp(App):
    def build(self):
        return sm
        

if __name__ == '__main__':
    
    TestApp().run()
Screen:  

    BoxLayout:
        size_hint_y: None
        orientation: 'horizontal'       
        Button:
            text: 'Go back'

        CheckBox:
            size_hint_x: None
            width: 60           
            canvas.before:
                Rectangle:
                    source: 'white.png'
                    size: sp(22), sp(22)
                    pos: int(self.center_x - sp(11)), int(self.center_y - sp(11))

enter image description here

All of the area shown in red can be clicked on to activate the button. Why is that? And, how do I limit the activation/deactivation specifically to the actual CheckBox?




Multiple filters in react (search bar & checkbox)

Hi I have a question about multiple filters in react. I have a search bar and checkbox filters and each on their own works great, but if I for example use two filters, only one works. I need them to work together. Does anyone have any idea how to do this?

This is my team.js:

const [genre, setGenre] = useState([]);
const [filteredGenre, setFilteredGenre] = useState([]);

    const handleChange = e => {
        if (e.target.checked) {
            setGenre([...genre, e.target.value]);
            return e;
        } else {
            setGenre(genre.filter(id => id !== e.target.value));
            return e;
        }
    };

    useEffect(() => {
        if (genre.length === 0) {
            setFilteredGenre(players);
        } else {
            setFilteredGenre(
                players.filter(position =>
                    genre.some(category => [position.position].flat().includes(category))
                )
            );
        }
    }, [genre]);


    const [value, setValue] = useState('');
    const handleSearch = (e) => {
        setValue(e.target.value)
    }
    const filteredEvent = players.filter(events => {
        return events.name.toLowerCase().includes(value.toLowerCase());
    });
   
    return (
        <>
            <SectionContent columns={2}>
                <Left>
                    <Filter
                        handleChange={handleSearch}
                        handlePositionChange={handleChange}
                    />
                </Left>
                <Right>
                    <Grid>
                        {filteredGenre.map(info => (
                            <Cards
                                key={info.id}
                                img={info.imgUrl}
                                alt={info.imgAlt}
                                numberInfo={info.number}
                                name={info.name}
                                position={info.position}
                                age={info.age}
                                nationality={info.nationality}
                                value={info.value}
                            />
                        ))}
                    </Grid>
                </Right>
            </SectionContent>
        </>
    );
};



only sumif checkbox is checked?

How do I only sum the amounts for Susan that are checked?

=if(AND(Sheet1!A:A="Susan",Sheet2!N:N=true,sum(Sheet2!M:M,""))))

or

=sumif(AND(Sheet1!A:A="Susan",Sheet2!N:N=true),Sheet2!M:M,""))))

I believe the above snippets are saying that all N:N checkboxes must be checked to be true, or will return false. Anyway they're not working...

Sheet1      Sheet2             
Column A    Column M     Column N
 Tom         100         (un-checked)
 Susan       150         (checked)
 Susan       75          (un-checked)
 Tom         25          (checked)
 Susan       50          (checked)



CSS: How to set url image properly to checked checkbox

I have this scenario, I have this list of checkbox with corresponding image for it, If the checkbox is checked, I want to append black circle at the back of checkbox image

Sample current output:

enter image description here

Sample expected output:

enter image description here

Code for populating checkbox:

<div
                key={item.id}
                className="chk-multiple-badge form-check form-check-inline"
              >
                <input
                  className="chkbox-badge form-check-input"
                  type="checkbox"
                  id={item.id}
                />
                <label
                  htmlFor={item.id}
                  className="form-check-label form-check-label-badge"
                >
                  <Row>
                    <Col>
                      <img
                        className="chk-badge-img"
                        src={item.imgBase64}
                        alt={item.badge_name}
                      />
                    </Col>
                  </Row>
                  <Row>
                    <Col>{item.badge_name}</Col>
                  </Row>
                </label>
              </div>

And CSS for checkbox:

:checked + .form-check-label-badge:before {
  content: url("../../../../assets/images/checkd-badge.png");
  position: absolute;
  cursor: pointer;
}
.chkbox-badge {
  display: none;
}



dimanche 27 mars 2022

Javascript Checkbox.checked Select All Function doesn't work. [Problem Solved] [duplicate]

<script>
       let SelectAll = document.querySelector('input')
        let items = document.querySelectorAll('input:nth-child(n+2)')
        // let a1 = SelectAll.checked
        // console.log(a1)
        

        SelectAll.onclick = function () {
            let SelectAll_status = SelectAll.checked
            console.log(SelectAll_status)
            // console.log(items.length)
            if (a1 = true) { 
          for (var i = 0;i < items.length;i++) {
            items[i].setAttribute("checked", "true");
        
          } } else {
            for (var j = 0;j < items.length;j++) {
            items[j].setAttribute("checked", "false");
            let return1 = items[j].checked
            
          }
          console.log (return1)
        }}
</script>

I use the If condition. But when I deselect the tick. Nothing works. Even the whole part of "Else" doesn't work.

At beginning, I used "items[i].checked= SelectAll.checked " , at console.log , "false" is given to items, but the tick toggle doesn't show. So,I need to use setAttribute. Then I need to use If conditions. And problems appear...

Updated Problem Solved : if (SelectAll_status === true) ,here must be "===" ,not "=" .

for Else , setAttribute is not working. I change it to removeAttribute .It works.

let SelectAll = document.querySelector('input')
        let items = document.querySelectorAll('input:nth-child(n+2)')
       
        SelectAll.onclick = function () {
            let SelectAll_status = SelectAll.checked
            console.log(SelectAll_status)
            if (SelectAll_status === true) { 
          for (var i = 0;i < items.length;i++) {
            items[i].setAttribute("checked", "true");
        
          } } else {
            
            for (var j = 0;j < items.length;j++) {
             
            items[j].removeAttribute("checked");
            
            
          }
          
        }}
  form {
        border: 1px pink solid;
        width: 200px;
        background-image: linear-gradient(
          rgb(255, 226, 255),
          rgb(255, 250, 192)
        );
        color: rgb(121, 121, 121);
        margin: 20px auto;
      }
      hr {
        border: pink 1px solid;
      }
<form action="">
      <input type="checkbox" id="all" name="form1" />
      <label for="opt">Select ALL</label>
      <br />
      <hr />
      <input type="checkbox" id="opt1" name="form1" />
      <label for="opt1">111111</label>
      <br />
      <input type="checkbox" id="opt2" name="form1" ckecked />
      <label for="opt2">222222</label>
      <br />
      <input type="checkbox" id="opt3" name="form1" />
      <label for="opt3">333333</label>
      <br />
      <input type="checkbox" id="opt4" name="form1" />
      <label for="opt4">4444</label>
    </form>



Javascript Checkbox.checked to select all ,cannot be deselect [duplicate]

<script>
       let SelectAll = document.querySelector('input')
        let items = document.querySelectorAll('input:nth-child(n+2)')
        // let a1 = SelectAll.checked
        // console.log(a1)
        

        SelectAll.onclick = function () {
            let SelectAll_status = SelectAll.checked
            console.log(SelectAll_status)
            // console.log(items.length)
            if (a1 = true) { 
          for (var i = 0;i < items.length;i++) {
            items[i].setAttribute("checked", "true");
        
          } } else {
            for (var j = 0;j < items.length;j++) {
            items[j].setAttribute("checked", "false");
            let return1 = items[j].checked
            
          }
          console.log (return1)
        }}
</script>

I use the If condition. But when I deselect the tick. Nothing works. Even the whole part of "Else" doesn't work.

At beginning, I used "items[i].checked= SelectAll.checked " , at console.log , "false" is given to items, but the tick toggle doesn't show. So,I need to use setAttribute. Then I need to use If conditions. And problems appear...




Python subplots with multiple checkboxes? Click event in graphics? How to make?

Does anyone have any idea what tool or library I could use in Python to do the following:

I have several signals in a list, I wanted to plot multiple signal graphs side by side with subplots, and then I wanted to select just some of the plots based on clicks or checkbox selection on top of each one, in the end return the index of all selected ones.

An example would be the code below, but I would change the checkbox selection to get the index instead of changing the graph, but I wanted to do this in several subplots, side by side, so I would need to have a checkbox on each one.

x = np.linspace(0, 5, 100)
y = np.exp(x)
  
# Plotting the graph for exponential function
def plot(checkbox):
      
    # if checkbox is ticked then scatter
    # plot will be displayed
    if checkbox:
        plt.scatter(x, y, s = 5)
        plt.title('Scatter plot of exponential curve')
      
    # if checkbox is not ticked (by default)
    # line plot will be displayed
    else:
        plt.plot(x, y)
        plt.title('Line plot of exponential curve')
          
# calling the interact function        
interact(plot, checkbox = bool())



vendredi 25 mars 2022

Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php)

I got an Error message Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php) when I'm trying to create a checkbox for the edit form page

my controllers

public function edit(Employeejadwalpiket $Employee, $id)
{
    $employee = Employee::all();
    $jadwalpiket = Jadwalpiket::all();
    $data = Employeejadwalpiket::with('employees','jadwalpiket')->find($id);

    return view('jadwalpiket.editemployeepiket', compact('Employee','employee','jadwalpiket','data'));

}

my view

<div class="col-xs-12 col-sm-12 col-md-12">
                        <div class="form-group">
                        <strong>Pilih Tugas :</strong>
                        <div class="form-check">
                            @foreach ($jadwalpiket as $j)
                                <label class="form-check-label">
                                <input class="form-check-input" type="checkbox" name="jadwalpiket_id[]" value="" @if (count($Employee->jadwalpiket->where('id', $j->id)))
                                    checked
                                @endif>

                                    &emsp;&emsp;
                                </label>
                                @endforeach
                            </div>
                        </div>
                    </div>

my web.php

Route::get('/editemployeepiket/{id}',[EmployeejadwalpiketController::class, 'edit'])->name('editemployeepiket'); 
Route::post('/upemployeepiket/{id}',[EmployeejadwalpiketController::class, 'update'])->name('upemployeepiket');

please help me to fix it..




jeudi 24 mars 2022

I am trying to print the toppings from a group of checkboxes for a pizza order program inside a table as well as calculate the result of a select box

In my program it asks for which size of the pizza you want which are radio buttons as well as toppings which are all checkbox items. Then there is a select tag for pickup or delivery. When you confirm the order it will print the size and price of the pizza, the toppings chosen, whether you choose pick up or delivery and the total. The problems I am having are one, I am not sure how to print multiple checkbox values without overwriting another inside the table, they need to be displayed one after another if multiple checkboxes are checked. My second problem is for the select tag. I know you could do .checked for the select tag but if there are multiple options how do you check for the options and then print that option selected.

Here is my code.

<!DOCTYPE html>
<html>
    <head>
        <title>Drackley_Chapter 6 program</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <script type="text/javascript">
    function getPizza(){
    var price = 0;
    var size = "";
    var top = 0;
    var total = 0;
    var first_last = document.getElementById("first_last");
    document.getElementById("name_result").innerHTML = first_last.value + "'s Order";
    
    
    var s1 = document.getElementById("s1");
    var s2 = document.getElementById("s2");
    var s3 = document.getElementById("s3");
    var s4 = document.getElementById("s4");
    
    if(s1.checked==true)
    {
    price = 8.00;
    size = "Small";
    }
    //alert("The size selected is: "+s1.value);
    else if(s2.checked==true)
    {
    price = 10.00;
    size = "Medium";
    }
    //alert("The size selected is: "+s2.value);
    else if(s3.checked==true)
    {
    price = 12.00;
    size = "Large";
    }
    //alert("The size selected is: "+s3.value);
    else if(s4.checked==true)
    {
    price = 14.00;
    size = "X-Large";
    }
    //alert("The size selected is: "+s4.value);
    else
    alert("No size selected");
document.getElementById("p_result").innerHTML = "$" + price;
document.getElementById("s_result").innerHTML = size;

var t1 = document.forms["order"]["topping1"].checked;
var t2 = document.forms["order"]["topping2"].checked;
var t3 = document.forms["order"]["topping3"].checked;
var t4 = document.forms["order"]["topping4"].checked;
var t5 = document.forms["order"]["topping5"].checked;

if(t1 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML = "Pepperoni";
}
else
top = top;

if(t2 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML = "Sausage";
}
else 
top = top;

if(t3 == true) {
top = top + 1.5;
}
else 
top = top;

if(t4 == true) {
top = top + 1.5;
}
else 
top = top;

if(t5 == true) {
top = top + 1.5;
}
else 
top = top;

document.getElementById("t_result").innerHTML = "$ " + top;
 

    var select = document.getElementById("pick_deliv");
    
    if (select.checked == true)
    document.getElementById("sel_opt").innerHTML = select;
    alert(select.options[select.selectedIndex].value);
    
    
    total = total + price + top;
        document.getElementById("total_result").innerHTML = "Your Current Total is $ " + total;

}
     </script>  
<style>
table, th, td {
  border:1px solid black;
}
</style>
<body>
<h1>Chapter 6 Pizza Program </h1>

<form id="order" name="order">
<label for="first_last"> Name:</label>
<input type="text" name="first_last" id="first_last" placeholder="First Last"> <br>

<p> Please choose your size of pizza:</p>

<input type="radio" name="size" id="s1" value="Small"> Small - $8</input><br>
<input type="radio" name="size" id="s2" value="Medium"> Medium - $10</input><br>
<input type="radio" name="size" id="s3" value="Large"> Large - $12</input><br>
<input type="radio" name="size" id="s4" value="X-Large"> Extra Large - $14</input><br>

<p>Please choose your topping ($1.50 each): </p>
<input type="checkbox" name="topping1" id="topping1" value="pepperoni"> Pepperoni </input><br>
<input type="checkbox" name="topping2" id="topping2" value="sausage"> Sausage </input><br>
<input type="checkbox" name="topping3" id="topping3" value="bacon"> Bacon </input><br>
<input type="checkbox" name="topping4" id="topping4" value="onions"> Onions </input><br>
<input type="checkbox" name="topping5" id="topping5" value="spinach"> Spinach </input><br> <br>

<select name="pick_deliv" id="pick_deliv">
<option value="Pickup">Pick up </option>
<option value="Delivery">Delivery </option> 
</select> <br> <br>
</form> 

<button onclick="getPizza()" id="btn1"> Confirm Order</button>
<h1 id="name_result"> Your Order </h1> <br> <br>

<table style="width:50%">
<tr>
<th>Description</th>
<th>Option</th>
<th>Price</th>
</tr>

<tr>
<td> Size </td>
<td id="s_result"> </td>
<td id="p_result"> </td>
</tr>
<tr>
<td> Toppings </td>
<td id="t_options"> </td>
<td id="t_result"> </td>
</tr>
<tr>
<td> Pick-Up/Delivery</td>
<td id="sel_opt"> </td>
<td id="sel_price"> </td>
</tr>
</table>

<h4 id="total_result">Your Current Total is $ </h4>
</body>
</html>



Angular Material set mat-checkbox checked programatically

I am doing an Angular 12 Material APP.. I have a list of checked created dinamycally like this

   <li *ngFor="let chanel of dataSourceChannelLevel">
            <mat-checkbox id= formControlName="Channel"
             (change)="onChangeEventFunc( $event)">
              
            </mat-checkbox>
 </li>

I want also to checked them depending on the condition of

 

I have tried with value= but those not work... also with

 [checked]= 

but got this error

Parser Error: Got interpolation () where expression was expected at column 0 in []

The only things it works is [ngModel] but it checked all the mat-checkbox where checked or unchecked.

Is there a way to do it?

Thanks




Checkbox for website not working!!! I want to add checkbox to the website for terms and conditions [closed]

I am having trouble displaying the checkbox here. Can you please help me solve this issue? Here is the following code for the webpage.




jQuery filtering a close element using multiple checkboxes

I need a solution for filtering a group of items with multiple checkboxes. I found a fiddle and modified it to my needs for testing purposes:

Fiddle

Before it was based on "data-category" but I need it to be based on classes. Works just fine but there is one thing that I can't figure out myself. When filtering I don't want the actual element having the class (.red, .small, .africa) to hide or show but actually an element that it is nested in, I named it ".test" in my example and made it a div.

I think you can somehow do this using .closest('.test') but I don't know where to put it exactly.

closest()

Can you help me with this? I would really appreciate it.




Expand script for multiple columns

I'm new with these kind of things so sorry for the mistakes. I'm trying to use this script to remove checkboxes from a column everytime that the value in other columns is 0. The script is the following:

function onEdit() {var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Zodiac issues"); //change this to the name of your sheetui = SpreadsheetApp.getUi();

var names = ss.getRange("L3:L");

var namesValues = names.getValues(); //Get array of all the names

var checkboxes = ss.getRange("J3:J");

var cbRows = checkboxes.getHeight(); //Get # of rows in the rangesvar cbValues = checkboxes.getValues(); //Get array of all the checkbox column cell values//Logger.log(cbValues);

var newCBValues = new Array(cbRows); //Create an array to store all the new checkboxes values before we edit the actual spreadsheet

for (var row = 0; row < cbRows; row++) {
    newCBValues[row] = new Array(0); // Make the array 2 dimensional (even though it only has 1 column, it must be 2D).
    if (namesValues[row] == "0" || namesValues[row] == " ") { //If the name cell of this row is empty or blank then...
      newCBValues[row][0] = " "; //Set the value to one space (which will make the cell NOT true or false, and thus NOT display a checkbox).
      //Logger.log("newCBValues[" + row + "][0]: " + newCBValues[row][0]);
    }else{ //otherwise, if the name cell isn't blank...
      if (cbValues[row][0] === true) {
        newCBValues[row][0] = true; //Keep the checkbox checked if it's already checked
      }else{ //If the name cell isn't blank, and it's not true...
        newCBValues[row][0] = false; //Then Keep it or set it to False (an empty checkbox):
        
      }   
    }
  }
  checkboxes.setDataValidation(SpreadsheetApp.newDataValidation().requireCheckbox()).setValues(newCBValues);
  
}

If in var names = ss.getRange("L3:L") I select only one column it works. But when I want to set it for more columns (eg L3:N) it doesn't work.

Hope you can help me. THANKS!!!!

EDIT:

this is what I obtain if I write var names = ss.getRange("B1:B")

But if I want to include also column A ( so var names = ss.getRange("A1:B") ) the result is this one

CODE FOR ONE COLUMN

CODE FOR MORE THAN ONE COLUMN




mercredi 23 mars 2022

React - How To Uncheck All Checkboxes At Once

I have attempted calling my setItems functions and using a spread operator on items and/or allItems to map over and set item.checked to false but I'm stumped. I appreciate any feedback and if I have posted incorrectly please let me know. Everything renders correctly upon loading page. I can changed object property bools manually and they update accordingly. I am just trying to figure a button that will reset them all back to false.

const Checklist = () => {
const allItems = [
 { name: "Pan", checked: false },
 { name: "Spatula", checked: false },
 { name: "Bread", checked: false },
 { name: "Butter", checked: false },
 { name: "Cheese", checked: false },
];

const [items, setItems] = useState(allItems);

return (
<div className="checklist">
  <div>
    <table>
      <tbody>
        {items.map((item) => {
          return (
            <tr key={item.name}>
              <td>
                <input
                  type="checkbox"
                  defaultChecked={item.checked}
                  onChange={() => !item.checked}
                  onClick={() => console.log(item.checked)}
                />
              </td>
              <td>{item.name}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
  <br />
  <button type="submit" id="checkbox-clear-btn">
    Uncheck All
  </button>
</div>
);
};



add multiple workbooks using checkboxes

I have a userform with 2 checkboxes, when the user clicks on the send button it should copy the sheet 1 from currentWorkbook to a new workbook. If the user clicks in one of checkboxes (1 or 2) it works but if I clicks on the 2 checkboxes at the same time it doesn't work.

My goal is if the user clicks on the 2 checkboxes, it copies the sheet 1 from currentWorkbook to 2 new workbooks.

Any help is highly appreciated.

Private Sub CommandButton1_Click()

Dim theNewWorkbook As Workbook
Dim currentWorkbook As Workbook
Dim sFileSaveName As Variant
Dim industry As String
Dim dttoday As String

Set currentWorkbook = Workbooks("blabla" & ".xlsm")
Set theNewWorkbook = Workbooks.Add
currentWorkbook.Sheets("Sheet1").Activate

If one= True Then
currentWorkbook.Worksheets("Sheet1").Copy before:=theNewWorkbook.Sheets(1)
    With ActiveSheet
        .ListObjects(1).Name = "one"
    End With
ActiveSheet.ListObjects("one").Range.AutoFilter Field:=1, Criteria1:= _
        Array("bla", "ble", "bli", "blo"), _
        Operator:=xlFilterValues
    Rows("2:2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Delete Shift:=xlUp
    ActiveSheet.ShowAllData

'Save File

industry = "one "
dttoday = VBA.format(Now(), "ddmmyyyy")
saveLocation = "C:\blabla" & industry & dttoday & ".xlsx"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=saveLocation, fileFilter:="Excel Files (*.xlsx), *.xlsx")
If sFileSaveName <> "False" Then ActiveWorkbook.SaveAs sFileSaveName
theNewWorkbook.Close

End If

If two = True Then
currentWorkbook.Worksheets("Sheet1").Copy before:=theNewWorkbook.Sheets(1)
    With ActiveSheet
        .ListObjects(1).Name = "two"
    End With
ActiveSheet.ListObjects("two").Range.AutoFilter Field:=1, Criteria1:= _
        Array("bla", "ble", "bli"), _
        Operator:=xlFilterValues
    Rows("2:2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Delete Shift:=xlUp
    ActiveSheet.ShowAllData

'Save File

industry = "two "
dttoday = VBA.format(Now(), "ddmmyyyy")
saveLocation = "C:\blabla_" & industry & dttoday & ".xlsx"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=saveLocation, fileFilter:="Excel Files (*.xlsx), *.xlsx")
If sFileSaveName <> "False" Then ActiveWorkbook.SaveAs sFileSaveName
End If
Unload Me
End Sub



Checkbox value not showing up right in Google Apps Script

I am having an issue were the values I have setup in the Data Validation for my check boxes in cells C3 and D3 are not showing up correct. I set the values of "Yes" for checked and "No" for unchecked. A3 has Customer's Name and B3 is FT or PT.

I added the alert to display what all the values are and if the If/Else statement was working but regardless of whether the checkbox is checked or not it returns the values of Yes.

function ContactType() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var DBSheet = spreadsheet.getSheets()[0];

var ConType  = SpreadsheetApp.setActiveSheet(DBSheet).getRange('A3').getValue();
var CatType  = SpreadsheetApp.setActiveSheet(DBSheet).getRange('B3').getValue();
var spd = "None"
var spdcb = "None"
var dec = "None"
var deccb = "True"
var deccb = SpreadsheetApp.getActiveSheet().getRange('D3').getValue();
var spdcb = SpreadsheetApp.getActiveSheet().getRange('C3').getValue();

if (spdcb = "Yes")  
  spd = "Not Suspended";
  else if (spdcb = 'No')
    spd = "Suspended"
  
if (deccb = 'Yes')  
  dec = "Returned";
  else if (deccb = 'No')
    dec = "Not Returned" 

SpreadsheetApp.getUi().alert('The Contact type is '+ConType +'\r\n The Category Type is '+CatType +'\r\n The Suspension checkbox is ' +spdcb + '\r\n The Suspension status is '+spd +'\r\n The Reinstatement Declaration is ' +deccb + '\r\n The Reinstatement Declaration is '+dec);

}

I have tried changing the data validation to different values but got the same result.

I am hoping that the checkbox value will be correctly recognized and the If/Else to return the correct values for the other variables.




Why does the react hooks checkbox give an incorrect value?

This checkbox is consistent in displaying the wrong value of 'checked'

 <input type='checkbox'
 name='isCheckeD' 
 id='isChecked'
 checked={formData.isCheckeD}
 onChange={handleChecked}
 />

the function is

function handleChecked(e) {
    const {name, checked} = e.target 
    formDataSet( cB => {
            return {...cB, [name]: checked}
        }) 
}

and the state is:

const [formData, formDataSet] = useState(
    {
     isCheckeD: false    
    }
)

Any ideas?




mardi 22 mars 2022

Filtering items, checkbox issue laravel + vue js

I have a "Messages" table in the database. I am trying to make a filter by read/unread

For the filter, I am trying to make two checkboxes, and a "isread" variable, however I cant manage to make it work, heres what I have:

<input
                type="checkbox"
                id="1"
                class="read"
                v-model="isread"
                :value="1"
              />
<input
                type="checkbox"
                id="0"
                class="unread"
                v-model="isread"
                :value="0"
              />

The issue is that I get tons of errors in the console, plus the checkboxes get ticked/unticked at the same time (like its the same checkbox). My expected result, is that the variable "isread" stores value "0" if the "0" checkbox is checked, and "1" if the "1" is checked. Or, if both - both values get stored. Could you help me?




php checking if value matches in table and checking checkboxes if its true

so I made a program in php where i can assign screens to users i got it working by using a pivot table and getting the screenId and userId and insert those into the table when i check the checkbox

the only thing i want to be able to see is if the link between the screenId and userId already exist in the pivot table to check the checkbox

here is an image of the table I'm showing with checkboxes

https://i.stack.imgur.com/T6XYp.jpg

code to show the screens in a table:

    $sql = "SELECT * FROM screens";

    $screenStmt = mysqli_stmt_init($conn);
    
    if(!mysqli_stmt_prepare($screenStmt, $sql)){
        echo "SQL Error: Screens";
    }
    else{
        mysqli_stmt_execute($screenStmt);
        $screenResult = mysqli_stmt_get_result($screenStmt);
    }
    
        while($screenRow = mysqli_fetch_assoc($screenResult)){
            echo "<td>".$screenRow["screenId"]."</td>";
            echo "<td>".$screenRow["screenGuid"]."</td>";
            echo "<td>".$screenRow["screenName"]."</td>";
            echo "<td>".$screenRow["screenDesc"]."</td>";
            echo "<td><input type='checkbox' name='screenLink[]' value='".$screenRow["screenId"]."'></td>";
            echo "</tr>";
        }

code for saving the link into table when checkboxes are checked:

    if(isset($_POST['screenLink'])){
    if(!empty($_POST['screenLink'])){
        foreach($_POST['screenLink'] as $check){
            
            $sqlCheck = "SELECT userKey FROM linked WHERE screenKey=?";
            $userLink = "INSERT INTO linked (userKey, screenKey) VALUES (?,?);";


            $stmtCheck = mysqli_stmt_init($conn);

            if(!mysqli_stmt_prepare($stmtCheck, $sqlCheck)){
                echo "SQL Error";
            }
            else{
                mysqli_stmt_bind_param($stmtCheck, "s", $check);
                mysqli_stmt_execute($stmtCheck);
                $result = mysqli_stmt_get_result($stmtCheck);
                $result = mysqli_fetch_assoc($result);
            }
            if($result > 0){

            }
            else{
                $stmtInsert = mysqli_stmt_init($conn);
                if(!mysqli_stmt_prepare($stmtInsert, $userLink)){
                    echo "SQL error";
                }
                else{
                    mysqli_stmt_bind_param($stmtInsert, "ss", $userId, $check);
                    mysqli_stmt_execute($stmtInsert);
                    header("Location: ../users.php?change=Success");
                }
            }
        }
    }

}

this is probably not the best way but i got it kinda working how i need it and can change it later




FluentUI/React - Get key of dynamic checkbox list onChange

Using React 17 with Fluent UI, I am trying to create a dynamic list of checkboxes. I have created the list of checkboxes, but I am struggling to get the key of each checkbox when they are selected, to update the state that is meant to be an array containing the keys of all the selected checkboxes.

I am open to suggestions that use a different property other than the key of the checkbox to store the values, but I am limited to using Fluent UI.

Here is the code I have used to generate the list of checkboxes (This is working). profiles is an array of objects that was created, the only properties that are used in this code is name and token which are both strings:

const getProfileCheckboxes = () => {
    var profiles = ProjectManager.getProfileList();
    const checkboxes = profiles.map(profile => 
        <Checkbox
            label={profile.name}
            defaultChecked={true}
            onChange={onChangeProfileCheckbox}
            key={profile.token}
        />
    );
    return checkboxes;
}

Below is where I am having issues, I have tried quite a few things for this function including all the answers to the related questions that I have found on Stack Overflow, but I have had no luck.

selectedProfiles defaults to an array containing all the profile tokens.

const onChangeProfileCheckbox = (ev: any) => {
    const value = "key of profile"; // Placeholder
    const checked = false; // Placeholder
    if (checked) {
        selectedProfiles.push(value);
    } else {
        setSelectedProfiles(prev => prev.filter(x => x !== value));
    }
}

Does anybody know how I can get the key and checked values in the onChange() function?

The checked values is less important since I can just check if the key is already contained in the state array, but I think it would be cleaner if I could get the value directly.

Thanks for the help!




How to set a custom checkmark and checkmark box?

I've created a custom checkbox based on my needs, but rather than use the default checkmark, I have my own SVG I want to use. Additionally, I can't seem to attach a border radius to my custom checkbox.

How do I set a custom checkmark and checkbox radius to the present styles?

body {
  font-size: 16px;
}

.checkboxes {
  display: flex;
  flex-direction: column;
}
.checkboxes .checkbox {
  display: flex;
  flex-direction: row;
}
.checkboxes .checkbox + .checkbox {
  margin-top: 1rem;
}
.checkboxes .checkbox input[type=checkbox] {
  width: 1.5rem;
  height: 1.5rem;
}
.checkboxes .checkbox input[type=checkbox]:hover {
  cursor: pointer;
}
.checkboxes .checkbox input[type=checkbox]::before {
  border: 2px solid purple;
}
.checkboxes .checkbox input[type=checkbox] + label {
  margin-left: 0.75rem;
  font-size: 1rem;
  line-height: 1.5rem;
  color: #000A70;
  flex: 1;
}
.checkboxes .checkbox input[type=checkbox] + label:first-line {
  align-items: center;
}
.checkboxes .checkbox input[type=checkbox]:checked {
  accent-color: #005FEC;
}
.checkboxes .checkbox input[type=checkbox]:checked + label::after {
  content: url('data:image/svg+xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" width="12" height="6" fill="none" viewBox="0 0 12 6"><path fill-rule="evenodd" clip-rule="evenodd" d="M13.2426 2.24264L11.8284 0.828427L4.75811 7.89874L1.92969 5.07031L0.515474 6.48453L3.3439 9.31295L3.34315 9.31371L4.75736 10.7279L4.75811 10.7272L6.17233 9.31295L13.2426 2.24264Z" fill="white"/></svg>');
}
<div class="checkboxes">
  <div class="checkbox">
    <input type="checkbox" id="check1">
    <label for="check1">Checkbox One</label>
  </div>
  <div class="checkbox">
    <input type="checkbox" id="check2" checked="checked">
    <label for="check2">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Magni eos incidunt, est nesciunt amet eum iure omnis quo. Excepturi ducimus atque numquam quis voluptatem consectetur facilis et tenetur repellat quae.</label>
  </div>  
  <div class="checkbox">
    <input type="checkbox" id="check3" checked="checked">
    <label for="check3">Checkbox One</label>
  </div>  
</div>



Angular click checkbox without checking it

I have this checkbox in my Angular project:

<input type="checkbox" id="approve_required" (change)="onClick($event,'approve_required',data)" [checked]="isChecked">

When the checkbox is clicked, I actually first want to check if it is even allowed to set it on checked. Because if not, the checkbox should remain unchecked and instead a modal will open. The way it is now, it is clicked and appears as checked immediately even if I set "isChecked" false after checking a condition in my onClick function.

Is there a way to do this?




How to count checkboxes for a given date and paste it as number in a cell

I'm trying to develop a task management system where I need to check all the completed tasks for a given date.

Pls refer to the attached sheet.

When I check the box as complete (Column B), Column C automatically has to print the current date. For that I gave the equation: =if(B3=True,NOW(),"")

Each time a checkbox is checked, the date will be automatically added in column C.

But the real challenge is I also want to display the number of tasks I completed on a specific date in Column F. For that, I gave the equation: =COUNTIFs(B:B=true,C:C=E4)

But as you can see, the answer comes in zero. I even checked if the two dates are equal by checking: =if(E4=C4,True,False), and the answer came out False.

Although both the dates are equal, how come they are false? How can I solve this issue?

Screenshot




lundi 21 mars 2022

Get value checkbox and push in array

Can you help me on how to get the checkbox values to be a data array? I code like this, and don't get any output. Thanks for helping me.

In my html :

<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value=""data-id="">

In my JS:

function multiple_delete(id) {
  const selected = [];
  $(".form-check input[type=checkbox]:checked").each(function () {
    selected.push(this.value);
  });
  if (selected.length > 0) {
    dataid = selected.join(",");
    $.ajax({
      url: "multiple-delete",
      type: "POST",
      data: +dataid,
      success: function (data) {
        if (data["success"]) {
          alert(data["success"]);
        } else {
          alert(data["error"]);
          console.log(data);
        }
      },
      error: function (data) {
        alert(data.responseText);
      },
    });
  }
}

My output :

console output




Get boolean value as a checkbox

I have a database. I want to display a table with all the data and get boolean values as a checkbox.

<ngx-datatable-column name="Value">
        <ng-template ngx-datatable-cell-template let-value="value">
            <mat-checkbox [(ngModel)]="valueGroup.isAction"></mat-checkbox>
        </ng-template>
</ngx-datatable-column>

But I have an error

core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'isAction')
    at PriceGroupsComponent_ng_template_15_Template (price-groups.component.html:20:27)
    at executeTemplate (core.mjs:9618:1)
    at refreshView (core.mjs:9484:1)
    at refreshEmbeddedViews (core.mjs:10609:1)
    at refreshView (core.mjs:9508:1)
    at refreshEmbeddedViews (core.mjs:10609:1)
    at refreshView (core.mjs:9508:1)
    at refreshComponent (core.mjs:10655:1)
    at refreshChildComponents (core.mjs:9280:1)
    at refreshView (core.mjs:9534:1)
defaultErrorLogger @ core.mjs:6485



Why does this react hooks checkbox give an incorrect value?

This checkbox is consistent in displaying the wrong value of 'checked'

 <input type='checkbox'
 name='isCheckeD' 
 id='isChecked'
 checked={formData.isCheckeD}
 onChange={handleChecked}
 />

the function is

function handleChecked(e) {
    const {name, checked} = e.target 
    formDataSet( cB => {
            return {...cB, [name]: checked}
        }) 
}

and the state is:

const [formData, formDataSet] = useState(
    {
     isCheckeD: false    
    }
)

Any ideas?




dimanche 20 mars 2022

Laravel 7 - No data mapped in insert multiple data to mysql database

I am inserting multiple data into mysql database, apparently everything works fine, but when I checked the data in phpmyadmin, it seems that only the first value of the first selected checkbox is being inserted multiple times, which means only the first id_student is the value that is being inserted multiple times. I think it's a mapping problem but I don't know how to solve it, can someone help me?

  • This is my view
@foreach ($group->students as $student)
         @if($student->pivot->pass)
         <tr>
            <td class="align-middle text-center">
                <input class="form-control" type="text" name="name" value="  " disabled>
            </td>

            <td class="align-middle text-center">
                <input class="form-control form-control-sm" type="text" name="grade" value="" placeholder="Grade" disabled>
            </td>

            <form action="" method="POST">
             

                  <input class="form-control form-control-sm" type="hidden" name="id_student" value="" >

                  <td class="align-middle text-center">
                      <input id="select" type="checkbox" name="select[]">
                  </td>
        </tr>
        @endif
@endforeach
  • This is my function in Controller.

     public function create(Request $request)
        {
            try { 
                
                $id_student = $request->get('id_student');
                   
                $consecutive = DB::select('SELECT SUM(idRecord) FROM records GROUP BY idRecord'); 
                $final_consecutive = sprintf("%04d", $consecutive); 
                foreach($request->select as $data)
                {
                    Constancias::create(['id_student' => $id_student, 'consecutive' => $final_consecutive]);
                }
    
                return back()->with('success', 'Constancia creada correctamente');
            } catch (\Illuminate\Database\QueryException $e) {
                $message = $e->getMessage();
                if (strpos($message, "Duplicate entry")) {
                    return back()->with('err', 'Esta constancia ya ha sido creada');
                }
                if (strpos($message, "1366 Incorrect integer value: '' for column 'idGrupo'")) {
                    return back()->with('err', 'Debe seleccionar un grupo para poder continuar');
                }
                return back()->with('err', $message);
            }
        }

  • Image of the table "Record"

records




Javascript validation and loops

I'm learning basic web development and I'm VERY, VERY stuck on JavaScript form validation and loops. I need to validate radio buttons, drop down selection, checkboxes, number selector, and a box to type in your name. I think I'm on the right track for some of it but I could be completely wrong. I have 0 idea how to do a number selector (pin number between 1000-9999). The loop needs to read all the form fields and display their value in the console when submit button is pressed and validation passes. I've tried finding this stuff everywhere and have struggled a lot. I'll leave the code for each below, This is also my first post on here so if you need more info to help me please just let me know!

For the enter your name box

function validateForm() {
      let x = document.forms["whatisyourname"]["name"].value;
      if (x == "") {
        alert("Name must be filled out");
        return false;
      }
    }

Radio button

function validateForm() { 
var radios = document.getElementsByName("hair_color");
var formValid = false;
var i = 1;
while (!formValid && i < radios.length) {
    if (radios[i].checked) formValid = true;
    i++;
}
if (!formValid) alert("Please select a hair option");
return formValid;
}

Drop Down

    function validate() {
 var ddl = document.getElementById("food");
 var selectedValue = ddl.options[ddl.selectedIndex].value;
    if (selectedValue == "")
   {
    alert("Please select a food");
   }
}   

Check Boxes

function valthisform() {
var checkboxs=document.getElementsByName("hobby");
var okay=false;
for(var i=1,l=checkboxs.length;i<l;i++)
{
    if(checkboxs[i].checked)
    {
        okay=true;
        break;
    }
}
else alert("Please check 2 checkboxes");
}



Modify Checkboxes based on changes in Streamlit

I wanted to create a checkbox which checks all other checkboxes if checked and if the checkbox is unchecked that all other checkboxes also get unchecked.

For example:

enter image description here

Clicking on “all” should be also checking “option1, option2, etc.”. Same if I uncheck.

I tried to use session_states but could not come up with a solution. Is there a possibility to modify checkboxes?




How to have a longPress Event on a CheckBox in Codenameone?

i need to implement a long press event on a checkbox in codenameone. On normal buttons i use the longPointerPress method and a boolean to control if the short- or longpress event happens. With the checkboxes i cannot find that option, it only toggles between checked/unchecked.

How is it possible to use a long press on a checkbox?

Thanks for your help!




samedi 19 mars 2022

How to disable the unselected checkboxes and change the css class for selected checkboxes only using Angular 12 and Typescript?

I have stored checkboxes dynamically using json array of object. What I need is, I have to select only 5 checkboxes. If my selection is reached 5, then I have to disable the unchecked checkboxes and change the css only for unchecked checkboxes only. I tried but when the selection is reached 5 I am not able to change the class to that unselected checkboxes.

<div class="pinnedtoolsbox" *ngFor="let item of menuList">
  <div>
    <div class="pinnedtoolbox-caption">
      
      <div>
      
        <img src=""/>
     
          
      </div>
      <div>
        <span></span>
     

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

  

  <div  *ngFor="let sublist of item.submenus; let i=index" >
  
  <label [ngClass]="sublist.selected ? 'submenulist_label_checked': 'submenulist_label'">
   <div>
   <img [src]="sublist.selected ? 'assets/icons/listmenuiconwhite.svg': 'assets/icons/listicon.svg'"/>
   </div>
   <div>
     
    

    <input type="checkbox"
    [(ngModel)]="sublist.selected" 
    [disabled]="disableCheckbox(sublist)"  
    (change)="changeSelection($event, sublist)"
    
    style="display:none;">
   </div>
  
  </label>
  </div>

  </div>

component.ts file

private _jsonURL = 'assets/menus.json';

public getJSON(): Observable<any> {
 return this.http.get(this._jsonURL);
}   

[{"title":"one",
"submenus": [
    {
        "id":1, "menu": "home", "selected": false
    },
    {
        "id":2, "menu": "about", "selected": false
    },
   
    
]
 
},

{"title":"two",
    
"submenus": [
    {
        "id":1, "menu": "Status", "selected": false
    },
    {
        "id":2, "menu": "Balance", "selected": false
    },
    
   
    
]
},

    



]


checkboxList = [];
public maxElementCheckbox = 5;


changeSelection($event, item){

if ($event.target.checked) {
 
  this.checkboxList.push(item);
 
 }

else {
  
  this.checkboxList.splice(this.checkboxList.indexOf(item), 1);
  console.log("esle part");
}
console.log(this.checkboxList);
}

 public disableCheckbox(id): boolean {

return this.checkboxList.length >= this.maxElementCheckbox && !this.checkboxList.includes(id);

}



vendredi 18 mars 2022

One check per column in one row for checkbox in google sheet?

I was trying to figure out how to make so there would be one check per column in one row. So far, I was still looking for an way to do this via Apps Script extension which I have been met with disappointment.

So, for example, if you have two rows but needs to have one checks per columns in the respective row? How would you do this?




Image selection input in html with checkbox or radio

I'm creating a web page and I want to create a section with images so the user can select only one by clicking on it. I'm trying with checkbox and radio but it only gets selected when I press on the checkbox itself, not in the image. How can I do that?

I've tried this:

<section>
        <fieldset>
                <legend><h2>Favorite character</h2></legend>
    
                <input type="checkbox" id="imagen">
                <label for="myCheckbox1"><img src="image.jpg"></label>
        </fieldset>
</section>

And also the same but with radio




Add scroll effect from section to section to HTML, CSS or JavaScript

I have multiple checkboxes on a page, I want that when anyone clicks on a checkbox button it scrolls to the next checkbox button section, and there's a select all button that selects all the checkboxes button, I want it to scroll to the very bottom when clicked, how should I do this. Below is my code:

.select {
  margin: 4px;
  background-color: #06213B;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.select label {
  float: left;
  line-height: 4.0em;
  width: 26.0em;
  height: 4.0em;
}

.select label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.select label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.select label input+span {
  color: #fff;
  font-size: 19px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.select input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.select input:checked+span {
  background-color: #78E821;
}

input[type="checkbox"]+span:after {
  content: "Select all";
}

input[type="checkbox"]:checked+span:after {
  content: "All selected";
}

.branded {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.branded label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.branded label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.branded label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.branded label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.branded input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.branded input:checked+span {
  background-color: #78E821;
}

.branded input[type="checkbox"]+span:after {
  content: "SELECT";
}

.branded input[type="checkbox"]:checked+span:after {
  content: "SELECTED";
}

.lifepoints {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.lifepoints label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.lifepoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.lifepoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.lifepoints label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.lifepoints input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.lifepoints input:checked+span {
  background-color: #78E821;
}

.lifepoints input[type="checkbox"]+span:after {
  content: "SELECT";
}

.lifepoints input[type="checkbox"]:checked+span:after {
  content: "SELECTED";
}

.mypoints {
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.mypoints label {
  float: left;
  line-height: 4.0em;
  width: 16.0em;
  height: 4.0em;
}

.mypoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.mypoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}


/* selects all of the text within the input element and changes the color of the text */

.mypoints label input+span {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  font-family: default;
}


/* This will declare how a selected input will look giving generic properties */

.mypoints input:checked+span {
  color: #ffffff;
  text-shadow: 0 0 0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.mypoints input:checked+span {
  background-color: #78E821;
}

.mypoints input[type="checkbox"]+span:after {
  content: "SELECT";
}

.mypoints input[type="checkbox"]:checked+span:after {
  content: "SELECTED";
}
<!doctype html>
<html>

<head>
  <title>Test</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.0/css/all.min.css" />
  <script>
    window.addEventListener('DOMContentLoaded', function() {
      const checks = document.querySelectorAll('.chk');
      const checkAll = document.getElementById('selectAll')
      document.addEventListener('click', function(e) {
        const tgt = e.target;
        if (tgt.matches('.chk')) {
          if (tgt.id === "selectAll") {
            tgt.closest('div').querySelector('i').classList[tgt.checked ? 'add' : 'remove']('fa-circle-check');
            checks.forEach(chk => {
              chk.checked = tgt.checked
              chk.closest('div').querySelector('i').classList[chk.checked ? 'add' : 'remove']('fa-circle-check');
            })
          } else {
            tgt.closest('div').querySelector('i').classList[tgt.checked ? 'add' : 'remove']('fa-circle-check');
            checkAll.checked = [...checks].slice(1).every(chk => chk.checked); // check all sub checkboxes are checked
            checkAll.closest('div').querySelector('i').classList[checkAll.checked ? 'add' : 'remove']('fa-circle-check');
          }
        }
      });
    });
  </script>
</head>

<body>
  <div class="select action">
    <label>
      <input type="checkbox" class="chk" id="selectAll" value="1"><span><i class="fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div><br clear="all" />
  <h2>Some other place</h2><br clear="all" />
  <br clear="all" />
  <div class="branded surveys">
    <label>
      <input type="checkbox" class="chk" value="1"><span><i class="fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div><br clear="all" />
  <h2>Some other place</h2><br clear="all" />
  <br clear="all" />
  <div class="lifepoints">
    <label>
      <input type="checkbox" class="chk" value="1"><span><i class="fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div><br clear="all" />
  <h2>Some other place</h2>
  <br clear="all" />
  <div class="mypoints">
    <label>
      <input type="checkbox" class="chk" value="1"><span><i class="fa-solid fa-circle"></i> &nbsp;</span>
   </label>
  </div>
</body>

Any help would be welcome, please.




jeudi 17 mars 2022

Como ocultar un panel con un checkbox?

281 / 5,000 Resultados de traducción I have the following problem, what I want to do is that when pressing a checkbox a panel is visible. I always hide the panels with image buttons and it works, but this time I want to do it with a checkbox, but the page does nothing.

This is code:

My checkbox and the aspx.

<asp:CheckBox ID="checkbox"  runat="server"  AutoPostBack="True"  oncheckedchanged="Checkbox_CheckedChanged"

<div class="col-sm-5">
        <asp:Panel ID="panel" runat="server" Visible="false">
            <asp:UpdatePanel ID="upanel" runat="server" UpdateMode="Conditional" >

            </asp:UpdatePanel>
        </asp:Panel>
    </div>

Server side C#

    protected void Checkbox_CheckedChanged(object sender, EventArgs e)
    {

        if (checkbox.Checked)
        {
            panel.Visible = true;
        }
        else
        {
            panel.Visible = false;
        }



How do i use a checkbox from my Form Type file inside my Controller file?

I'm currently still learning PHP and Symfony bases, and I'm working on a project to allow employees of my company to use their leaves. I don't have people around to help with that (either not here, either "no time", either...).

So I will try to be as clear as my english allows me to :

In my Form file (CongeType.php, didn't chose the name, it was already created by the previous guy) I have that :

     ->add('morning', CheckboxType::class, [
         'label' => 'Matin',
         'mapped' => false,
         'required' => false
    ])
    ->add('afternoon', CheckboxType::class, [
        'label' => 'Après-midi',
        'mapped' => false,
        'required' => false
    ])

Which allow me to have two checkboxes "Morning" and "Afternoon" on my view (by the way, that project is using FullCalendar plugin, I don't know if it's relevant to say it so far).

If the user check "Morning" or "Afternoon" only half a day is took from it's leaves balance, instead of a full day. Well, that's the plan, but so far I'm not sure how to do it.

In my controller, I have that :

    $solde = $this->getUser()->getSoldeCp()->getCurrentYear();
    $conge = new Conge();
    $form = $this->createForm(CongeType::class, $conge);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $daybreak = $cg->GetNbrJourConge($data->getDateDebut(),  $data->getDateFin()->modify('+ 1 day'), $this->getUser());

        /** @var User $user */
        $soldeCp = $this->getUser()->getSoldeCp()->getCurrentyear();
        $this->getUser()->getSoldeCp()->setCurrentyear($soldeCp - count($daybreak));

So I'm trying to create an other "if" that would divide by 2 the value of $daybreak if any of the "Morning" or "Afternoon" box is checked, but I don't know how to call those boxes inside my controller.

I'm not sure I'm very clear here, so don't hesitate to ask me more info.

Also, thanks for reading me !

(Project is on Symfony 5.3.9, and using JS FullCalendar plugin)




javascript only working for one element, only the first one

I have multiple checkbox button elements on my page, whenever someone clicks on each of them, their color and text are changed, I was able to do that with CSS, but I wanted to change the icon in the checkbox button also, So I Use javascript in my HTML code but when I run the script it only works for one element, only the first one, so that means the icon only change for the first checkbox button but it is not working for all the other button, I tried to give all my checkbox button unique ID but I still have the same issue

This is checkbox 1 and 2 when not selectedenter image description here

This is checkbox 1 and 2 when selected enter image description here

Here's the code I run to do that:

 document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementById('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);
.select{
  margin: 4px;
  background-color: #06213B;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.select label {
  float: left; line-height: 4.0em;
  width: 26.0em; height: 4.0em;
}

.select label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.select label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.select label input + span{color: #fff;
    font-size: 19px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.select input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.select input:checked + span{background-color: #78E821;}

input[type="checkbox"] + span:after{
  content: "Select all"; 
}

input[type="checkbox"]:checked + span:after{
  content: "All selected"; 
}



.branded{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.branded label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.branded label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.branded label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.branded label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.branded input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.branded input:checked + span{background-color: #78E821;}

.branded input[type="checkbox"] + span:after{
  content: "SELECT"; 
}

.branded input[type="checkbox"]:checked + span:after{
  content: "SELECTED"; 
}


.lifepoints{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.lifepoints label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.lifepoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.lifepoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.lifepoints label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.lifepoints input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.lifepoints input:checked + span{background-color: #78E821;}

.lifepoints input[type="checkbox"] + span:after{
  content: "SELECT"; 
}

.lifepoints input[type="checkbox"]:checked + span:after{
  content: "SELECTED"; 
}


.mypoints{
  margin: 4px;
  background-color: #3E8BB5;
  border-radius: 4px;
  border: 0px solid #fff;
  overflow: hidden;
  float: left;
}

.mypoints label {
  float: left; line-height: 4.0em;
  width: 16.0em; height: 4.0em;
}

.mypoints label span {
  text-align: center;
  padding: 0px 0;
  display: block;
}

.mypoints label input {
  position: absolute;
  display: none;
  color: #fff !important;
}

/* selects all of the text within the input element and changes the color of the text */
.mypoints label input + span{color: #fff;
    font-size: 16px;
    font-weight: 500;
    font-family: default;
}


/* This will declare how a selected input will look giving generic properties */
.mypoints input:checked + span {
    color: #ffffff;
    text-shadow: 0 0  0px rgba(0, 0, 0, 0.8);
}


/*
This following statements selects each category individually that contains an input element that is a checkbox and is checked (or selected) and chabges the background color of the span element.
*/

.mypoints input:checked + span{background-color: #78E821;}

.mypoints input[type="checkbox"] + span:after{
  content: "SELECT"; 
}

.mypoints input[type="checkbox"]:checked + span:after{
  content: "SELECTED"; 
}
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://kit.fontawesome.com/6e6e078929.js" crossorigin="anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class="select action">
   <label>
      <input type="checkbox" value="1" id="checkbox"><span><i class="fa-solid fa-circle" id="icon"></i> &nbsp;</span>
   </label>
</div>
  
</body>
</html>



<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://kit.fontawesome.com/6e6e078929.js" crossorigin="anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class="branded surveys">
   <label>
      <input type="checkbox" value="1" id="checkbox"><span><i class="fa-solid fa-circle" id="icon"></i> &nbsp;</span>
   </label>
</div>

</body>
</html>


<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://kit.fontawesome.com/6e6e078929.js" crossorigin="anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class="lifepoints">
   <label>
      <input type="checkbox" value="1" id="checkbox"><span><i class="fa-solid fa-circle" id="icon"></i> &nbsp;</span>
   </label>
</div>

</body>
</html>


<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://kit.fontawesome.com/6e6e078929.js" crossorigin="anonymous"></script>
<!--Get your own code at fontawesome.com-->
</head>
<body>

 <div class="mypoints">
   <label>
      <input type="checkbox" value="1" id="checkbox"><span><i class="fa-solid fa-circle" id="icon"></i> &nbsp;</span>
   </label>
</div>
  
<script>
  document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementById('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);
</script>

</body>
</html>

If you want a more organized view and to see how the code is interacting, get a look at it here: https://codepen.io/edengandhi/pen/BaJoJYY




Show the next contents in a table in Word

Team,

Scenario I have a word document where I have a table as shown in Image 1. The checkboxes are used to show the next contents. For example, I have in first step yes and no, when yes is checked the next content is shown. And in next step, I have thre Checkboxes with case 1,2 and 3 respectively. enter image description here

When the case 1 is checked I have next a text that is filled via vba as F1Feld1...till F4Feld1.

Problem First problem is, I am unable to create a fucntion where only yes and no can be checked as well as either of the case can be checked. Second, problem is that the vba for case checkboxes run perfectly when I have them created seperate but when combined together only case 1 vba runs.

Following is my code

Option Explicit
Dim tabelle As Table, zelle As Cell
Private Sub Document_ContentControlOnEnter(ByVal CC As ContentControl)

    Dim r As Range
    Set tabelle = ActiveDocument.Bookmarks("local").Range.Tables(1)
    If ActiveDocument.SelectContentControlsByTag("Yes").Item(1).Checked = True Then

        ActiveDocument.SelectContentControlsByTag("No").Item(1).Checked = False
        Call local_blockiert

    Else: Call local_offen

    End If
    If ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = True Then
        On Error Resume Next
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = "F1Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB2").Range.Text = "F1Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB3").Range.Text = "F1Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB4").Range.Text = "F1Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
        End With
    ElseIf ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = False Then
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = ""
            .Bookmarks("TB2").Range.Text = ""
            .Bookmarks("TB3").Range.Text = ""
            .Bookmarks("TB4").Range.Text = ""
        End With
    ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = True Then
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = "F2Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB2").Range.Text = "F2Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB3").Range.Text = "F2Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB4").Range.Text = "F2Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
        End With
    ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = False Then
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = ""
            .Bookmarks("TB2").Range.Text = ""
            .Bookmarks("TB3").Range.Text = ""
            .Bookmarks("TB4").Range.Text = ""
        End With
    ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = True Then
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = "F3Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB2").Range.Text = "F3Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB3").Range.Text = "F3Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
            .Bookmarks("TB4").Range.Text = "F3Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
        End With
    ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = False Then
        With ActiveDocument
            .Bookmarks("TB1").Range.Text = ""
            .Bookmarks("TB2").Range.Text = ""
            .Bookmarks("TB3").Range.Text = ""
            .Bookmarks("TB4").Range.Text = ""
        End With
    End If

End Sub
Private Sub local_blockiert()
    Dim i As Long, j As Long
    On Error GoTo fehler
    With ActiveDocument.Bookmarks("local").Range
        .Font.ColorIndex = wdWhite
    End With

fehler:
Call AllesAuf
End Sub
Private Sub local_offen()
    Dim i As Long, j As Long
    On Error GoTo fehler
    With ActiveDocument.Bookmarks("YesorNo").Range
        .Font.ColorIndex = wdBlack
    End With

fehler:
Call AllesAuf

End Sub


Private Sub yes_blockiert()
    Dim j As Long
    On Error GoTo fehler

    With tabelle.Cell(2, 2)
        .Shading.ForegroundPatternColorIndex = wdGray25
        .Range.Font.ColorIndex = wdGray25
        For j = 1 To .Range.ContentControls.Count
            .Range.ContentControls(j).LockContents = True
        Next j
    End With
    Exit Sub
fehler:
Call AllesAuf
End Sub

Private Sub yes_offen()
    Dim j As Long
    On Error GoTo fehler

    With tabelle.Cell(2, 2)
        For j = 1 To .Range.ContentControls.Count
            .Range.ContentControls(j).LockContents = False
        Next j

        .Shading.ForegroundPatternColor = RGB(255, 242, 204)
        .Range.Font.ColorIndex = wdAuto

    End With
    Exit Sub
fehler:
Call AllesAuf
End Sub

Private Sub AllesAuf()
    Dim i As Long

    With ActiveDocument
        For i = 1 To .ContentControls.Count
            .ContentControls(i).LockContents = False
        Next i
    End With
End Sub

Hope to find a solution for this. Thank you.




Enable button if checkbox is selected in Kotlin?

I want to enable a button if checkbox is selected or checked and disable it if unselected or unchecked. I started all my application using kotlin. if there is a way for doing somehting like that in kotlin please help! and if there is no way in kotlin, show me a way for doing that wanted I mentioned above. thanks to whome is trying to help. see this picture of my mean

here is my button and checkbox codes and :

<LinearLayout
        android:id="@+id/llIAWith"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:orientation="horizontal"
        android:padding="10dp">

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/i_agree_with"
            android:textSize="15dp"
            android:textColor="@color/Middle_Gray"
            app:buttonTint="@color/Orange"
            tools:ignore="TextContrastCheck" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/terms_of_services"
            android:textSize="15dp"
            android:textColor="@color/Orange"
            tools:ignore="TextContrastCheck" />
    </LinearLayout>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnSUp"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/custom_button"
        android:text="@string/sign_up"
        android:textSize="18dp"
        android:textAllCaps="false"
        android:textColor="@color/White"
        tools:ignore="TextContrastCheck,TouchTargetSizeCheck" />

here is my kotlin codec :

class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityLoginBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    initData()
}
private fun checkForInternet(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val network = connectivityManager.activeNetwork ?: return false
    val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
    return when{
        activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
        activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
        activeNetwork.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) -> true
        else -> false
    }
}
private fun initData(){
    auth = FirebaseAuth.getInstance()
    clickListener()
    clickListenerFP()
}
private fun clickListenerFP(){
    binding.llFPassword.setOnClickListener{
        startActivity(Intent(this,ForgotPasswordActivity::class.java))
        finish()
    }
}
private fun clickListener(){
    binding.llDHAAccount.setOnClickListener{
        startActivity(Intent(this,RegisterActivity::class.java))
        finish()
    }
    binding.btnSIn.setOnClickListener{
        getUserData()
    }
}
private fun getUserData(){
    val email = binding.etEmail.text.toString()
    val password = binding.etPassword.text.toString()
    if(email.isNotEmpty() && password.isNotEmpty()){
        authUser(email, password)
    }else{
        Toast.makeText(this,resources.getString(R.string.all_inputs_are_required),Toast.LENGTH_SHORT).show()
    }
}
private fun authUser(email: String, password: String){
    auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener{
            checkResult(it.isSuccessful)
        }
}
private fun checkResult(isSuccess: Boolean){
    if (checkForInternet(this)) {
        Toast.makeText(this,resources.getString(R.string.connected), Toast.LENGTH_SHORT).cancel()
    } else {
        Toast.makeText(this,resources.getString(R.string.no_network_connection), Toast.LENGTH_SHORT).show()
    }
    if(isSuccess){
        startActivity(Intent(this,DashboardActivity::class.java))
        finish()
    }else{
        Toast.makeText(this,resources.getString(R.string.authentication_failed),Toast.LENGTH_SHORT).show()
    }
}
private var backPressedTime:Long = 0
private lateinit var backToast:Toast
override fun onBackPressed() {
    backToast = Toast.makeText(this,resources.getString(R.string.press_back_again_to_leave_the_app), Toast.LENGTH_SHORT)
    if (backPressedTime + 2000 > System.currentTimeMillis()) {
        backToast.cancel()
        super.onBackPressed()
        return
    } else {
        backToast.show()
    }
    backPressedTime = System.currentTimeMillis()
}



mercredi 16 mars 2022

Hide woocommerce notice with checkbox, based on shipping class

Want to hide woocommerce notice with jQuery on checkout page if specific shipping class checkbox is checked. Trying to make with this code but not working for me :(

//Hide Delivery Message in case Express Shipping Checked

add_action( 'woocommerce_checkout_process', 'hide_notice_billing' );
function hide_notice_billing(){
    ?>
        <script>
        jQuery(function($){
           $(document).ready(function() {
    $(document).on("click", "#shipping_method_0_flat_rate-12", function(e) {
       var checked = $(this).find("input:checkbox").is(":checked");
       if (checked) {
           $('.woocommerce-message').hide(300);
       } else {
           $('.woocommerce-message').show(300);
       }
    });
});
        });
    </script>
    <?php
}



When Checkbox true I want to delete item from ObservableCollection

I'm trying to implement a simple reminder list on my application. The only problem I'm facing is how to delete the item from my collection/view. I have a checkbox with each DataTemplate, what I would like to happen is when you click the checkbox it will delete the completed event from the view, i.e. the task has been completed. I know this sounds simple but I'm actually lost.

My XMAL:

<CollectionView HeightRequest="{Binding AddNotesHeight}" ItemsSource="{Binding CurrentPetEvents}">
                         <CollectionView.Header>
                             <StackLayout>
                                 <Label
                                     FontFamily="Bold"
                                     FontSize="Large"
                                     Text="+ Add Notes"
                                     TextDecorations="Underline">
                                     <Label.GestureRecognizers>
                                         <TapGestureRecognizer Tapped="AddNotes_Tapped" />
                                     </Label.GestureRecognizers>
                                 </Label>
                             </StackLayout>
                         </CollectionView.Header>
                         <CollectionView.ItemTemplate>
                             <DataTemplate>
                                 <StackLayout>
                                     <Grid>
                                         <CheckBox Color="#63a9ef"/>
                                         <Label
                                             Margin="40,0,0,0"
                                             FontSize="22"
                                             Text="{Binding TitleNote}"
                                             VerticalOptions="Center" />
                                     </Grid>
                                     <Label
                                         Margin="40,0,0,0"
                                         FontSize="20"
                                         Text="{Binding DateTimeRepeat}" />
                                     <BoxView HeightRequest="1" Color="Black" />
                                 </StackLayout>
                             </DataTemplate>
                         </CollectionView.ItemTemplate>
                     </CollectionView>

My Model:

 public class PawJournalEventModel
 {
     public string TitleNote { get; set; }
     public string DateTimeRepeat { get; set; }
 }

My ViewModel:

public ObservableCollection<PawJournalEventModel> _currentPetEvents;
         public ObservableCollection<PawJournalEventModel> CurrentPetEvents
         {
             get => _currentPetEvents;
             set
             {
                 {
                     _currentPetEvents = value;
                     OnPropertyChanged(nameof(CurrentPetEvents));
                 }
             }
         }
    
         public JournalViewModel()
         {
             CurrentPetEvents = new ObservableCollection<PawJournalEventModel>();
         }
    
         private void CreateJournalEvents()
         {
             if (CurrentItem != null)
             {
                 PetNameSelected = CurrentItem.PetName;
                 CurrentPetEvents.Clear();
                 List<PawJournalEventModel> pawJournalEventModels = CurrentItem.PawJournalEvents.ToList();
    
                 foreach (var Eventitems in pawJournalEventModels)
                 {
                     if(Eventitems.Title != "")
                     {
                         CurrentPetEvents.Add(new PawJournalEventModel()
                         {                      
                             TitleNote = Eventitems.Title + "- " + Eventitems.Notes,
                             DateTimeRepeat = Eventitems.EventDate + " " + Eventitems.EventTime + ", " + Eventitems.RepeatValue
                         });
                     }
                 }
             }
         }



tick and untick checkbox with typescript Angular 2

I currently working on a school assignment to create a checkbox in a table on admin side to disable/enable the dates on the calendar for users to make booking. If the checkbox is ticked/unticked which will insert a Y/N for that particular date in the table. currently, the checkbox has to be implement in resbooking.component.ts instead of resbooking.component.html.

in the resbooking.component.html

            <ng-table #resBookingTable [config]="config" #ngTable="ng-table" [rows]="data" [columns]="columns">
            </ng-table>
in the resbooking.component.ts
// Data Table
  public columns: Array<any> = [
    .....
    { title: 'Restaurant Booking', name: 'resBooking' }
  ];

// html part of checkbox in ts file
  "resBooking": '<input #resbookChkBox id="resbookChkBox" type="checkbox" function="resbookingfn" />'


// function wrote for control the checkbox 

   if (targetTagName === "INPUT") {
      if (target.getAttribute("function") != null) {
        let functionAccessed = target.getAttribute("function");
        if (functionAccessed === "resbookingfn") {
          $('#resbookChkBox').prop("checked",true);
        }
      }
    }
    
 

I have tried many methods such as:

  1. target.setAttribute("checked","true/false/checked") // still not able to untick
  2. target.removeAttribute
  3. jquery such as $(id).prop("checked")
  4. angular ng model such as 2 way databinding Angular 2 Checkbox Two Way Data Binding

Thank you for the all the help. **I am using Angular 2 and not able to allow to upgrade.




mardi 15 mars 2022

React update checkbox from object value

I'm trying to control a checkbox by using the value property that is coming from tableData. And by default the value is true.

let newData = newRes.data.map((e) => {
        return {
          ...e,
          installmentChecked: true,
          lateFeeChecked: true,
          depositChecked: true,
          collectionChecked: true,
        };
      });
     setTableData(newData);

After I mapped the data, I return the input like this.

const { data, index } = props;
return(
...
<input
  type="checkbox"
  value={latefee}
  checked={data?.lateFeeChecked}
  onChange={() => onChangeCheckbox('lateFeeChecked', index,data?.lateFeeChecked)}
/>
...

And this how I handle the value of the object.

const onChangeCheckbox = (key, index,status) => {
    tableData[index][key] = !tableData[index][key];
    console.log(tableData[index][key], 'props key');
    console.log(status, 'status');
  };

The problem that I'm getting is, the checkbox won't change at all. When I click, the console says.

false 'props key'
true 'status'

Is there any problem with my code? Or maybe anyone could gimme a better way to handle a checkbox in React? Appreciate any kind of responses, thanks before.




How to select multiple posts through django checkboxes for comparison on a seperate page but pagination not allowing it

I'm a beginner in Django. Thanks for your help and patience.

I have a model which I use to show a list of posts. I am using django pagination as there are many posts. I want the visitor to be able to select some posts through checkboxes. The selected posts are then used for comparison on a seperate page.

In the html template, I have all the posts inside a form - each post is associated with a checkbox (checkbox is not part of the model). When a visitor selects some posts and clicks a submit button, then a view function returns a page with the selected posts for comparison. It all works fine, but the problem is with the pagination - i.e., when the visitor selects posts from different pages. For example, when selecting posts from the second page, those that were selected in the first page are not considered (no longer checked ?).

I have looked at using sessions, form wizard, etc. But I still can't figure out how they can help or what is the appropriate approach for me to investigate more.

Any guidance would be appreciated.