mardi 30 novembre 2021

How to use material UI Checkbox with formik?

I am not able to code in the right way such that formik.values will reflect into Material UI's Checkbox




Why can't my checkbox affect my div contents?

I have a checkbox and a div element. When I click on the checkbox, the contents of the div elements are supposed to rotate to form a cross. But it does not do that. Below is the code

:root {
  --main-color: red;
  --secondary-color: blue;
  --dark-color: #444;
  --light-color: #fafafa;
}

body {
  font-family: 'Montserrat', sans-serif;
  text-align: justify;
  margin: 0px;
  display: grid;
  place-items: center;
  font-size: 18px;
}

input {
  box-sizing: border-box;
}

.toggle {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

span {
  height: 20px;
  width: 100px;
  display: grid;
  place-items: center;
  background-color: blue;
  margin: 5px 0;
}

.check:checked~span {
  background: red;
}

.check:checked~.span-one {
  position: relative;
  top: 100%;
  transform: rotate(45deg);
  transition: 400ms;
}

.check:checked~.span-two {
  position: relative;
  opacity: 0;
  transition: 400ms;
}

.check:checked~.span-three {
  position: relative;
  bottom: 100%;
  transform: rotate(-45deg);
  transition: 400ms;
}
<input class="check" type="checkbox">
<div>
  <span class="span-one"></span>
  <span class="span-two"></span>
  <span class="span-three"></span>
</div>

It works without the div but I need the div for something else so I can't remove that.

How do I fix this?




Delete selected checkbox rows from mysql using php

I am having troubles with deleting the selected checkbox rows from mysql using php code. I tried searching for the same problem here and implementing the logic in my practice project, but it doesn't seem to work. Once I select the checkboxes to delete, it loads the blank page and nothing is deleted.

The first two parts with inserting new values and deleting the row by typing the ID work correctly.

Here's my code.

<?php

if (isset( $_POST["create"])){
    
    $conn= mysqli_connect("localhost","root","" );
    mysqli_select_db($conn, "phonebook_assignement");
    $phonenumber= $_POST["number"];
    $textname= $_POST["name"];
   
    $sql = "INSERT INTO contacts(name, number) VALUES ('$textname', $phonenumber)";
    //exit($sql);
    $rs= mysqli_query($conn,$sql);
   // exit($rs);
  
    if ($rs) {
       echo "Record inserted";
    }
   
    mysqli_close($conn);
    die();
}

elseif (isset($_POST["delete"])){
    $conn= mysqli_connect("localhost","root","" );
    mysqli_select_db($conn, "phonebook_assignement");
    $id= $_POST["id"];
    $delete = "DELETE FROM contacts WHERE id=$id";
    $sqlDelete= mysqli_query($conn, $delete);
enter code here

    if ($sqlDelete){
        echo "Record deleted";
    }

    mysqli_close($conn);    
    die();
}




elseif (isset($_POST["delete"])){
    $conn= mysqli_connect("localhost","root","" );
    mysqli_select_db($conn, "phonebook_assignement");
    $checkbox= $_POST["checkbox"];
    for($i=0;$i<count($checkbox);$i++){

        $del_id = $checkbox[$i];
        $deleteBox = "DELETE FROM contacts WHERE id=$del_id";      
        $boxDelete= mysqli_query($conn, $deleteBox);
    }

    if ($boxDelete){
        echo "Record deleted";
    }

    mysqli_close($conn);    
    die();
}
    
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"> 
    <title> Phonebook assignement</title> 
</head>   

<body>    

<?php

$conn= mysqli_connect("localhost","root","" );
mysqli_select_db($conn, "phonebook_assignement");

$result= mysqli_query($conn, "SELECT * FROM contacts");

while ($rw=mysqli_fetch_row($result))
    echo  '<form method="POST" action="dbassignment_testcheckbox.php"><input type="checkbox" name="checkbox[]" id="checkbox" value="<?php echo $rw["id"]; ?></form>' . "ID: ". $rw[0]. "- Name: ". $rw[1]. "- Phone Number: ". $rw[2]. "<br>";
?>

<br>
<fieldset>
<form method="POST" action="dbassignment_testcheckbox.php" name="createUser">
    
        <label for="name">Insert new name : </label>
        <input type="text" name= "name" id="name">

        <label for="number">Insert new phone number : </label>
        <input type="text" name="number" id="number">


        <input type="submit" name="create" value="Insert"><br><br>

    
        <label for="delete">Delete row number : </label>
        <input type="number" name= "id" id="delete">
        <input type="submit" name="delete" value="Delete">
</form>
</fieldset>
<?php   

?>

</body>
</html>

Thank you.




Checkbox be checked, unique custom attribute

How can a checkbox be checked using JavaScript: (cpf="45258236978")

<input type="checkbox" style="vertical-align: bottom;" id_pasta="26337043" cpf="45258236978" id_tarefa="122525428">



Angular Material Checkbox disabled on condition

In my Angular application I have a dynamically generated reactive form with multiple FormArrays. On of these FormArrays contains 6 checkboxes. I only want a user to be able to check 3 boxes, so I have a count for the amount of selected checkboxes. When the count is over 3 a boolean is set to true and if the count is under 3 it is set to false again. The problem here is that once the checkboxes are disabled, a user can not unselect one of his selected boxes since the checkboxes are completely disabled.

What i am trying to accomplish is that unselected checkboxes can no longer be selected once the count is higher than 3, while the user is still able to unselect his already selected checkboxes.

I am using the Angular Material checkboxes with the [disabled] attribute. How can I achieve described behaviour?

HTML

<mat-checkbox *ngIf="option.key === 'vacancy'" (change)="onCheckboxChangeEvent(option.key, value, $event)" [checked]="isActiveValue(optie.key, value)" [disabled]="vacancyDisabled">
                            </mat-checkbox>

TS

onCheckboxChangeEvent(
    key: string,
    value: string,
    event: MatCheckboxChange
): void {
    const feature = this.candidateForm?.get(key) as FormArray;

    if (event.checked) {
        if (key === 'vacancy') {
            this.selectedVacancy++;
            if (this.selectedVacancy >= 3) {
                this.vacancyDisabled = true;
                console.log('disable');
            }
        }
        feature.push(new FormControl(value));
    } else {
        if (key === 'vacancy') {
            this.selectedVacancy--;
            if (this.selectedVacancy <= 3) {
                this.vacancyDisabled = false;
                console.log('enable');
            }
        }
        const index = feature.controls.findIndex((x) => x.value === value);
        feature.removeAt(index);
    }
}



JQuery check/uncheck checkboxes based on filters

There are plenty of posts about checking/unchecking checkboxes but my case is totally different. I am trying to check/uncheck checkboxes based on the filters (i.e check/uncheck checkbox(es) of visible content), and skip the rest of the checkboxes which become invisible when the filter is applied.

    $('.select2-brands').on('change', function () {
        if ($(".select2-brands").val() == "-1") {
            $(".card-box-products").parent().show();
        } else {
            $(".card-box-products").parent().hide();
            $(".select2-brands").find("option:selected").each(function () {
                var optionValue = $(this).val();
                if (optionValue) {
                    $(".card-box-products:contains(" + optionValue + ") ").parent().show();
                } else {
                    $(".card-box-products").parent().show();
                }
            });
        }
    });
    
    $('#unselect_products').on('click', function () {

                if ($('div#product_box .card-box-products').css('display') != 'none') {

                    $('input[type="checkbox"]').prop('checked', false);
                    // alert('hi');
                } else {
                    // $('input[type="checkbox"]').prop('checked', true);
                    $('input[type="checkbox"]').prop('checked', true);
                }

    });
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="  crossorigin="anonymous"></script>

<span class="ml-2"><input type="checkbox" class="control-input" id="unselect_products" name="unselect_products" checked/><strong> Unselect Products </strong></span>   
<div class="row" id="product_box"><h4 class="mt-0 mb-2 header-title col-md-12">
        Products
    </h4>
    <div class="col-md-3">
                <select class="form-control select2-brands" multiple="multiple">
                  <option value="-1"> Select All </option>
                  <option value="Hisense"> Hisense </option>
                  <option value="Bestron"> Bestron </option>
                  <option value="AEG"> AEG </option>
                  <option value="TIN"> TIN </option>
                  <option value="NEFF"> NEFF </option>
                  <option value="TESTING"> TESTING </option>
                  <option value="TESTING"> TESTING </option>
                  <option value="NESTRON"> NESTRON </option>                  
                </select>
            </div>
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
               
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">Hisense</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="219.09" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="219.09" data-id="1119220" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">Bestron</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="244.65" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="244.65" data-id="1119293" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
               
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">AEG</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="249.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="249.75" data-id="1119276" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">Bestron</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="299.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="299.75" data-id="1119204" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">TIN</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="69.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="69.75" data-id="1119235" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">NOE</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="287.25" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="287.25" data-id="1119275" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">AEG</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="149.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="149.75" data-id="1119273" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
                    <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
              
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">TESTING</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="124.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="124.75" data-id="1119167" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">NEFF</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="242.25" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="242.25" data-id="1119169" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
        <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
                
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">FOIL</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price :</strong><span class="ml-2"><input type="text" value="159.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="159.75" data-id="1119178" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
                <div class="col-xl-3 col-md-6">
        <div class="card-box card-box-products widget-user" style="padding:1rem!important;">
            <div class="media">
               
                <div class="media-body overflow-hidden">
                    <p class="text-muted font-13 my-0"><strong>Brands :</strong><span class="ml-2">FILE</span></p>
                    <hr style="height: 1px;background:#e8e8e8;" class="my-2">
                    <p class="text-muted font-13 my-0"><strong>Price:</strong><span class="ml-2"><input type="text" value="199.75" class="product_price_field" name="product_price_field"></span></p>
                    <p class="text-muted font-13 my-0 d-flex"><strong>Add :</strong><span class="ml-2"><input type="checkbox" class="control-input product_add_checkbox cb_style" data-price="199.75" data-id="1119166" checked=""></span></p>

                    
                </div>
            </div>
        </div>
    </div><!-- end col -->
  
</div>

I tried hard to find any solution but all went in vain. It would be a big help if you could find a solution of it.

NOTE: HTML is being rendered in the DOM of each card and I don't want to give the unique ID to each checkbox.




Set value of DataGrid cell when CheckBoxColumn in same row is checked

I've a DataGrid with several columns, one of which is a CheckBoxColumn. When the CheckBox is checked, I want to set the value of another cell in that DataGrid row (column "Verifisert").

How can I do that? Whether it is done in code-behind or not, is irrelevant to me.

<DataGrid x:Name="dg_preview_invoice"                
                    AutoGenerateColumns="False">                   
    <DataGrid.Columns>      
        <DataGridCheckBoxColumn Width="*" HeaderStyle="{StaticResource CenterGridHeaderStyle}"
                                            Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}">
           
            <DataGridCheckBoxColumn.Header>

                <CheckBox x:Name="cbc_check_all" HorizontalAlignment="Center"
                                      IsChecked="False" Checked="{s:Action CheckAllPreviewInvoices}"
                                      Unchecked="{s:Action UncheckAllPreviewInvoices}"></CheckBox>
            </DataGridCheckBoxColumn.Header>
        </DataGridCheckBoxColumn>

        <DataGridTextColumn Header="Verifisert" Width="95"
                                        HeaderStyle="{StaticResource CenterGridHeaderStyle}"
                                        Visibility="Hidden"/>

    </DataGrid.Columns>
</DataGrid>



Clicking on a check box using selenium - Python

I am trying to click on a check box. Below is the HTML Code

<div class="mb-1 p-3 termsCheck">
            <input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span>
                    Agree to Terms &amp; Conditions </span> / <span> أوافق على الشروط والأحكام
            </span> </label>
        </div>

I am using the below code to click on it.

check = driver.find_element(By.CSS_SELECTOR, '#flexCheckDefault')
check.click()

I am getting this error

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (477, 1222)

full error:

     driver.find_element(By.XPATH, "//label[@for='flexCheckDefault']").click()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
    return self._parent.execute(command, params)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 1317)
  (Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x556910005919 <unknown

Can some please help me with this.

when I am using the below code I am getting this error::

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()

Error

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
    return self._parent.execute(command, params)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 467)
  (Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x563f45805919 <unknown> 



How to fill array of boolean values on checkbox change event?

What I would like to do is, filling the answers array with boolean values.My checkboxes are populated dynamically but there will be only four of them. If checkbox is unchecked then its value should be false and if checked it should be true.Values should correspond to array index, I mean if first checkbox is switched then only answers[0] should change, if second checkbox is changed then answers[1] and so on..

I would also appreciate if you can help me setting the checked value as well.

In the end I am setting this values to the context store to be send to server in the end.

const Quiz1 = (props) => {
      const [answers, setAnswers] = useState([false, false, false, false]);

  const handleChange = (e) => {
     setAnswers([...answers, e.target.checked]);
     setQuizState({ id: 0, question_id: question.question_id, answer: [answers] });
  };
    return (
    {question?.options?.map((option, i) => { 
       <Checkbox
         id={i}
         name={option}
         checked={WHAT TO PUT HERE?}
         onChange={(e) => handleChange(e)}
      />}
 )
}



lundi 29 novembre 2021

Javascript hide/show elements does not work properly

I have added this checkbox to my form:

<div class="row">
  <div class="form-group col">
    <input type="checkbox" name="prd_presell" id="product_presell" 
      onclick="presellTXT()" value="TRUE" @if(!empty($product)) @if($product->prd_presell == 'TRUE') checked @endif @endif>
    <label for="presell_product">Presell Product</label>
  </div>
</div>

So there is an onClick function named presellTXT() which goes like this:

function presellTXT() {
        var presell_checkbox = document.getElementById("product_presell"); // get checkbox
        
        var presell_text = document.getElementById("show_presell_text"); // text div
        
        var presell_text_input = document.getElementById("presell_product_text"); // text input
        
        if (presell_checkbox.checked == true){
            presell_text.style.display = "block";
        } else {
            presell_text_input.value = "";
            presell_checkbox.value = "";
            presell_text.style.display = "none";
        }
    }

So when the checkbox is checked, it basically shows the element with an id of show_presell_text:

<div class="row" id="show_presell_text">
  <div class="col-lg-12">
    <div class="form-group">
      <label>Product Presell Text:</label>
      <input name="prd_presell_text" id="presell_product_text" class="form-control" value="">
    </div>
  </div>
</div>

So when the page loads, it should not be showing the Product Presell Text unless the checkbox is checked.

Now if you take a look at jsfillde example, you can see as soon as the page loads, the text input appears however the checkbox is not checked at all!

So how to hide the text input when the page loads and the checkbox is not checked?

Note: I don't want to use CSS for this because I need to determine correctly if prd_presell is checked on page loads (because of @if($product->prd_presell == 'TRUE') which retrieves data from the DB) then it has to show the Product Presell Text text input.




How to limit the number of selected checkboxes in checklist in Dash(plotly)?

My question is the same as this one that is how to limit selected number of checkboxes but I wanted this feature for the checklist in Dash provided by plotly. I have read the official documentation but can't find anything useful.

Thanks for the help in advance.




Multiple checkbox filtering tornadofx

i'm new to tornadoFx dekstop developing and faced with a problem of filtering my tableview formed by psql, using checkboxes while i do it with a one checkbox is ok

checkbox("От кого") {
                                        action(){
                                            calls.setAll(
                                                psqlController.filteredResultCaller(input.value)
                                                    .map { it.toTableModel() })
                                            input.value = ""
                                        }
                                

}

and the same for calles

'checkbox("Кому") {

                                    action {
                                        calls.setAll(
                                            psqlController.filteredResultCallee(input.value)
                                                .map { it.toTableModel() })
                                        input.value = ""
                                    }
                                }'

i wanna somehow combine theese 2 selectors for making 1 request to db by 2 filters




how to map API list data to single checkbox? in flutter

Hi i am new to flutter i need help in getting API data and display with a checkbox to select and deselect. i have used sample API database which contains the information of 10 users. I want to display Users Id, name, Username, company name and phone number as a card or list tile per user. I also want to assign single checkbox per card/list tile with check / uncheck functionality.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_application_http_get/example.dart';
import 'package:flutter_application_http_get/screen.dart';
import 'package:flutter_application_http_get/sunday_state.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Sunday(),
    );
  }
}

Here's My ApI Get method

class Sunday extends StatefulWidget {
  const Sunday({Key? key}) : super(key: key);

  @override
  _SundayState createState() => _SundayState();
}

class _SundayState extends State<Sunday> {
  var users = [];
  Future getUserData() async {
    var res =
        await http.get(Uri.https("jsonplaceholder.typicode.com", "users"));
    var jsonData = jsonDecode(res.body) as List;

    setState(() {
      users = jsonData;
    });
  }

  @override
  void initState() {
    super.initState();
    getUserData();
  }

here's my build method

 Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("User Data"),
      ),
      body: Container(
        child: Card(
          margin: EdgeInsets.all(20.0),
          child: ListView.builder(
              itemCount: users.length,
              itemBuilder: (context, i) {
                final post = users[i];

                return Card(
                    elevation: 5,
                    child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: ListView(shrinkWrap: true, children: [
                          // singlecheckbox(notification),
                          ...notification.map(singlecheckbox).toList(),
                          Text("${post['id']}"),
                          Text("${post['name']}"),
                          
                        ])

here's my widget to toggle check box

final notification = [SundayCheckBoxState()];
void togglegroupcheckbox(bool? value) {
    if (value == null) return;
    setState(() {
      // notification.value = value;
      notification.forEach((element) => element.value = value);
    });
  }

  Widget singlecheckbox(SundayCheckBoxState checkbox) {
    return CheckboxListTile(
      controlAffinity: ListTileControlAffinity.leading,
      activeColor: Colors.green,
      value: checkbox.value,
      // title: Text('${users.last['name']}'),
      onChanged: togglegroupcheckbox,

      
    );



Update depending on checkbox if it's check or not it's not working for me

please I am new in php and as you can see in picture I have this table filled from a database called produit in mysql, I want when I checked one of the checkbox or tow or all of them enabled date columns and edited and when I click in button enregistrer do update. I tried a lot of codes and it's not working for me.

enter image description here

$query = "select * from produit where  Id_Projet = " . $_SESSION["SSidProjet"] . "";

$query_run = mysqli_query($link, $query);

echo '<form id="form1" method="post">';
echo '<table id="dataTable" class="table table-bordered">';
echo "<thead>";
echo "<tr>";
echo '<th><input type="checkbox" id="selectall" /></th>';
echo "<th>Numéro Produit</th>";
echo "<th>Dénomination</th>";
echo "<th>Superficie</th>";
echo "<th>Titre Foncier</th>";
echo "<th>Date Reception Administratif</th>";
echo "<th>Date Contrat</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";

if($query_run)
{
    while($row = mysqli_fetch_array($query_run)){
        echo "<tr>";
        echo '<td><input type="checkbox" value="' . $row['Id_Produit'] . '" name="TcheckBox[]" /></td>';
        echo '<td>' . $row['Num_Produit'] . '</td>';
        echo "<td>" . $row['Libelle_Produit'] . "</td>";
        echo "<td>" . $row['Superficie_Produit'] . " </td>";
        echo "<td>" . $row['Titre_Foncier_Produit'] . " </td>";
        echo "<td><input id=\"DateRA\" type=\"date\" value=" . $row['Date_Reception_Administratif_Temp'] . " readonly=\"readonly\" disabled ></td>";
        echo "<td><input id=\"DateC\" type=\"date\" value=" . $row['Date_Contrat_Temp'] . " readonly=\"readonly\" disabled ></td>";
        echo "</tr>";
    }
}

echo "</tbody>";                            
echo "</table>";
echo '<input type="submit" name="enregistrer" value="Enregistrer" />';
echo "</form>";

if(isset($_POST['enregistrer'])){
    $q="update produit set Date_Contrat_Temp='2021/12/01' where Id_Produit=";
    for ($i=0; $i<count($checkBox); $i++)
        $q .= "".$checkBox[$i]."";
    mysqli_query($q) or die (mysqli_error() );



How do I uncheck checkbox in Laravel livewire for the changes to reflect in the database?

Please I need assistance solving this problem, I am using laravel Spatie roles and permission, I want to add permissions to the role using checkboxes, so far adding permission to roles is working fine, but when editing roles if I unchecked permission for a role it doesn't reflect the changes in the database,any help will be appreciated

enter image description here

This is view

  <!-- Modal -->
 <div class="modal " id="roleModal" tabindex="-1" aria-labelledby="roleModalLabel" aria- 
   hidden="true">
   <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="roleModalLabel">Role</h5>
           <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <form method="POST">
                    @csrf

    <div class="col-span-6 sm:col-span-4">
        <x-jet-label for="role" value="" />
        <x-jet-input id="role" type="text" class="mt-1 block w-full" 
    wire:model.defer="roleName" />
        <x-jet-input-error for="role" class="mt-2" />
    </div>

      <div class="block">
        <strong>Permission:</strong>
        <br/>
        @foreach($permissions as $key => $permission)
         <x-jet-label value="" />
         
        <x-jet-checkbox  id="permission" value=""  
         type="checkbox" class="mt-1 block " wire:model.defer="permissionId"   />
        <br/>
        @endforeach
   </div>
    --}}
    </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="bg-red-500 text-white active:bg-indigo-600 px-3 py-2 
   rounded outline-none focus:outline-none" wire:click="closeModal">Close</button>

    @if ($editMode)
        <button type="button" class="bg-indigo-500 text-white active:bg-indigo-600 px-3 
     py-2 rounded outline-none focus:outline-none" wire:click="updateRole">Save 
    changes</button>
    @else

    <button  type="button" class="btn btn-primary" wire:click="storeRole">Create 
   Role</button>
  @endif
  </div>
</div>

This is the role livewire component

class Roles extends Component
{

    public $editMode = false;
    public $roleId;
    public $roleName;
    public $permissionId = [];


    public function showEditModal($id)
    {
        $this->reset();

        $this->editMode  = true;

        $this->roleId = $id;

       
        $this->loadRole();

        $this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'show']);
        
    }

    public function loadRole()
    {
        $role = Role::find($this->roleId);

        $this->roleName = $role->name;
        $this->permissionId = $role->permissions->pluck('id');

    }


    public function updateRole()
    {
       
        $role = Role::find($this->roleId);

        $role->update(['name'  => $this->roleName ]);

        $role->syncPermissions($this->permissionId);
        
        
       
        $this->reset();
        
        $this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'hide' ]);
        
        session()->flash('message', 'Role Updated Successfully');
    }

    public function deleteRole($id)
    {
        $role = Role::find($id);

        $role->delete();

        session()->flash('message', 'Role Deleted Successfully');
    }


    public function closeModal()
    {
        $this->reset();
        $this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'hide' ]);
    }
    
    public function render()
    {
        $roles = Role::orderBy('id','DESC')->paginate(5);

        $permissions = Permission::get();

        
      

        return view('livewire.roles', ['roles' => $roles, 'permissions' => $permissions ]);
    }
}



Checkbox in Dropdown Jupyter Widget Python

I have a Dataframe with one column , "Intimation month" in it.

Index Intimation Month 0 6 1 8 2 9 3 9 4 9 .. 24856 8 24857 9 24858 9 24859 8 24860 8

I want to create a dropdown with unique values of Intimation month and checkbox should be enabled in the dropdown because I want to select multiple months in the dropdown and then continue with further processing.

I wrote the below code for dropdown with unique values of months but I want checkboxes corresponding to a month number.

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

months=df['Intimation month'].dt.month
months= set(months)

w=widgets.Dropdown(
    options= [i for i in months],
    value= None,
    description='Month:',
)

display(w)



dimanche 28 novembre 2021

The custom CheckBoxListTile does not pass checked state to the child checkbox

I'm trying to use the check box (child widget) in a parent widget which has a label in front of the check box. I'm trying to create a custom version of CheckBoxListTile.

Problem: When you tap the label the check box does not change, but check box itself change when you tap.

My aim is, when you tap on the parent widget (both label and checkbox), the check box should check/uncheck.

enter image description here

Child widget

import 'package:flutter/material.dart';

class CheckBox extends StatefulWidget {
  final Function runThisFunction;
  final double size;
  final double borderStrokeWidth;
  final Color iconColour;
  final Color borderColour;
  final Color checkedBackColour;
  final bool isChecked;

  const CheckBox({
    Key? key,
    required this.runThisFunction,
    this.size = 30,
    this.borderStrokeWidth = 3,
    this.iconColour = Colors.white,
    this.borderColour = Colors.white,
    this.checkedBackColour = const Color(0xff00D5DD),
    this.isChecked = false,
  }) : super(key: key);

  @override
  _CheckBoxState createState() => _CheckBoxState();
}

class _CheckBoxState extends State<CheckBox> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    

    return Column(
        
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Column(
           
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
               
                children: [
                  InkWell(
                    onTap: () {
                      widget.runThisFunction();
                      setState(() {
                        isChecked = !isChecked;
                         
                      });
                    },
                    child: Container(
                      width: widget.size,
                      height: widget.size,
                      
                      decoration: BoxDecoration(
                        color: (isChecked == true)
                            ? widget.checkedBackColour
                            : Colors.transparent,
                        border: Border.all(
                          width: widget.borderStrokeWidth,
                          color: Color(0xff40D4E8),
                        ),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: FittedBox(
                        child: (isChecked == true)
                            ? Center(
                                child: Icon(
                                  Icons.check,
                                  color: widget.iconColour,
                                  size: 15.0,
                                ),
                              )
                            : Container(),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ]);
  }

Parent Widget

import 'package:flutter/material.dart';

class DetailsCheckLine extends StatefulWidget {
  final double sentenceWidth;
  final double gap;
  final double strokeWidth;
  final double checkBoxSize;
  final String description;
  final double lineToTextGap;
  final Color lineColour;
  final Function passThisFunction;

  const DetailsCheckLine({
    Key? key,
    this.sentenceWidth = 100,
    this.description = 'Description',
    required this.passThisFunction,
    this.gap = 10,
    this.checkBoxSize = 8,
  }) : super(key: key);

  @override
  _DetailsCheckLineState createState() => _DetailsCheckLineState();
}

class _DetailsCheckLineState extends State<DetailsCheckLine> {
   
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    double lineWidth =
        widget.checkBoxSize + widget.sentenceWidth + widget.gap + 30;
    
    return InkWell(
        onTap: () {
          setState(() {
            
            isChecked = !isChecked;
          });
        },
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: <
            Widget>[
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Center(
              child: Container(
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Column(children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              
                              isChecked = !isChecked;
                            });
                          },
                          child: CheckBox(
                              isChecked: isChecked,
                              runThisFunction: () {
                                widget.passThisFunction();
                              }),
                        ),
                      ]),
                      SizedBox(
                        width: widget.gap,
                      ),
                      Column(
                          
                          children: <Widget>[
                            Container(
                                width: widget.sentenceWidth,
                                child: RichText(
                                     
                                    text: TextSpan(
                                        style: oneLinerTextDefaultStyle,
                                        children: <TextSpan>[
                                      
                                      TextSpan(text: widget.description)
                                    ]))),
                          ]),
                    ]),
              ),
            ),
          ]),



React native nativebase checkbox: Text inside a checkbox going out of the screen

I cant make it work, text inside a checkbox (nativebase) is not shrinking, does anyone knows why? Am i missing some flex properties?

import React from "react"
import {Box, Center, Checkbox, Heading, NativeBaseProvider, Text} from "native-base"

export const List = () => {
    return (
        <Box mb="10%" mt="30%" width="80%" height="80%" maxHeight="80%">
            <Checkbox value={"superlongipermegatest"}>
                <Text mx="2">
                    superlongipermegatest
                </Text>
            </Checkbox>
        </Box>
    )
}

export default () => {
    return (
        <NativeBaseProvider>
            <Center
                flex={1}
                px="1">
                <List/>
            </Center>
        </NativeBaseProvider>
    )
}




samedi 27 novembre 2021

Remove inaccessible vertical checkbox margin

I am trying to create a grid of checkboxes. Therefore I am trying to remove all whitespaces between them, but there seem to be some vertical margins or line heights in the background that I cannot control:

input[type=checkbox] {
  display: inline-block;
  margin: 0;
}
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>

But I know it has to be possible, since, with display: block, the vertical margin is gone.

input[type=checkbox] {
  display: block;
  margin: 0;
}
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>
<div><input type="checkbox"><input type="checkbox"><input type="checkbox"></div>
well, I need them inline though.

Where is the space coming from and how can I get rid of it?




Python PyQt5: How do i make a checkbox state the factor that has allows user to proceed

So i am making an application where i would like the user to accept some terms via a checkbox. I've gotten the checkbox to execute a function when checked, but i cant figure out how i would make all the other functions and widgets look at that checkbox state to see if they can execute.

#function for if the box is checked
        def agree_box():
            if 

        #Agree box
        self.agree_box = QtWidgets.QCheckBox(self.centralwidget)
        self.agree_box.setGeometry(QtCore.QRect(340, 140, 141, 17))
        self.agree_box.setObjectName("agree_box")
        self.agree_box.stateChanged.connect(agree_box)



round off the amount if checkbox is checked

if the checkbox is checked the total amount should be roundoff. if the checkbox is unchecked the total value in decimals in angular js tell me from starting, I didn't start $scope.checked=?




Checkbox / Radiobutton custom image

I need to make a VB.NET application with checkboxes and radio buttons. But I want to replace the checkbox/radio button for images (with text labels inside, would be nice I the customer can change the text label). This to make it more appealing for the customer :-)

But I do not know where to start. I already searched the web, but haven't found anything useful. Any tips, links, example programs?




How to validate multiple checkboxes in JavaScript?

I have 4 checkboxes, I want to show different alerts for first two when they are selected but not getting the output.Please let me know where it went wrong.

let ReviewCheckBox = checkform.ratings;
if (ReviewCheckBox[0].checked == true) {
  alert("1 Selected");
} else if (ReviewCheckBox[0].checked == true && ReviewCheckBox[1].checked == true) {
  alert("Both Selected");
}
<div>
  <span>CUSTOMER REVIEWS</span><br>
  <form name="checkform" onclick="productFilter()">
    <input type="checkbox" name="ratings" id="rating-checka">
    <label for="rating-checka">4 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkb">
    <label for="rating-checkb">3 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkc">
    <label for="rating-checkc">2 * & Above</label><br>

    <input type="checkbox" name="ratings" id="rating-checkd">
    <label for="rating-checkd">1 * & Above</label>
  </form>
</div>



vendredi 26 novembre 2021

React material-ui multiple checkboxes and onChange not working

I have multiple checkboxes in an edit modal form, which has a record structure for update, containing the inputs including the checkboxes in state. There is one onChange event for the inputs.

When I click on a checkbox, the onChnage 'handleInputChanges' does execute. The evt.target.checked is true or false. The evt.target.name is correct and matches the name in the updateRecordStructure.

But the checkbox won't display the checked or unchecked status.

The markup:

<Grid item xs={5}>
    <FormControlLabel variant="outlined" size="small"
         control={<Checkbox
         checked={defaultChecked}
         color="primary"
         name={name}
         onChange={handleInputChanges}/>
        }
        label={label}
        id={id}
    />
</Grid>

    const updateRecordStructure ={
            id: 0,
            name: '',
            canDo1b: false,
            canDo1a: false,
            canDo2b: false,
            canDo2a: false
 };
     
 const [editRecordState, setEditRecordState] = React.useState(
    updateRecordStructure
);

   const handleInputChanges = (evt) => {
    //  Distinguish which input the change is coming from using the target.name.
    //  The square brackets around target.name, creates a dynamic key of that targets name in the object.
      
    if (evt.target.name !== '') {
        const value = evt.target.value;

         if (evt.target.checked) {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: evt.target.checked
            });
        } else {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: value
            });
        }
    }
};



How do I make the value of the checkbox appear?

I have been trying to make a simple "click and submit your element". I don't believe I did it justice since it won't work, and the best I can say is I have tried to come at it from each angle I could think of in order to have the value of that specific checkbox appear up on the screen not just the console.

 <div class="elementWheel">
        
        <input type="checkbox" value="water" class="water pickColor" />
        <input type="checkbox" value="wind" class="wind pickColor" />
        <input type="checkbox" value="earth" class="earth pickColor" />
        <input type="checkbox" value="fire" class="fire pickColor" />

        <input type="button" id="demo" value="demo" />

    </div>
    <script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
    <script type="text/javascript">
        $("#demo").live("click", function () {
            $("input:checkbox[class=pickColor]:checked").each(function () {
                alert("Class: " + $(this).attr("class") + " Value: " + $(this).val());
            });
        });
    </script>



jeudi 25 novembre 2021

Checkbox is not updating checked or not checked when an item from cart reducer is removed from cart modal in react native bouncy checkbox

When i am on the menu page the user can check menu items to add them to cart and then it adds the selected items to cart and if cart.selecteditems.length > 0 the user can open a cart modal and can also increase quantity or decrease or remove the item from the modal. But when the user remove the item and closes the modal the checkbox of menuitem which was removed will be still checked the i need to fetch the menu again so that the page could re render and only added items should be checked Check Box Code

const cart = useSelector(state => state.cart)

const checkedAlreadyAdded = (id) => {
   let alreadyExist = cart.selectedItems.findIndex((obj)=> obj.itemId == id)       i 
   if(alreadyExist < 0){
      return false
   }else{
      return true
   }
}


<BouncyCheckbox
   onPress={()=>addItemToCart(item)}
   isChecked={checkedAlreadyAdded(item.id)}                                                  
 />

So the checkox is not updating its checked value when cart reducer make changes in selectedItems




Dynamic table using javascript?

  1. add new button doesn't work if any existing row is deleted before adding
  2. delete button doesn't work for newly added rows
  3. checkbox on the top should select/remove all rows
  4. age column is an integer, only numbers allowed

UPDATES

  1. add four more columns email, phone number, password, password confirmation. use validation on those columns while typing, if it's not valid then make the background color red, if it's valid background color green. (I.E: password must be at least 8 digits, contains at least 1 integer, confirm password must be same with the password.)



How to access from child checkbox to child class in different parent divs?

How can i rotate all 3 pictures on click on checkbox?

I am trying with ~ but it only affects on the image where checkbox is.

HTML:

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <input class="checkbox" type="checkbox" id="rotate">
  <label class="label-checkbox" for="rotate">Rotate</label>

  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

SCSS:

.checkbox:checked {
        ~ .img {
          transform: rotate(180deg);
        }
    }



I want to update mat-checkbox value in reactive form which are looped on Frontend using ngFor Angular 11

  1.                   </mat-checkbox>
    
         </li>
    

/typescript/ this.service.getCurrentData(this.router.snapshot.params.id).subscribe( (result)=>{ console.info('result is',result); this.camera.controls['camId'].setValue(result['camId']) this.camera.controls['ipAdress'].setValue(result['ipAdress']) this.camera.controls['userName'].setValue(result['userName']) this.camera.controls['password'].setValue(result['password'])

       for(var i = 0;i<this.Activity.length; i++){
        if( result.cameraActivity[i].featureId==this.Activity[i].activityFeatures[i].featureId)
        {
         
         this.activityfeature.patchValue(result['cameraActivity'][i].featureId);
          this.activityfeature.controls['featureId'].setValue(result['cameraActivity'][i].featureId)
        // this.activityfeature.controls['featureId'].setValue(result['cameraActivity'][i].featureId);
          console.log(result);
        }



How to print only the checked checkboxes? [duplicate]

How can I do possible using the standard browser print menu, print only selected checkboxes? Using javascript, of course. I am using Bootstrap default checkboxes. I mention that i am new to web development.

Checkbox list example:

<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">Option 1</label>
</div>
<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">Option 2</label>
</div>
<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">Option 3</label>
</div>



adding checkbox header in DGV c#

I saw a code to add a checkbox header in a DGV, but it is not working fine with my DGV.

the code:

private void addCheckBoxHeader()
        {
            DataGridViewCheckBoxColumn checkboxColumn = new DataGridViewCheckBoxColumn();
            checkboxColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            checkboxColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            DGViewListItems.Columns.Insert(0, checkboxColumn);

            Rectangle rect = DGViewListItems.GetCellDisplayRectangle(0, -1, false);
            rect.X = rect.Location.X + (rect.Width / 2);
            rect.Y = rect.Location.X + (rect.Width / 2);
            checkboxHeader = new CheckBox();
            checkboxHeader.BackColor = Color.FromArgb(0, 80, 200);
            checkboxHeader.Name = "checkboxHeader";
            checkboxHeader.Location = rect.Location;

            //checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged);

            DGViewListItems.Controls.Add(checkboxHeader);
            
        }

This is the output of the code above:

enter image description here

What is wrong with the code? How can I put the checkbox header correctly?

also, nevermind the Column1 column that is the column i added in the Design




How to capture a check box input element in Java script?

<form name="formname">
  <input type="text" maxlength="100" name="user_name" id="user_input"></input>
  <input type="checkbox" name="website_response[]" value="I really like your site" id="checkbox">I like your site</input>
  <input type="checkbox" name="website_response[]" value="One of the best site">One of the best site</input>
  <input type="checkbox" name="website_response[]" value="good site">Good Site</input>
  <input type="checkbox" name="website_response[]" value="I wish my site were good">I wish my site were good</input>
</form>

The above code conatins name attribute as an array. How do I access it in Javascript?




DEVEXPRESS DELPHI TCXTREELIST

I have such trees

  • A
    • aa
    • bb
  • B
    • abvb
    • aa
    • dhhht
  • C
    • sd
    • fgf

I want that if I checked on one 'aa', another 'aa' also checked. Is the any solution about this?




mercredi 24 novembre 2021

Check if all checkboxes are checked and console.log("all checked") Javascript/React

The following component is meant to be a To-Do list. I got multiple checkboxes. As soon as all checkboxes are checked, a console.log("all checked") should appear.

My idea is to check if the todo.lengh === checked.length, but it doesn't work.

Problem: trying to console.log(checked.length) doesn't work either so there must be the problem.

Can someone help me how to reach the checked.length?

import React from 'react';
import { AiOutlinePlusCircle } from 'react-icons/ai';
import { useState } from 'react';

function Checkboxes() {
  const [todo, setToDo] = React.useState('');
  const [todos, setToDos] = React.useState([]);
  const [checked, setChecked] = useState(false);

  function handleToDoSubmit(e) {
    e.preventDefault();

    const newToDo = {
      id: new Date().getTime(),
      text: todo,
      completed: false,
    };

    setToDos([...todos].concat(newToDo));
    setToDo('');
  }

  function toggleCompleteToDo(id) {
    const updatedToDos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setToDos(updatedToDos);
  }

  function allChecked(checked) {
    if (todo.length === checked.length) {
      console.log('all checked');
    }
  }

  return (
    <div className="ToDoList">
      <form className="goalInputToDo" onSubmit={handleToDoSubmit}>
        <input
          className="goalInput"
          type="text"
          onChange={(e) => setToDo(e.target.value)}
          value={todo}
        />
        <button className="AddGoalBtn" type="submit">
          .
          <AiOutlinePlusCircle size="2em" />
        </button>
      </form>

      {todos.map((todo) => (
        <div className="goalItem">
          <div key={todo.id}>
            <div>{todo.text}</div>
            <input
              type="checkbox"
              onChange={() => {
                toggleCompleteToDo(todo.id), allChecked(todo.checked);
              }}
              checked={todo.completed}
            />
          </div>
        </div>
      ))}
    </div>
  );
}
export default Checkboxes;



How to change the tick of the checkbox to black being by default in white in react-native-expo

I am needing to change the tick color to black when it is TRUE. which by default is white. I am importing my checkbox from expo-checkbox, I do not know what I would be doing wrong or if there is any property to change the color of it

<CheckBox
     disabled={false}
     checkboxDefaultColor="transparent"
     value={rememberMe}
     onValueChange={()=>setRememberMe(!rememberMe)}
     color={rememberMe ? {"checkboxDefaultColor": "transparent", "color": "#000"} : undefined}
     style={styles.checkbox}
/>

enter image description here




Create a new row of checkboxes

I have 10 checkboxes in a row currently, however it is very crowded. I would rather have 5 checkboxes in 2 rows but have no idea how to achieve this.

I am new to HTML so I may be forgetting something simple. I tried a couple of ways but nothing seems to work. (I left all the code just in case, but labelled where everything is. Checkboxes are at the bottom.)

Link: https://codepen.io/Tantlu/full/JjyQYZw

HTML

<body>
  <div class="video-bg">
 <video width="320" height="240" autoplay loop muted>
  <source src="https://assets.codepen.io/3364143/7btrrd.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
  
<!-- Header -->  
  
<h1>Design Survey.</h1>  

<!-- Form -->  
  
<form class="form">
  
 <!-- Form Element 1 --> 
  
 <div class="form-control">
   <label for="name" class="label-name">
     Name
   </label>
  <input type= "text" id= "name" placeholder= ""/>
        </div>
  
  <div class="form-control">
   <label for="email" class="label-email">
     Email
   </label>
  <input type="email" id= "email" placeholder= "" />
        </div>
  
  <div class="form-control">
   <label for="age" class="label-age">
     Age
   </label>
  <input type= "number" id= "age" placeholder= ""/>
        </div>
  
  <!-- Drop Down Box -->
  
  <div class="form-control">
    <label for="edu" id="label-edu">
       What is your education level?
    </label>
    
   <div class="options"> 
    <select name="edu" id="dropdown">
      <option hidden></option>
      <option value="high-school">High School</option>
      <option value="cert-4">Certificate IV</option>
      <option value="diploma">Diploma</option>
      <option value="b-degree">Bachelors Degree</option>
      <option value="m-degree">Masters Degree</option>
     </select>
    </div>  
  </div>      
    
    
<div class="form-control">
  <label>Do you like this design?</label>
 
<!-- Radio Buttons -->
  
 <div class="rad-row"> 
  <label for="rad1" class="rc-label">
    <input type="radio" id="rad1" name="radio">
    <span class="rc-text">Yes</span>
    </input>
  </label>
  
  <label for="rad2" class="rc-label">
    <input type="radio" id="rad2" name="radio">
    <span class="rc-text">No</span> 
    </input>
  </label>
  
  <label for="rad3" class="rc-label">
    <input type="radio" id="rad3" name="radio">
    <span class="rc-text">Unsure</span> 
    </input>
  </label>
  </div>
</div>

<!-- Checkboxes -->

<div class="form-control">
  <label class="label2">Languages and frameworks known</label>

<div class= "checkbox-row">
<label for="inp-1" class="rc-label">
   <input type="checkbox" id="inp-1" name="inp">
  <span class="rc-text">C</span>
  </input>
 </label>
   
<label for="inp-2" class="rc-label">
   <input type="checkbox" name="inp" id="inp-2">
  <span class="rc-text">C++</span>
  </input>
 </label>

<label for="inp-3" class="rc-label">
   <input type="checkbox" name="inp" id="inp-3">
  <span class="rc-text">C#</span>
  </input>
 </label>

<label for="inp-4" class="rc-label">
   <input type="checkbox" id="inp-4" name="inp">
  <span class="rc-text">Java</span>
  </input>
 </label>

<label for="inp-5" class="rc-label">
   <input type="checkbox" id="inp-5" name="inp">
  <span class="rc-text">Python</span>
  </input>
 </label>

<label for="inp-6" class="rc-label">
   <input type="checkbox" id="inp-6" name="inp">
  <span class="rc-text">JavaScript</span>
  </input>
 </label>

<label for="inp-7" class="rc-label">
   <input type="checkbox" id="inp-7" name="inp">
  <span class="rc-text">React</span>
  </input>
 </label>

<label for="inp-8" class="rc-label">
   <input type="checkbox" id="inp-8" name="inp">
  <span class="rc-text">HTML</span>
  </input>
 </label>

<label for="inp-9" class="rc-label">
   <input type="checkbox" id="inp-9" name="inp">
  <span class="rc-text">Solidity</span>
  </input>
 </label>

<label for="inp-10" id="inp-1" class="rc-label">
   <input type="checkbox" id="inp-10" name="inp">
  <span class="rc-text">Spring</span>
  </input>
 </label>
</div>  
</div>  
</form>
</body>

CSS

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");

body {
  font-family: 'Poppins', sans-serif;
  color: #fff;
}

/* Background */

.video-bg {
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

video {
  width: 100%;
  height: 100%;
  object-fit: cover;
 }

/* Header */

h1 {
  position: relative;
  font-family: 'Poppins', sans-serif;
  color: #fff;
  text-align: center;
  top: 0;
  font-size: 45px;
}

/* Form */

.form {
  max-width: 700px;
  margin: 50px auto; 
  background-color: rgba(16 18 27 / 30%);
  border-radius: 14px;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  padding: 30px 30px;
}

/* Form Items */

.form-control {
  text-align: left;
  margin-bottom: 25px;
  font-size: 1.1rem;
  letter-spacing: 0.4px;
  font-weight: 500;
}

.form-control label {
  display: block;
  margin-bottom: 15px;
}

.form-control input, 
.form-control select, 
.form-control textarea {
  background: rgba(16 18 27 / 35%);
  width: 97%;
  border: none;
  border-radius: 4px;
  padding: 10px;
  display: block;
  font-family: inherit;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0.1px;
  color: #fff;
  outline: none;
  box-shadow: 0 0 0 2px rgb(134 140 160 / 8%);
}

/* Dropdown Box */

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

select {
  width: 100% !important; 
  cursor: pointer;
  -webkit-appearance: none;
  appearance: none;
  z-index: 10;
  position: relative;
  background: transparent;
}

.options {
  position: relative;
  margin-bottom: 25px;
}

.options::after {
  content: ">";
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
  top: 6px;
  right: 15px;
  position: absolute;
  z-index: 0;
}

/* Radio Buttons & Checkboxes */

.form-control input[type="radio"],
.form-control input[type="checkbox"] {
  display: inline-block;
  width: auto;
}

.rc-label {
  border-radius: 100px;
  padding: 10px 10px;
  cursor: pointer;
  transition: .3s;
  flex: 1;
}

.rc-label:hover,
.rc-label:focus-within {
  background: hsla(0, 0%, 80%, .14);
}

.rc-text {
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0.1px;
}

/* Radio Buttons */

.rad-row {
  display: flex;
  margin-bottom: -20px;
}

/* Checkboxes */

.checkbox-row {
  display: flex;
}



mardi 23 novembre 2021

How to change states of Tkinter checkboxes when creating checkboxes with dictionary?

I'm making a program which gives the user a selection of checkboxes to select from. The checkboxes are being automatically created with a loop. I am able to detect which checkboxes have been ticked, but I'm unable to change the state of specific checkboxes by myself later on. Specifically, I want to remove all the ticks from the ticked checkboxes after a button is clicked, but more generally, I would like to know how to change the state of individual checkboxes. Here's a sample code:

import tkinter
from tkinter import *
tagsValue = {'Beef': 0, 'Fish': 0, 'Chicken': 0, 'Pork': 0, 'Lamb': 0, 'Egg': 0, 'Ham': 0}

def execute():
    my_text.delete('1.0', END)
    for tag in tagsValue:
        if tagsValue[tag].get() == '1':
            my_text.insert(INSERT, ('\n' + tag))

root = Tk()
root.title('User Selection')
root.geometry("300x300")
my_button = Button(root, text ="Submit",command = execute)
my_text = Text(root)

for tag in list(tagsValue):
    tagsValue[tag] = Variable()
    l = Checkbutton(root,justify=LEFT,width=8, text=tag, variable=tagsValue[tag])
    l.deselect()
    l.pack()

my_button.pack()
my_text.pack()
root.mainloop()

I have tried using things like tagsValue['Ham'] = '0' and tagsValue['Ham'] = 0 before root.mainloop() but those do not work. I am aware of using ['state'] to change the state of checkboxes, but since my checkboxes are not named, I can't use it. (I can't name the checkboxes individually because I have many many many checkboxes). So how can I change the state of the checkboxes?




Populate text box when checkbox is checked

I have a form with a Website text field and multiple (5-6) checkboxes. I need specific text to be populated into the Website field based on which checkbox has been selected.enter image description here




Refresh the state of checkboxes based on dropdown option : Angular

I have a dropdown list and few checkboxes. What is the best way to refresh the state (checked or unchecked) based on the selected option on the dropdown ?

For example, the checkboxes are few vehicles.

  • If I select "Cars" in the dropdown, only the checkboxes with value as any Car will get checked and rest will get unchecked.
  • If I select "Bikes" in the dropdown, the state of checkboxes gets refreshed and only the checkboxes with value as any Bike will get checked and rest will get unchecked.



Update automaticaly switch button on checked

I have issues in my project. In deed, I want to update automatically a switch button when I check it. The case that I have is that when I click on the switch button, the page is refresh but the value is not changed.

my code :

<div class="col-4 text-left">
     <form  id="form" class="was-validated" method="POST" action="" enctype="multipart/form-data">
     @method('PUT')
     @csrf
         <div style="float: right">
              <label class="switch">
                  <input type="checkbox" onchange="$('#form').submit();" name="cas_suivi" id="cas_suivi" type="checkbox"  >
                      <div class="slider"></div>
              </label>
          </div>
       </form>
     </div>



Get list of toggled checkboxes : Angular

I have a few checkboxes. Some of them are selected by default on the basis of data from the database. A user can unselect the selected checkboxes or select the unselected ones. Is there any way to get the list of only those checkbox values which were toggled(this list can be produced on the click of the button once the user finally decide which checkboxes are to be toggled) ?

<ul>
    <li *ngFor="let file of files">
       <input type="checkbox" ng-selected = "file.isPresent"> 
    </li>
</ul>


 <button (click)="getToggledCheckboxValues()"> Get Value </button>

If the file is present already then the checkbox will be checked by default.




lundi 22 novembre 2021

Check/uncheck input checkboxes in Isotope

I have a simple Isotope grid with checkbox inputs to sort the items in a grid. This works OK. The problem is the interaction between the "Show All" checkbox and the different category checkboxes.

When "Show All" is checked, I have to manually uncheck it to be able to check any category checkboxes. And when I uncheck all the categories, I'd like to have "Show all" check itself to indicate that all category items are being shown.

  1. How can I have "Show All" uncheck itself when any one or all of the categories are checked?

  2. How can I have "Show All" check itself when all of the categories are unchecked?

and

  1. How can I have "Show all" be checked on page load?

https://codepen.io/bluedogranch/pen/MWvdyNm

jQuery

var $container = $('#container').isotope({
    itemSelector: '.product',
    layoutMode: 'fitRows',
    transitionDuration: '0.2s'
  });
  
  var $checkboxes = $('#filters input');
  $checkboxes.change(function(){
    var filters = [];
    // get checked checkboxes values
    $checkboxes.filter(':checked').each(function(){
      filters.push( this.value );
    });
    filters = filters.join(', ');
    $container.isotope({ filter: filters });
  });

CSS

.product  {
float: left;
width: 50px;
height: 50px;
border: 1px solid #000;
padding:10px;
text-align:center;
margin: 5px;
}

#container {
width:400px;

HTML

<div id="filters">
<label><input type="checkbox" value="*"  id="all">Show all</a></li>
<label><input type="checkbox" value=".category1" id="category1">Category 1</label>
<label><input type="checkbox" value=".category2" id="category2">Category 2</label>
<label><input type="checkbox" value=".category3" id="category3">Category 3</label>
</div>

<div id="container">

<div class="product category1">1</div>

<div class="product category1 category2 ">1,2</div>

<div class="product category1 category3">1,3</div>

<div class="product category2">2</div>

<div class="product category2 category3">2,3</div>

<div class="product category3">3</div>

<div class="product category3 category2">3,2</div>

<div class="product category1">1</div>

<div class="product category2">2</div>

<div class="product category3">3</div>

<div class="product category2">2</div>

<div class="product category1">1</div>

</div>



when I save a dice and then unsave it, itl doesn't roll anymore even though there's no checkmark and not saved

So the game is Yahtzee, I should be able to roll the dice 3 times and save dice until the end, when I reset it, all my checks should disappear an I should be able to roll all dice again. I only did javascript for the dice[0]so for the first dice I haven't done it for the rest of the 4 other dice. I just want to save my first dice and then roll it and then when I uncheck it or reset it, It should roll it again but its not doing that. when I check and uncheck or reset it still thinks its checked and won't roll

<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script   src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous"></script>
  <style>
    body{
      background-color: #555555;
    }
    td {
      width: 30%;
      font-size: small;
    }
    .col-6{
      padding-bottom: 30px;
      padding-top: 25px;
      color: white;

    }
    .col-6 span{
      color: black;
      padding-right: 20px;
    }
    .resTable span{
      padding-left: 20px;
    }
    .resTable{
      border-style: solid;
      border-color: black;
      border-width: thin;
    }
    h1 {
      margin-bottom: -20px;
    }
    h1{
      font-family: Papyrus;
      font-size: 45px;
    }
    li a {
      margin-top: 40px;
      margin-left: 20px;
    }


  </style>
  <script>
    let dice = [
      {'img': 'Die1.PNG', 'value': 1},
      {'img': 'Die2.PNG', 'value': 2},
      {'img': 'Die3.PNG', 'value': 3},
      {'img': 'Die4.PNG', 'value': 4},
      {'img': 'Die5.PNG', 'value': 5},
      {'img': 'Die6.PNG', 'value': 6}
    ]
    let userDice =[
      {'dice': 0, 'checked': false, 'id': "d1"},
      {'dice': 0, 'checked': false, 'id': "d2"},
      {'dice': 0, 'checked': false, 'id': "d3"},
      {'dice': 0, 'checked': false, 'id': "d4"},
      {'dice': 0, 'checked': false, 'id': "d5"},
    ]
    var turns = 9;
    var rollsLeft = 3;
    var wins =0;
    var losses = 0;
    const WINPOINTS=200;
    function user(){
      // document.getElementById("name").innerHTML= prompt("Enter your name");
    }
    function rollDice() {
      if (rollsLeft > 0) {
        for (let i = 0; i < userDice.length; i++) {
          if (userDice[i].checked == false)
          {
            let rDie = Math.floor(Math.random() * 6);
            document.getElementById(userDice[i].id).innerHTML = `<img src ="imgs/${dice[rDie].img}" height='50px' width='50px'> `;
            //userDice[i].value = dice[rDie].value;  //WHAT DOES THIS DO???
          }
        }
        rollsLeft--;
        var display = document.getElementById("rollsLeft")
        display.innerHTML = rollsLeft;

      } else {
        alert("u gotta do somethin else")
        for(let j = 0; j < userDice.length; j++)
        {
          // userDice[j].checked = false;
          // rollsLeft = 3;
        }
      }
    }
    // let wins = document.getElementById("wins");
    // let losses = document.getElementById("losses");
    // if(wins > WINPOINTS){
    //   wins++
    // }else {
    //   losses++
    // }
    $( document ).ready(function() {
      resetThings();
      console.log( "yo im ready!" );
    //
    //==   $("#rollBtn").click(function() {
    //     rollsLeft--;
    //     var display = document.getElementById("rollsLeft")
    //     display.innerHTML = rollsLeft;
    //     var checkedItems =[];
    //     if (rollsLeft === 0) {
    //       alert("no more clicking")
    //       rollsLeft=3
    //       return;
    //     }else{
    //       checkedItems = $('input[name="diceCheck"]:checked' );
    //
    //       setMyDice( checkedItems );
    //       displayDice();
    //       console.log(`check${checkedItems}`)
    //     }
    //
    //   //=======================================
      function resetThings(){
        rollDice();
      }

      $("#reset").click(function() {
        alert("reset this");
        rollsLeft=3;
        var display = document.getElementById("rollsLeft")
        display.innerHTML = rollsLeft;
        rollDice();
        $('input[type=checkbox]:checked').each(function(){
          $(this).prop('checked', false);
        });
      })

      $("#d1Check").click(function() {
        if(userDice[0].checked){
          userDice[0].checked= false;
        } else {
          userDice[0].checked= true;
        }
        })
      })

  </script>
  <title>Hello, world!</title>
</head>
<body onload="user()">
<div class ="container-fluid">
  <header class=" mb-4 border-bottom border-dark">
    <div class="row">
      <div class="col-5">
        <ul class="nav nav-pills">
          <li class="nav-item">
            <a href="https://usbrandcolors.com/apple-colors/" class="nav-link active link-dark bg-dark text-light">Color</a>
          </li>
        </ul>
      </div>
      <div class="col-6">
        <h1><span>Dark</span><img src="imgs/543598.png" width="180"height="80"></h1>
      </div>
    </div>
  </header>
  <div class="row">
    <div class="col">
      <div class="col-9">
        PLAYERS NAME: <span id="name"></span>
      </div>
      <br>
      <br>
      <table class="resTable table-bordered">
        <tbody>
        <tr>
          <th scope="row">Win points</th>
          <td><span id="200">200</span></td>
        </tr>
        <tr>
          <th scope="row">Wins</th>
          <td><span id="wins">0</span></td>
        </tr>
        <tr>
          <th scope="row">Losses</th>
          <td><span id="losses">0</span></td>
        </tr>
        </tbody>
      </table>
    </div>
    <div class="col-4">
      <table class="table table-bordered border-dark border border-2 table-sm">
        <caption>* if total score is 62 or over <br>** of upper section</caption>
        <thead>
        <tr>
          <th scope="col">UPPER <br>SECTION</th>
          <th scope="col">HOW TO <br>SCORE</th>
          <th scope="col">GAME <br>#1</th>
        </tr>
        </thead>
        <tbody>
        <tr>
          <th scope="row">ACE <img src="imgs/Die1.PNG" width="40"height="38" > =1</th>
          <td>Count and <br> add only <br>ACES</td>
          <td><div id="ace1"></div></td>
        </tr>
        <tr>
          <th scope="row">TWOS <img src="imgs/Die2.PNG" width="40"height="38" > =2</th>
          <td>Count and <br> add only <br>TWOS</td>
          <td><div id="twos1"></div></td>
        </tr>
        <tr>
          <th scope="row">THREES <img src="imgs/Die3.PNG" width="40"height="38" > =3</th>
          <td>Count and <br> add only <br>THREES</td>
          <td><div id="threes1"></div></td>
        </tr>
        <tr>
          <th scope="row">FOURS <img src="imgs/Die4.PNG" width="40"height="38" > =4</th>
          <td>Count and <br> add only <br>FOURS</td>
          <td><div id="fours1"></div></td>
        </tr>
        <tr>
          <th scope="row">FIVES <img src="imgs/Die5.PNG" width="40"height="38" > =5</th>
          <td>Count and <br> add only <br>FIVES</td>
          <td><div id="five1"></div></td>
        </tr>
        <tr>
          <th scope="row">SIXES <img src="imgs/Die6.PNG" width="40"height="38" > =6</th>
          <td>Count and <br> add only <br>SIXES</td>
          <td><div id="sixes1"></div></td>
        </tr>
        <tr>
          <th scope="row">3 of a kind</th>
          <td>Add total <br> of all dice</td>
          <td></td>
        </tr>
        <tr>
          <th scope="row">4 of a kind</th>
          <td>Add total <br> of all dice</td>
          <td></td>
        </tr>
        <tr>
          <th scope="row">FULL HOUSE</th>
          <td>Score 25</td>
          <td></td>
        </tr>
        <tr>
          <th scope="row"><b>TOTAL SCORE</b></th>
          <td> <img src="imgs/arrow.png" width="60" height="30"></td>
          <td></td>
        </tr>
        <tr>
          <th scope="row"><b>BONUS*</b></th>
          <td>Add total <br> of all dice</td>
          <td></td>
        </tr>
        <tr>
          <th scope="row"><b>TOTAL**</b></th>
          <td> <img src="imgs/arrow.png" width="60" height="30"> </td>
          <td></td>
        </tr>

        </tbody>
      </table>
    </div>
    <div class="col-4">
      <h3>Your Dice</h3>
      <form id="shuffle">
        <button type="button" class="btn btn-dark" id="rollBtn" onclick="rollDice();">Roll</button>
        <button type="button" class="btn btn-dark" id="reset">Reset</button>
        <p>Rolls left: <span id="rollsLeft">2</span></p>
      </form>
      <table class="table table-borderless table-sm table-hover ">
        <tr> <td> Save: <input type="checkbox" name='diceCheck' id="d1Check" /> </input> </td>
          <td id="d1"> <img src="imgs/Die1.PNG" height="50" width="50"> </td>
        </tr>
        <tr>  <td> Save: <input type="checkbox" name="diceCheck" id="d2Check" /> </input> </td>
          <td id="d2"><img src="imgs/Die2.PNG" height="50" width="50"> </td>
        </tr>
        <tr> <td> Save: <input type="checkbox" name="diceCheck" id="d3Check"/> </input> </td>
          <td id="d3"> <img src="imgs/Die3.PNG" height="50" width="50"></td>
        </tr>
        <tr> <td> Save: <input type="checkbox" name="diceCheck" id="d4Check"/> </input> </td>
          <td id="d4"> <img src="imgs/Die4.PNG" height="50" width="50"></td>
        </tr>
        <tr> <td> Save: <input type="checkbox" name="diceCheck" id="d5Check"/> </input> </td>
          <td id="d5"> <img src="imgs/Die5.PNG" height="50" width="50"></td>
        </tr>
      </table>
      <br>
      <br>
    </div>
  </div>
</div>
<!-- Optional JavaScript; choose one of the two! -->

<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>



dimanche 21 novembre 2021

limit number of checks for groups of checkboxes selected in angular

I am building Angular Website. I have data coming from server which contains info about options and sub options

the data from server

in my html

 <div class="radiobox" *ngFor="let mainOption of data.cartItem.option[0].options">
          <h5 class="text-left" style="font-size: 16px;color: #4c5156;"></h5>
          <!-- <h6 class="text-left" style="font-size: 13px;color: #4c5156;">Choose Upto: </h6> -->
          <h6 class="text-left" style="font-size: 13px;color: #4c5156;">Choose Upto: </h6>
          <div class="row" style="flex-direction: column;margin: 0;">
            <div class="col-md-4" *ngFor="let option of mainOption.suboptions, let i = index " style="padding: 0;width: 100%;">
              <div class="row" style="margin: 0;">
                <div class="changed p-0" style="width: 15px;place-self: center;">
                  <input type="checkbox" class="float-right form-check-input position-static"
                    name=""  [value]='option' [(ngModel)]="option[i]"
                    (ngModelChange)='changeEventInRadioButton($event)' style="margin: 0;">
                </div>
                <div class="col-8 p-2">
                  <div class="float-left">
                    <span class="inputdisplay"> </span>
                    <br>
                    <span class="inputdisplay1" style="font-size: 14px;">+ </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

It creates multiple groups of checkboxes. in each group I need the user to be able to select limited number of options. which are present in mainOption.max

how is this possible for me to make this work?

Thanks!




How to display a textfield value in other textfield when checkbox is checked in flutter using ListTile

I created a textfield named chargesMax and add a ListTile widget which contains checkbox and two textfield named charges and time. I want when user enter some value on chargesMax textfield and then check any checkbox then charges textfield should contain the value of chargesMax textfield. and then if user modify then charges textfield then only this field will modify not all the textfield of listTile.

here is my code

charges.text = chargesMax.text;

In this above line i'm trying to do what i want but when i check the checkbox of any listTile, value of chargesMax display to charges textfield but all textfield of checkbox modify on check on any checkbox. wherease, i can check the checkbox indiviually.

Full code:


void _onCitySelected(bool selected, cityId) {
    if (selected == true) {
      setState(() {
        charges.text = chargesMax.text;  
        _selectedCities.add(cityId);
        print(_selectedCities);
      });
    } else {
      setState(() {
        _selectedCities.remove(cityId);
      });
    }
  }
Widget build(BuildContext context) {
    return SafeArea(
        child: Container(
        child: Column(
              children: [
                    //chargesMax textfield
                    textformfieldCustomwithouticon(
                    context,
                    TextInputType.number,
                    MediaQuery.of(context).size.width * 0.9,
                    chargesMax, (String value) {
                  setState(() {
                    chargesMax.text = value;

                    chargesMax.selection = TextSelection.fromPosition(
                        TextPosition(offset: chargesMax.text.length));
                  });
                }, (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                }, 'Enter delivery charges for maximumn destination',
                    'Delivery charges', 55.0),
                
                   SizedBox(
                                height:
                                    MediaQuery.of(context).size.height * 0.6,
                                child: ListView.builder(
                                    itemCount: books.length,
                                    itemBuilder: (context, index) {
                                      final book = books[index];
                                      if (isLoading) {
                                        return showCircularLoader(context);
                                      } else {
                                        return Padding(
                                          padding: const EdgeInsets.fromLTRB(
                                              0, 10, 0, 0),
                                          child: Column(
                                            children: [
                                              buildCitesList(book),
                                              SizedBox10(),
                                              Divider(),
                                              SizedBox10()
                                            ],
                                          ),
                                        );

                                        //
                                      }
                                    }),
                              ),


Widget buildCitesList(Book book) => ListTile(
        leading: checkboxCustom(context, _selectedCities.contains(book.id),
            (bool? selected) {
          if (selected != null) {
            setState(() {
              _onCitySelected(selected, book.id);
            });
          }
        }),
        title: Text(book.title, style: GoogleFonts.montserrat()),
        subtitle: Padding(
          padding: const EdgeInsets.only(top: 10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
             
              //charges textfield
              textformfieldCustomwithouticon1(
                  context,
                  TextInputType.number,
                  MediaQuery.of(context).size.width * 0.3,
                  charges, (String value) {
                setState(() {
                  charges.text = value;
                  charges.selection = TextSelection.fromPosition(
                      TextPosition(offset: charges.text.length));
                });
              }, (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              }, 'Charges', 'Charges', 10.0),
              SizedBox(
                width: 10,
              ),
              textformfieldCustomwithouticon1(
                  context,
                  TextInputType.number,
                  MediaQuery.of(context).size.width * 0.3,
                  time, (String value) {
                setState(() {
                  time.text = value;
                  time.selection = TextSelection.fromPosition(
                      TextPosition(offset: time.text.length));
                });
              }, (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              }, 'Time', 'Time', 10.0),
              // SizedBox10(),
            ],
          ),
        ),
      );

here is the snap of output

enter image description here

please help how i can do this.