samedi 30 avril 2022

Bootstrap Treeview relation between (parent or child ... ) and checkbox : how set item checkbox when i click on element span which have this checkbox?

I added checkboxes to my treeview, but there is no relationship between the node (parent or child...) and the added checkbox

I want when I click on the node or at the input I checked checkbox and I open the list of children of this node at the same time,

and if I click again on the node (parent or child ...) or input I uncheck input and I close the list of children of this node

Here is my code

$(function () {
    $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
     var extra = $(".tree li.parent_li > span")
    .parent("li.parent_li")
    .find(" > ul > li");
  extra.hide("fast");
    
    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide('fast');
            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }
        e.stopPropagation();
    });
});
.tree {
    min-height:20px;
    padding:19px;
    margin-bottom:20px;
    background-color:#fbfbfb;
    border:1px solid #999;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);
    -moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);
    box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05)
}
.tree li {
    list-style-type:none;
    margin:0;
    padding:10px 5px 0 5px;
    position:relative
}
.tree li::before, .tree li::after {
    content:'';
    left:-20px;
    position:absolute;
    right:auto
}
.tree li::before {
    border-left:1px solid #999;
    bottom:50px;
    height:100%;
    top:0;
    width:1px
}
.tree li::after {
    border-top:1px solid #999;
    height:20px;
    top:25px;
    width:25px
}
.tree li span {
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    border:1px solid #999;
    border-radius:5px;
    display:inline-block;
    padding:3px 8px;
    text-decoration:none
}
.tree li.parent_li>span {
    cursor:pointer
}
.tree>ul>li::before, .tree>ul>li::after {
    border:0
}
.tree li:last-child::before {
    height:30px
}
.tree li.parent_li>span:hover, .tree li.parent_li>span:hover+ul li span {
    background:#eee;
    border:1px solid #94a0b4;
    color:#000
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" id="theme" rel="stylesheet">
<div class="tree well">
    <ul>
        <li>
            <span>  <input type="checkbox" id="test1" name="test1">  Parent</span> 
            <ul>
                <li>
                    <span><input type="checkbox" id="test2" name="test2"> Child</span> 
                    <ul>
                        <li>
                            <span><input type="checkbox" id="test3" name="test3"> Grand Child</span> 
                          <ul>
                        <li>
                            <span><input type="checkbox" id="test3" name="test3"> Grand Grand Child</span> 
                           <ul>
                        <li>
                            <span><input type="checkbox" id="test3" name="test3"> Grand Grand Grand Child</span> 
                        </li>
                    </ul>
                        </li>
                    </ul>
                        </li>
                    </ul>
                </li>
                <li>
                    <span><input type="checkbox" id="test4" name="test4"> Child</span> 
                    <ul>
                        <li>
                            <span><input type="checkbox" id="test4" name="test4"> Grand Child</span> 
                        </li>
                        <li>
                            <span><input type="checkbox" id="test5" name="test5">Grand Child</span> 
                            <ul>
                                <li>
                                    <span><input type="checkbox" id="test6" name="test6"> Great Grand Child</span> 
                                    <ul>
                                        <li>
                                            <span><input type="checkbox" id="test7" name="test7">Great great Grand Child</span> 
                                        </li>
                                        <li>
                                            <span><input type="checkbox" id="test8" name="test8"> Great great Grand Child</span> 
                                        </li>
                                     </ul>
                                </li>
                                <li>
                                    <span><input type="checkbox" id="test9" name="test9">Great Grand Child</span> 
                                </li>
                                <li>
                                    <span><input type="checkbox" id="test10" name="test10"> Great Grand Child</span> 
                                </li>
                            </ul>
                        </li>
                        <li>
                            <span><input type="checkbox" id="test11" name="test11"> Grand Child</span> 
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
        <li>
            <span><input type="checkbox" id="test12" name="test12"> Parent2</span> 
            <ul>
                <li>
                    <span><input type="checkbox" id="test13" name="test13"> Child</span> 
                </li>
            </ul>
        </li>
    </ul>
</div>

Here's a JSFiddle link :https://jsfiddle.net/daizdev/q5hwg0yj/13/




vendredi 29 avril 2022

PHP: Update database with checkbox values for each row

I'm currently working on displaying a table, containing a list of alarms, where each row contains a checkbox that determines whether the user has already viewed that alarm or not. Here's an image:

So far, I managed to check/uncheck the chekbox given it's state in the database. What I want to do, and don't exactly know how to, is to be able for the user to check/uncheck a checkbox and inmediatly update the database with this new state, without having to press a submit button. The code that i have right now is the following:

<div class="card-body table-responsive p-0">
  <form action=modules/alarms.php method="POST">
    <table class="table table-bordered table-hover">
      <thead>
        <tr>
          <th>ID</th>
          <th>Tipus</th>
          <th>Data</th>
          <th>Vista</th>
        </tr>
      </thead>
       <tbody> 
         <?php 
           foreach ($result->fetchAll() as $row){
             if ($row[4] == 1){
                 $status = "checked";
             }else{
                 $status = "";
             }
            echo 
             '<tr data-widget="expandable-table" aria-expanded="false">
                <td>'.$row[0].'</td> 
                <td>'.$row[1].'</td> 
                <td>'.$row[2].'</td>
                 <td><input type="checkbox" name="chk1[]" value="viewed" '.$status.'></td>
               </tr>
               <tr class="expandable-body">
                 <td colspan="5">
                    <p>
                      <video width="416" height="416" controls>
                       <!-- el 42 es la cabecera C:/... fins videos-->
                       <source src="'.substr($row[3], 42).'" type="video/mp4">
                       Your browser does not support the video tag.
                      </video>
                     </p>
                  </td>
                </tr>';
                      }                      
       ?>                                                                         
  </tbody>
</table>

And the php code I have (I don't have yet the code that will update values on the database, but I'll figure that out.

 <?php 
  $ei = $_POST['chk1'] ;  
  if ($_POST["chk1" ]=="chk1") {  
    for ($i=0; $i<sizeof ($checkbox1);$i++) {  
     print_r($checkboxl[$i]);     
    }  
  }  
?>

I want to know how could I retrieve the value of the checkbox of every row, and it's ID so I can update it on the database. Thanks for any help.




Gender radio input and fields of interest checkbox undefined in alerts

Can anyone help me why the gender and fields of interest output are undefined? I can't seem to get it no matter how I get the value and its getting out of hand

HTML:

<form id="theForm" onsubmit="theSubmit()">
    <div id="theGender">
        <label for="theGender">Gender:</label>
        <input type="radio" name="gender" value="Male"><a>Male</a>
        <input type="radio" name="gender" value="Female"><a>Female</a>
        <input type="radio" name="gender" value="Others"><a>Others</a>
        <input type="radio" name="gender" value="Prefer not to say"><a>Prefer not to say</a>
    </div>
    <div id="fieldsOfInterest">
        <label for="fieldsOfInterest">Fields Of Interest:</label>
        <input type="checkbox" name="fieldsOfInterest" id="architectureEngineering" value="Architecture/Engineering">
        <label for="fieldsOfInterest">Architecture/Engineering</label>
        <input type="checkbox" name="fieldsOfInterest" id="computerScience" value="Computer Science">
        <label for="fieldsOfInterest">Computer Science</label>
        <label for="fieldsOfInterest">Environmental Sustainability</label>
        <input type="checkbox" name="fieldsOfInterest" id="interestOther" value="Other">
        <label for="fieldsOfInterest">Others</label>
    </div>
    <input type="submit" value="Submit" onclick="theSubmit()" name="submit">
    <input type="reset" value="Reset" name="reset">
</form>

Script:

    function theSubmit() {
        if(theMale.checked){
            theGender = "Male"
        }else if(theFemale.checked){
            theGender = "Female"
        }else if(theOther.checked){
            theGender = "Other"
        }else if(thePreferNotToSay.checked){
            theGender = "Prefer Not To Say"
        }
        if(architectureEngineering.checked){
            fieldsOfInterest += "Architecture/Engineering"
        }else if(computerScience.checked){
            fieldsOfInterest += "Computer Science"
        }else if(interestOther.checked){
            fieldsOfInterest += "Others"
        }
        alert("This is the information that is filled out:\nName: "+firstName.value+" "+middleName.value+" "+lastName.value+"\nBirthday: "+birthDay.value+"\nGender: "+theGender.value+"\nCivil Status: "+civilStatus.value+"\nComplete Address: "+completeAddress.value+"\nContact Number: "+contactNumber.value+contactNumberInput.value+"\nFields Of Interest: "+fieldsOfInterest.value);
    }



jeudi 28 avril 2022

Jquery to allow checkbox after checking a condition?

I have 3 checkboxes like this

by default 3 checkboxes are False Now my requirement is that Both option is allowed to be True only when both First and Second option is true if any of them is false then both option should be unchecked i.e., false

I wanted to acheciver this with Jquery

so my jquery is:

    <input id="#first" type="checkbox" asp-for="first" /> 
    <input id="#second" type="checkbox" asp-for="second" /> 
    <input id="#both" type="checkbox" asp-for="both" /> 
        <script>
                function change() {
                    var firstArg = ($("#first").prop('checked')==true);
                    var secondArg = ($("#second").prop('checked') == true);
                    console.log("---" + firstArg + "------" + secondArg);
                    if (!(firstArg && secondArg))
                    {
                        $("both").prop("disabled", false);
                    }
                }
    function activate() 
{
    change();
    $("#first").bind('change', change());
    $("#second").bind('change', change());
    $("#change").bind('change', change());
    
    }
    
    </script>

But it is not working, can someone please help me with this?




Google AppScript - Update input checkbox following sheet value - partialy working

Please, I am requesting your help to finish a sidebar with a form in GSheet.

Actual statut :
Update Value with submited checkbox by sidebar form (50 checkbox) = 100% working
Checkbox "checked" at sidebar open if value = 1 : All working fine for 4 checkbox, but not working for 5 and more = 50%

Please Help requested :
Check code if it can be cleaned with : while loop or something like that
And the most important, make the checkbox "checked" value working for around 50 checkbox

Please find the Script code in HTML file :

<script>   
google.script.run.withSuccessHandler(function(returnCheck1) {
    document.getElementById("check1").innerHTML = returnCheck1;
    if (document.getElementById("check1").innerHTML=="checked"){document.getElementById("cbA1").checked = true;}
    }).getOneCellData();
google.script.run.withSuccessHandler(function(returnCheck2) {
    document.getElementById("check2").innerHTML = returnCheck2;
    if (document.getElementById("check2").innerHTML=="checked"){document.getElementById("cbA2").checked = true;}
    }).getOneCellData();
google.script.run.withSuccessHandler(function(returnCheck3) {
    document.getElementById("check3").innerHTML = returnCheck3;
    if (document.getElementById("check3").innerHTML=="checked"){document.getElementById("cbA3").checked = true;}
    }).getOneCellData();
google.script.run.withSuccessHandler(function(returnCheck4) {
    document.getElementById("check4").innerHTML = returnCheck4;
    if (document.getElementById("check4").innerHTML=="checked"){document.getElementById("cbA4").checked = true;}
    }).getOneCellData();
google.script.run.withSuccessHandler(function(returnCheck5) {
    document.getElementById("check5").innerHTML = returnCheck5;
    if (document.getElementById("check5").innerHTML=="checked"){document.getElementById("cbA5").checked = true;}
    }).getOneCellData();
google.script.run.withSuccessHandler(function(returnCheck6) {
    document.getElementById("check6").innerHTML = returnCheck6;
    if (document.getElementById("check6").innerHTML=="checked"){document.getElementById("cbA5a").checked = true;}
    }).getOneCellData();

<!-- Up to 50 checkbox -->

function submitForm() {
      google.script.run.appendRowFromPART1Submit(document.getElementById("formulaire"));
      document.getElementById("form").style.display = "none";
      document.getElementById("thanks").style.display = "block";
}
</script>

Please find the HTML code :

<body>
  <div id="form">
    <form id="formulaire">      
    <input type="button" id="form" name="form" value="Save" onclick="submitForm();">
    <p><b>Title</b></p><br>

<input type="checkbox" id="cbA1" name="cbA1" value="1">
      <label for="A1">A1 - </label><textarea id="check1" style="display: none;"></textarea><hr>
<input type="checkbox" id="cbA2" name="cbA2" value="1">
      <label for="A2">A2 - </label><textarea id="check2" style="display: none;"></textarea><hr>
<input type="checkbox" id="cbA3" name="cbA3" value="1">
      <label for="A3">A3 - </label><textarea id="check3" style="display: none;"></textarea><hr>
<input type="checkbox" id="cbA4" name="cbA4" value="1">
      <label for="A4">A4 - </label><textarea id="check4" style="display: none;"></textarea><hr>
<input type="checkbox" id="cbA5" name="cbA5" value="1">
      <label for="A5">A5 - </label><textarea id="check5" style="display: none;"></textarea><hr>
<input type="checkbox" id="cbA5a" name="cbA5a" value="1">
      <label for="A5a">A5a - </label><textarea id="check6" style="display: none;"></textarea><hr>

<!-- Up to 50 checkbox -->

    </form>
  </div>
  <div id="thanks" style="display: none;"><br>Thanks.</div>
</body>

Please find the Apps Script code :

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('=> Menu <=')
    .addItem('Suivi', 'suivi')
    .addToUi();
}

function suivi() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName('Valeurs');
  //var sheet = SpreadsheetApp.getActiveSheet();

  var html = HtmlService.createHtmlOutputFromFile('suivi').setTitle('Suivi');
  SpreadsheetApp.getUi().showSidebar(html);
}

function getOneCellData() { 
  var ss= SpreadsheetApp.getActiveSpreadsheet();
  var sheetss = ss.getSheetByName("Valeurs"); 

var data1 = sheetss.getRange("H1").getValue(); 
  if (data1 == "1") {    check1 = "checked"; } else {    check1 =""; }
var data2 = sheetss.getRange("H2").getValue(); 
  if (data2 == "1") {    check2 = "checked"; } else {    check2 =""; }
var data3 = sheetss.getRange("H3").getValue(); 
  if (data3 == "1") {    check3 = "checked"; } else {    check3 =""; }
var data4 = sheetss.getRange("H4").getValue(); 
  if (data4 == "1") {    check4 = "checked"; } else {    check4 =""; }
var data5 = sheetss.getRange("H5").getValue(); 
  if (data5 == "1") {    check5 = "checked"; } else {    check5 =""; }
var data6 = sheetss.getRange("H6").getValue(); 
   if (data6 == "1") {    check6 = "checked"; } else {   check6 =""; }

// Up to 50 again

return check1,check2,check3,check4,check5,check6;
// Up to 50 again
}

function appendRowFromPART1Submit(form) {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet2 = spreadsheet.getSheetByName('Valeurs');
  
  // DATA FORM
  var email = Session.getActiveUser().getEmail();

if (form.cbA1 != "1"){var rowcbA1 = "0";}else{var rowcbA1 = form.cbA1;}
  var data1 = sheet2.getRange("H1").getValue(); 
  if (data1 != rowcbA1) {sheet2.getRange("I1").setValue(email);}
  sheet2.getRange("H1").setValue(rowcbA1);
if (form.cbA2 != "1"){var rowcbA2 = "0";}else{var rowcbA2 = form.cbA2;}
  var data2 = sheet2.getRange("H2").getValue(); 
  if (data2 != rowcbA2) {sheet2.getRange("I2").setValue(email);}
  sheet2.getRange("H2").setValue(rowcbA2);
if (form.cbA3 != "1"){var rowcbA3 = "0";}else{var rowcbA3 = form.cbA3;}
  var data3 = sheet2.getRange("H3").getValue(); 
  if (data3 != rowcbA3) {sheet2.getRange("I3").setValue(email);}
  sheet2.getRange("H3").setValue(rowcbA3);
if (form.cbA4 != "1"){var rowcbA4 = "0";}else{var rowcbA4 = form.cbA4;}
  var data4 = sheet2.getRange("H4").getValue(); 
  if (data4 != rowcbA4) {sheet2.getRange("I4").setValue(email);}
  sheet2.getRange("H4").setValue(rowcbA4);
if (form.cbA5 != "1"){var rowcbA5 = "0";}else{var rowcbA5 = form.cbA5;}
  var data5 = sheet2.getRange("H5").getValue(); 
  if (data5 != rowcbA5) {sheet2.getRange("I5").setValue(email);}
  sheet2.getRange("H5").setValue(rowcbA5);
if (form.cbA5a != "1"){var rowcbA5a = "0";}else{var rowcbA5a = form.cbA5a;}
  var data6 = sheet2.getRange("H6").getValue(); 
  if (data6 != rowcbA5a) {sheet2.getRange("I6").setValue(email);}

// Up to 50 again


All this come from my searchs and been adapted for this project.
I not get so much knowledge on script, some in HTML and PHP to help get the logic of coding.


Thanks a lot for your time and help !!




Symfony form with check box conditional

I want to create a form in symfony with a double checkbox, in mode You approve the privacy policy or you don't approve the privacy policy.

[]I approve the privacy policy [] I do not approve the privacy policy

The doubt that arises is that one of them will be marked dynamically only if the answer to a query is a value a or another (For example a boolean) (So I think it should be relational), in plan: 1 to approve and 0 to not approve, but previously made the query to generate the form.

How can I do it?




mercredi 27 avril 2022

Hidden checkbox required to be checked even when hidden

I’m kinda of stuck.

I’m using html5 required for a very simple validation, and I have a checkbox that only shows up if you meet some conditions. You then have to agree with terms and check the checkbox.

The problem is when you don’t hit conditions and checkbox reminds hidden then its not posible to submit. It should only be required if you see it.

.terms{
display: none;
}

<form>

<p><input class="terms" type="checkbox" id="checkId" required>Terms & Conditions</p>
<input type="submit" name="submit" value="Submit" id="submit" />

</form>



When checking the checkbox terms_accepted doesn't change to true

Hey so I have a problem it is probably a very simple thing that I am missing...

So I have a checkbox that a user must tick in order to signup. And when checking the box terms_accepted is not changed to true... anyone got a clue?

here is the migration I made to user:

class AddTermsAcceptedToUsers < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :terms_accepted, :boolean, :default => false
  end
end

This is the validations in user.rb:

  validates :terms_accepted, acceptance: true

this is the simple_form for the checkbox:

  <%= f.check_box :terms_accepted,
                  required: true%>
  <%= label_tag(:owner, "I accept all terms and conditions by checking this box ") %>



mardi 26 avril 2022

Angular- Checkbox using reactive form

I have recently started using reactive forms. I was making 3 checkboxes with value 3 different values. Here in the 3rd checkbox, there is a select all selecting which should select all the checkboxes. I tried this one TS code:

  formData: FormGroup;
  gender: Gender[] = [
    {
      type: 'Male',
      value: '1',
    },
    {
      type: 'Female',
      value: '0',
    },
    {
      type: 'All gender',
      value: '5',
    },
  ];

  constructor() {
    this.formData = new FormGroup({
      gender_Form: new FormControl(''),
    });
  }

  ngOnInit() {
    //console.log('formData =>', this.formData);
  }

  genderSelection(data: any) {
    //console.log('data =>', data);
    console.log('checkbox =>', data.checked);
    console.log('value =>', data.value);
    const control = this.formData.controls['gender_Form'];
    if (data.value == '5') {
      control.setValue(
        this.gender.map((i) => {
          console.log('selected =>', i);
          i.type;
        })
      );
      console.log('gender =>', control);
    }
  }

HTML code:

  <div [formGroup]="formData" *ngFor="let data of gender">
  <input
    class="form-check-input"
    formControlName="gender_Form"
    type="checkbox"
    id="checkBox_"
    value=""
  />
  <label class="form-check-label" for="checkBox"></label>
  </div>

Here, even though selecting the select all checkbox, do ticks the rest of the boxes I was unable to see the values when I console logged console.log('gender =>', control);. Thanks for the help in advance




How to set checkboxes group with JS, created with PHP [closed]

I'm not sure how to best phrase my question, but here's my problem.

I have an HTML table dynamically created with PHP based on records from a MySQL database. So far, no worries,

In MySQL, each row of this table is linked to another table containing "status".

For example:

Row 1: Chkgrp 1 : Chk 1 = 1, Chk 2 = 0 , Chkgrp 2 : Chk 1 = 1, Chk 2 = 0 etc...

Row 2: Chkgrp 1 Chk 1 = 1, Chk 2 = 1 , Chkgrp 2 : Chk 1 = 1, Value 2 = 0 etc...

Row 2: Chkgrp 1 Chk 0 = 1, Chk 2 = 0 , Chkgrp 2 : Chk 1 = 1, Value 2 = 0 etc...

Etc..

To better express this, here is an image :

Demo

In this example, Row 2 is selected, and below the table, the corresponding checkboxes. If I click on Row 3, I will see below the state of the checkboxes for row 3 etc...

The number of checkbox groups is dynamic based on MySQL records, but for each group, only two checkboxes. I need to be able to modify the value of the checkboxes and to save with a button

I am able to do this, but I don't know how to make it dynamic on a single page, without reloading all the data each time If you have any ideas, could you direct me to the best way to achieve this result?

I'm not asking for complete code, but ideas or suggestions to achieve this.

Thank you for your help




lundi 25 avril 2022

How do I link my first check box with the appropriate row

I'm attempting to write a vba that automatically links checkboxes to the appropriate rows. I wrote the following

Sub LinkChecklist()

Dim chk As CheckBox

For Each chk In ActiveSheet.CheckBoxes
    chk.LinkedCell = chk.TopLeftCell.Offset(0, 1).Address
Next

End Sub

however when I run the code, the first checkbox which starts on row 2 col F, links to row 1 col G when it should be linking to row 2. This makes it so that some of the checkboxes below it link to the wrong cells also. Any tips on how to resolve that issue?

Also, would appreciate any tips on making sure that each row contains only one check box. As you can see in the image, the more text there is in a cell, the more the checkboxes get messed up. Is there any way to make it so that each row, no matter how large or small it gets, contains only one checkbox?

Thanks

image of checkboxes




dimanche 24 avril 2022

How to create a trigger to store data from two columns: trigger on completing a checkbox checklist

new to code and most of what I have, is copied from a mix of code found online. Apologies if it's messy and please explain simply as possible (:

I'm trying to (onEdit)trigger a function saveData that will move the comment section in A9, generating a timestamp in B9 and then moving both values from A9 and B9 and storing them 2 rows lower. The aim is to be able to check the "tasks" each week and write any comments and then completing the checklist will trigger storing that information in a lower row that then appends the values each time its completed.

Grateful for any direction / suggestions.

Screenshot of spreadsheet ¬

function onEdit(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var activeCell = ss.getActiveCell();      
  if( activeCell.getRow() == 7)
  if( activeCell.getColumn() == 3) {         
    saveData();    
 }

function saveData() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheets()[0];
  const comments = sheet.getRange('Sheet1!A9').getValue();
  const timestamp = sheet.getRange('Sheet1!B9').getValue(); 
  sheet.appendRow([comments,timestamp]); }

}



Toggle class based on cookie and on toggle checkbox

I set a cookie successfully in the browser, so that the cookie returned the cookie value true when checked, and false when unchecked. This cookie changes back and forth on every click of the checkbox.

Here's what I need to do:

  1. On page load, it reads cookie, and if cookie value is true then it runs addClass. If cookie is false, then it runs removeClass.
  2. If the checkbox is manually checked, it runs addClass.
  3. If the checkbox is manually unchecked, it runs removeClass.
  4. When it is toggled, it needs to run the add or remove class immediately, not wait until after page load.

Here's what I have, and no errors in console. It's working now, but there's a lag after the page load. How can I fix it to remove the lag?

var mytoggle = $.cookie('checkboxValue'); // gets the value saved
if(mytoggle && mytoggle === "true") // (sees if cookie exists and has value of true)
{
    $('body').addClass("myclass");
} else // (if cookie doesn't exist or value is false)
{
    $('body').removeClass("myclass");
}

Basically, it sees if there's a cookie with value of true, and if so then adds the class. But if there's no cookie or value is false, it removes the class. And if the checkbox is toggled while on the page, it adds or removes the class.

How can I get this to check the cookie and add or move class based on the cookie value, and also toggle the class when the checkbox is checked or unchecked?




How to globally change default color of checked MUI CheckBox

I wold like to give the CheckBoxes of MUI a custom color when they are selected.

Examples: Default CheckBox vs Colored CheckBox

I know for a specific CheckBox this can be manipulated by using the color attribute of the component like this:

<Checkbox value="remember" color="secondary"/>

But I want to apply the style globally via a custom theme. I tried several approaches, but for the CheckBox component the theme doesnt seem to be applied. I have something like this in my mind which does work for other components like the button:

import { createTheme } from '@mui/material/styles';

const themeOptions = {
    components: {
        MuiButton: {
            styleOverrides: {
                contained: {
                    background: '#363636',
                    '&:hover': {
                        background: '#FF6600',
                    },
                },
            },
        },
        MuiCheckbox: {
            styleOverrides: {
                checked: {
                    color: '#FF6600',
                },
            },
        },
    },
};

const theme = createTheme(themeOptions);

What do I miss? Thanks in advance




samedi 23 avril 2022

checkbox needing two click to react

im trying to make todo app. i have checkboxes on each item and im trying to change the value of checked(iscompleted) to true when i click my checkbox and it does that, but it needs two clicks to do that why is that happening im trying to solve this for very long time now

import React from "react";
import { useState, useEffect } from "react";
import { ControlPanel } from "./ControlPanel";

export const Input = () => {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");
  const [isCompleted, setIsCompleted] = useState(false);

  const handleChange = (e) => {
    setNewTodo(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const adding = {
      task: newTodo,
      id: Math.floor(Math.random() * 100000),
      checked: isCompleted
    };
    if (newTodo.length) {
      setTodos(todos.concat(adding));
      setNewTodo("");
    }
  };
  const checkbox = (index) => {
    const check = [...todos];
    check[index].checked = isCompleted
    setIsCompleted(!isCompleted);

    setTodos(check);
    console.log(todos);
  
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={newTodo}
          onChange={handleChange}
          placeholder="what needs to be done?"
        />

        <ul>
          {todos &&
            todos.map((todo, index) => {
              return (
                <div>
                  <input
                  
                    checked={todo.checked ? true : false}
                    type="checkbox"
                    onChange={() => checkbox(index)}
                  />
                  <li key={todo.index}>{todo.task}</li>
                </div>
              );
            })}
        </ul>
        <ControlPanel todos={todos} />
      </form>
    </div>
  );
};



How to select a date, tick a box and select a value from drop down box in internet explorer jsf page

I have a webpage to fill with excel data. I am a beginner in VBA. I manage to fill the boxes, however i dont know how to select a date value, tick a box and select a value from a drop down list.

here is my code (which is interrupted for manual actions as i dont know how to proceed with those) Code which is not working i put in comment mode

    Sub fillwebform()

' here I define elemnts for the loop
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("Accises per period")
Dim LastRow As Long
Dim i As Long
LastRow = sht.Cells(sht.Rows.Count, "I").End(xlUp).Row



' here I define Internet Explorer
Dim IE As Object
Dim Doc As HTMLDocument
Dim doccomplete As Boolean
Dim nodeInput As Object



Call Shell("cmd.exe taskkill /F /IM /c iexplore.exe")
Set IE = New InternetExplorerMedium
IE.Visible = True
IE.Navigate "https://eservices.minfin.fgov.be/webForm/public/pdie/pdie.jsf"

' here I define Object to sendkeys
Dim SHELL_OBJECT
SHELL_OBJECT = "WScript.Shell"
Set objShell = CreateObject(SHELL_OBJECT)

Do Until IE.readyState = 4
        DoEvents
Loop
On Error Resume Next

Set Doc = IE.Document

'Doc.getElementById("j_idt49_input").ReadOnly = False
'Doc.getElementById("j_idt49_input").Value = "11/2021"
'Set evt = IE.Document.createEvent("keyboardevent")
'evt.initEvent "change", True, False
'Doc.getElementById("j_idt49_input").dispatchEvent evt


MsgBox ("Selecteer volgende periode: " & sht.Range("j3").Value) '--> here i need to select a value in the date selection because above code is not working
Application.Wait (Now + TimeValue("0:00:1"))
  
Doc.getElementById("nomEntreprise").Click
Doc.getElementById("nomEntreprise").Value = "dummy1"
Doc.getElementById("numTva").Value = "dummy2"
Doc.getElementById("numAutorisation").Value = "dummy3"

Doc.getElementById("idWizard_next").Click

Do Until IE.readyState = 4
        DoEvents
Loop
On Error Resume Next

'Doc.getElementById("categorieCadreA:2").Click
'Doc.getElementById("categorieCadreA:2").Value = True
'Doc.findelementbyclass("ui-chkbox ui-widget").Click

'Dim elements As Variant
'elements = Doc.getElementsByClassName("ui-chkbox ui-widget")
'For Each element In elements
'element.Click
'Next

MsgBox ("klik voertuigen groter dan 7.5T") '--> here i need to tick that box
Application.Wait (Now + TimeValue("0:00:1"))

For i = 6 To LastRow - 1

'nummerplaat
Application.Wait DateAdd("s", 1, Now)
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":registrationId").Focus
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":registrationId").Value = sht.Range("l" & i).Value
Set evt = IE.Document.createEvent("keyboardevent")
evt.initEvent "change", True, False
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":registrationId").dispatchEvent evt

'eigendomsbewijs

MsgBox ("klik op selectie eigendom en selectgeer: " & sht.Range("m" & i).Value & ". Klik dan hier op ok") '--> here i need to select a dropdown value, below code not working
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription").Focus
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_focus").Focus
'Set Choices = Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_input")
'For Each elem In Choices.getElementsByTagName("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_input")
'If elem.Value = "A" Then elem.Selected = True: Exit For
'Next elem
'
'
'
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription").Focus
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription").Click
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_focus").Focus
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_focus").Click
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_focus").ariaActivedescendant = "cliquetsAData:0:cadreAData:" & i - 1 & ":preuve_inscription_1"
'Set evt = IE.Document.createEvent("keyboardevent")
'evt.initEvent "change", True, False
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":invoicesId_input").dispatchEvent evt
'Application.Wait DateAdd("s", 1, Now)

'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription").Focus
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription").Click
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_1").Focus
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":preuve_inscription_1").Click
'Set evt = IE.Document.createEvent("keyboardevent")
'evt.initEvent "change", True, False
'Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & '":preuve_inscription_1").dispatchEvent evt


'aantal facturen
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":invoicesId_input").Focus
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":invoicesId_input").Value = sht.Range("p" & i).Value
Set evt = IE.Document.createEvent("keyboardevent")
evt.initEvent "change", True, False
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":invoicesId_input").dispatchEvent evt

'liters
Dim number As String
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":tankedId_input").Focus
number = CStr(sht.Range("q" & i).Value)
number = Replace(number, ".", ",")
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":tankedId_input").Value = number
Set evt = IE.Document.createEvent("keyboardevent")
evt.initEvent "change", True, False
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":tankedId_input").dispatchEvent evt
Application.Wait DateAdd("s", 1, Now)


'kilometers
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":kmId_input").Focus
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":kmId_input").Value = sht.Range("r" & i).Value
Set evt = IE.Document.createEvent("keyboardevent")
evt.initEvent "change", True, False
Doc.getElementById("cliquetsAData:0:cadreAData:" & i - 6 & ":kmId_input").dispatchEvent evt
Application.Wait DateAdd("s", 1, Now)

sht.Range("s" & i).Value = "Created"

If i = LastRow - 1 Then
Else: Doc.getElementById("cliquetsAData:0:j_idt128").Click
End If

Next i

End Sub



jeudi 21 avril 2022

How to use the same JS code (text with a checkbox with some css) to create hundreds of the same element automaticly

I need hundreds of the same elements with different ID's so they can trigger different songs, without actually changing their ID manually. here for the HTML, JS and CSS:https://jsfiddle.net/Tylanmon/by5Lcvw0/4/ And here's just JS:

var Song_Name = document.createTextNode('La Marseillaise')

var div = document.createElement('div')
div.setAttribute('class', 'div')
var checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.name = 'checkNAME'
checkbox.id = 'checkID'

var label = document.createElement('label')
label.id = 'nameID'
label.htmlFor = 'checkID'
label.appendChild(Song_Name)

div.appendChild(label)
div.appendChild(checkbox)

document.getElementById('songs').appendChild(div)
//  
var length = label.offsetWidth  
var length2 = checkbox.offsetWidth
console.log(length);

div.style.width = `${length + (length2 * 2 - 5.9)}px`;
div.style.backgroundColor = 'whitte'
div.style.borderRadius = '4px'
div.style.border = `1px solid black`;



Excel insert a Checkbox in RPGLE on iSeries (HSSF Scott Klement Java)

i use the HSSF Excel-Tool from Scott Klement on iSeries.

i try to insert a checkbox in my Excel-Sheet with the POI API in RPGLE. But the methods to add Checkboxes aren't in the Scott Klement HSSF as an RPGLE Prototype.

Example:

enter image description here

I found these JavaCode to add Checkboxes:

 XSSFVMLDrawing vmlDrawing = getVMLDrawing(sheet);
  addCheckboxShapetype(vmlDrawing);
  addCheckbox(vmlDrawing, 1, 0, 1, 0, 3, 0, 2, 0, "Checkbox 1", true);
  addCheckbox(vmlDrawing, 1, 0, 2, 0, 3, 0, 3, 0, "Checkbox 2", false);

My Question: How can i use the addCheckbox Method in RPGLE to insert a Checkbox in my Excel-Sheet? How do I have to write the prototype in HSSF to use it on my RPGLE-Code? Is it possible?

Here for example the running RPG Code for add text in a Cell. Now i have to insert a Checkbox like this.

SS_TEXT( ROW:  0 : %TRIM(Titeltext) : text);

Prototype in HSSF:

D ss_text         PR                                         
D   peRow                             like(SSRow)            
D   peCol                        5I 0 value                  
D   peString                  1024A   varying const          
D   peStyle                           like(SSCellStyle)    



How do i add an method on the checkbox when they are clicked they have an specific amount and they add up?

This is an interface of a simple Restaurant Menu. where there is 4 categories Beverages, Snacks, Burger, Dessert. Each category has 10 items which are the checkbox. I need a method that will Upon selecting the items a display will show the total amount of the selected Items. The error is in the bottom part in where i can't access the individual myItem in order to add an method when it is clicked it adds a specific amount.

    import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
        
        public class Restau2 {
            JFrame myFrame = null;
            public static void main(String[] a){
                (new Restau2()).test();
            }
        
            private void test() {
                myFrame = new JFrame("Check Box Menu Item Test");
                myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                myFrame.setBounds(50,50,250,250);
                myFrame.setContentPane(new JDesktopPane());
          
                JMenuBar myMenuBar = new JMenuBar();
                JMenu myMenu = getFileMenu();
                myMenuBar.add(myMenu);
                myMenu = getColorMenu();
                myMenuBar.add(myMenu);
                myMenu = getOptionMenu();
                myMenuBar.add(myMenu);
                myMenu = getJoshMenu();
                myMenuBar.add(myMenu);
                
              
                myFrame.setJMenuBar(myMenuBar);
                myFrame.setVisible(true);
             }
        
             private JMenu getFileMenu() {
                JMenu myMenu = new JMenu("Beverages");
                JCheckBoxMenuItem myItem = new JCheckBoxMenuItem("Ice Tea");
                myItem.setSelected(true);
                myMenu.add(myItem);
                JCheckBoxMenuItem myItem1 = new JCheckBoxMenuItem("Juice");
                myItem.setSelected(true);
                myMenu.add(myItem1);
                JCheckBoxMenuItem myItem2 = new JCheckBoxMenuItem("Beer");
                myItem.setSelected(true);
                myMenu.add(myItem2);
                JCheckBoxMenuItem myItem3 = new JCheckBoxMenuItem("Coffee");
                myItem.setSelected(true);
                myMenu.add(myItem3);
                JCheckBoxMenuItem myItem4 = new JCheckBoxMenuItem("Chocolate Drink");
                myItem.setSelected(true);
                myMenu.add(myItem4);
                JCheckBoxMenuItem myItem5 = new JCheckBoxMenuItem("Pineapple Drink");
                myItem.setSelected(true);
                myMenu.add(myItem5);
                JCheckBoxMenuItem myItem6 = new JCheckBoxMenuItem("Wine");
                myItem.setSelected(true);
                myMenu.add(myItem6);
                JCheckBoxMenuItem myItem7 = new JCheckBoxMenuItem("Soda");
                myItem.setSelected(true);
                myMenu.add(myItem7);
                JCheckBoxMenuItem myItem8 = new JCheckBoxMenuItem("Energy Drink");
                myItem.setSelected(true);
                myMenu.add(myItem8);
                myItem = new JCheckBoxMenuItem("Tea");
                myMenu.add(myItem);
        
                myMenu.addSeparator();
                
                return myMenu;
             }
        
             public JMenu getColorMenu() {
                JMenu myMenu = new JMenu("Snacks");
                JCheckBoxMenuItem myItem = new JCheckBoxMenuItem("Chips");
                myItem.setSelected(true);
                myMenu.add(myItem);
                JCheckBoxMenuItem myItem1 = new JCheckBoxMenuItem("Biscuits");
                myItem.setSelected(true);
                myMenu.add(myItem1);
                JCheckBoxMenuItem myItem2 = new JCheckBoxMenuItem("Fruits");
                myItem.setSelected(true);
                myMenu.add(myItem2);
                JCheckBoxMenuItem myItem3 = new JCheckBoxMenuItem("Cookies");
                myItem.setSelected(true);
                myMenu.add(myItem3);
                JCheckBoxMenuItem myItem4 = new JCheckBoxMenuItem("Bars");
                myItem.setSelected(true);
                myMenu.add(myItem4);
                JCheckBoxMenuItem myItem5 = new JCheckBoxMenuItem("Sandwiches");
                myItem.setSelected(true);
                myMenu.add(myItem5);
                JCheckBoxMenuItem myItem6 = new JCheckBoxMenuItem("Crackers");
                myItem.setSelected(true);
                myMenu.add(myItem6);
                JCheckBoxMenuItem myItem7 = new JCheckBoxMenuItem("Crisps");
                myItem.setSelected(true);
                myMenu.add(myItem7);
                JCheckBoxMenuItem myItem8 = new JCheckBoxMenuItem("Candy");
                myItem.setSelected(true);
                myMenu.add(myItem8);
                myItem = new JCheckBoxMenuItem("Chocolate");
                myMenu.add(myItem);
                return myMenu;
             }
        
             private JMenu getOptionMenu() {
                JMenu myMenu = new JMenu("Burger");
                JCheckBoxMenuItem myItem = new JCheckBoxMenuItem("Egg Sandwich");
                myItem.setSelected(true);
                myMenu.add(myItem);
                JCheckBoxMenuItem myItem1 = new JCheckBoxMenuItem("Cheese Burger");
                myItem.setSelected(true);
                myMenu.add(myItem1);
                JCheckBoxMenuItem myItem2 = new JCheckBoxMenuItem("Chicken Burger");
                myItem.setSelected(true);
                myMenu.add(myItem2);
                JCheckBoxMenuItem myItem3 = new JCheckBoxMenuItem("Ham Burger");
                myItem.setSelected(true);
                myMenu.add(myItem3);
                JCheckBoxMenuItem myItem4 = new JCheckBoxMenuItem("Chicken with cheese Burger");
                myItem.setSelected(true);
                myMenu.add(myItem4);
                JCheckBoxMenuItem myItem5 = new JCheckBoxMenuItem("Regular Burger");
                myItem.setSelected(true);
                myMenu.add(myItem5);
                JCheckBoxMenuItem myItem6 = new JCheckBoxMenuItem("Double Patty Burger");
                myItem.setSelected(true);
                myMenu.add(myItem6);
                JCheckBoxMenuItem myItem7 = new JCheckBoxMenuItem("Deluxe Burger");
                myItem.setSelected(true);
                myMenu.add(myItem7);
                JCheckBoxMenuItem myItem8 = new JCheckBoxMenuItem("Vegetarian Burger");
                myItem.setSelected(true);
                myMenu.add(myItem8);
                myItem = new JCheckBoxMenuItem("Quarterpounder");
                myMenu.add(myItem);
                return myMenu;
             }
        
        
        private JMenu getJoshMenu() {
              JMenu myMenu = new JMenu("Dessert");
              JCheckBoxMenuItem myItem = new JCheckBoxMenuItem("Choco Fudge");
              myItem.setSelected(true);
              myMenu.add(myItem);
              JCheckBoxMenuItem myItem1 = new JCheckBoxMenuItem("Cake");
              myItem.setSelected(true);
              myMenu.add(myItem1);
              JCheckBoxMenuItem myItem2 = new JCheckBoxMenuItem("Shake");
              myItem.setSelected(true);
              myMenu.add(myItem2);
              JCheckBoxMenuItem myItem3 = new JCheckBoxMenuItem("Leche Flan");
              myItem.setSelected(true);
              myMenu.add(myItem3);
              JCheckBoxMenuItem myItem4 = new JCheckBoxMenuItem("Ice cream");
              myItem.setSelected(true);
              myMenu.add(myItem4);
              JCheckBoxMenuItem myItem5 = new JCheckBoxMenuItem("Pastries");
              myItem.setSelected(true);
              myMenu.add(myItem5);
              JCheckBoxMenuItem myItem6 = new JCheckBoxMenuItem("Pies");
              myItem.setSelected(true);
              myMenu.add(myItem6);
              JCheckBoxMenuItem myItem7 = new JCheckBoxMenuItem("Fruit salad");
              myItem.setSelected(true);
              myMenu.add(myItem7);
              JCheckBoxMenuItem myItem8 = new JCheckBoxMenuItem("Pudding");
              myItem.setSelected(true);
              myMenu.add(myItem8);
              myItem = new JCheckBoxMenuItem("Tart");
              myMenu.add(myItem);
              return myMenu;
           }
           public void actionPerformed(ActionEvent e){
              float amount = 0;
              String msg = "";
        
              if(myItem.isSelected()){
                 //been getting an error in where myItem cannot be resolved to a variable
//I need to add method in where if the checkbox is selected it will add a specific amount that adds up overtime.
              }
           }
        }



mercredi 20 avril 2022

How to populate unchecked checkboxes for edit page in React

I have an edit page of a recipe that is populated correctly using findOne axios call and populates all of the information for that recipe. However, it only displays the checkboxes that are checked and not the checkbox objects that are unchecked. I want it to display all checkboxes, both checked and unchecked. See below code.

Edit.jsx

const Edit = (props) => {

    const { _id } = useParams({})
    const [form, setForm] = useState({
        title: "",
        description: "",
        tags: [
            { name: "Athletic/Higher caloric", isChecked: false },
            { name: "Aggressive Weight Loss", isChecked: false },
            { name: "Kid-Friendly", isChecked: false },
            { name: "Non-Vegan", isChecked: false },
            { name: "Diabetes reversal", isChecked: false },
            { name: "Quick and Easy", isChecked: false },
        ],
    })

    useEffect(() => {
        axios.get(`http://localhost:8000/api/recipes/${_id}`)
            .then(res => {
                console.log(res.data.results);
                setForm(res.data.results);
            })
            .catch(err => {
                console.log(err)
                setErrors(err)
            })
    }, [_id])


My checkedHandler from create page:

const handleCheckedTags = (index) => {
        setForm(prev => ({
            ...prev,
            tags: [
                ...prev?.tags?.map(
                    ({ isChecked, ...rest }, idx) => (
                        idx === index ?
                            { ...rest, isChecked: !isChecked } :
                            { ...rest, isChecked })
                )]
        }));
    }

And here is my return code (the edit form):

return (
  <form>
       {
        form.tags.map((tag, i) => (
          <div className="form-inline mx-3" key={i}>
              <input
                   type="checkbox"
                   value={tag.name}
                   checked={tag.isChecked}
                   onChange={(event) => handleCheckedTags(i)}
                   key={i}
                 />
             </div>
           ))}
   </div>
   <input type="submit" />
 </form>

I know I have a single form state to begin with, which was how I setup my create form. Should I have set it up differently or is there a way to make sure the unchecked checkboxes display for the edit page?

Thanks in advance for your help.




Power Automate Desktop: Set the checkbox state in the window in which the window title changes dynamically (UI automation > Form filling)

I'm trying to create a flow where it checks the status of the checkbox for multiple windows (i.e. Windows app which changes the title dynamically). Currently, "set checkbox state window" in power automate desktop will allow to select form app window with the static title, but I need for desktop app window which changes title dynamically.

For e.g. In "Set checkbox state in the window", if we choose with Title "Demo App" and if that window changes its title to "Project A - Demo App" then "Set checkbox state in the window" unable to find the window.

Is there any possible way to get the result I needed?. So, any help would be greatly appreciated. Thanks in advance.

enter image description here




mardi 19 avril 2022

jQuery - show and hide div related to different checkbox

Hello I'm fairly new to jQuery (and stackoverflow), i saw a few questions about showing/hiding div for checkbox but i couldn't find a solution that apply for several checkboxes at the same time.

I would like to make it work so that when my first checkbox is checked, the 1st div/panel just after is shown then hiden when uncheck. And the same thing for my second checkbox with its own panel.

Right now, both panel are shown when first checkbox (or second checkbox) is checked. I don't know how to make it so the panel shown or hidden will be dependant of the checkbox (li?).

I would like a solution that could apply without touching the code when adding new checkboxes, so i think maybe ID shouldn't be use, right? is there any solution?

Your help is much appreciated! Thanks in advance!

HTML :

<ul class="form-check-list">
   <li class="js-tabCheck">
     <label for="coupon" class="check">
       <input type="checkbox" id="coupon" class="js-tabCheck-trigger">
       <span class="check__name txt-bold">COUPON</span>
       <span class="txt-notice txt-indent">-50%</span>
     </label>
     <div class="js-tabCheck-panel">
       <p>coupon detail</p>
     </div>
   </li>

   <li class="js-tabCheck">
     <label for="coupon1" class="check">
       <input type="checkbox" id="coupon1" class="js-tabCheck-trigger">
       <span class="check__name txt-bold">COUPON1</span>
       <span class="txt-notice txt-indent">-30%</span>
     </label>
     <div class="js-tabCheck-panel">
       <p>coupon detail</p>
     </div>
   </li>             
</ul>

JQUERY:

$(function(){
  var checkbox = $('.js-tabCheck-trigger'),
  panel = $('.js-tabCheck-panel');

  panel.hide();

  checkbox.change(function(){
    if($(this).is(':checked')){
      panel.show();
    } else {
      panel.hide();
    };
  });

});



lundi 18 avril 2022

How to select multiple checkboxes in Flatlist?

I'm working on flatlist with checkbox but could not select multiple checkboxes inside flatlist. Every time only single item is selected. Wanted to add dynamic checkbox according to the list and have to handle all checkbox using one function. I have used the following code but its not working. Any help would be appreciated.

import React, { useState, useEffect } from 'react';                                                                              
    import {
      SafeAreaView,
      StyleSheet,
      Text,
      View,
      FlatList,
      TouchableOpacity,
      Image,
      ActivityIndicator,
    } from 'react-native';
    import CheckBox from '@react-native-community/checkbox';
    
    
    const App = () => {
    
      const [isLoading, setIsLoading] = useState(true);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        getListPhotos();
        return () => {
        }
      }, [])
    
      getListPhotos = () => {
        const apiUrl = 'https://jsonplaceholder.typicode.com/photos';
        fetch(apiUrl)
          .then((res) => res.json())
          .then((resJson) => {
            setData(resJson);
          }).catch((err) => { console.error('Error', err); })
          .finally(() => setIsLoading(false))
      }
    
    
      onChangeValue = (item, index) => {
        const newData = data.map(newItem => {
          if (newItem.id == item.id) {
            return {
              ...newItem,
              selected: true,
            }
          }
          return {
            ...newItem,
            selected: false,
          }
        })
        setData(newData);
      }
    
      renderItem = ({ item, index }) => {
        return (
          <View style={styles.item}>
            <Image style={styles.image}
              source=
              resizeMode='contain'
            />
            <View style={styles.wrapText}>
              <Text >{item.title}</Text>
              <CheckBox
                value={item.selected}
                style={styles.ckItem}
                disabled={false}
                onAnimationType='fill'
                offAnimationType='fade'
                boxType='square'
                onValueChange={() => onChangeValue(item, index)}
              />
            </View>
          </View>
        )
      }
      
      return (
        <SafeAreaView style={styles.container}>
          {isLoading ? <ActivityIndicator /> : (<FlatList
            style={styles.list}
            data={data}
            renderItem={renderItem}
            //keyExtractor={(item, index) => item.id}
             keyExtractor={item => `key-${item.id}`}
          />)}
          <View>
            <Text style={styles.wrapButton}></Text>
            <TouchableOpacity style={styles.button}>
              <Text>
                Show item you selected
              </Text>
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      list: {
        flex: 1,
        padding: 8,
      },
      wrapButton: {
        width: '100%',
        justifyContent: 'center',
        alignItems: 'center',
      },
      button: {
        padding: 16,
        backgroundColor: 'orange',
        // justifyContent:'center',
        // alignItems:'center',
        alignSelf: 'center',
        width: '50%'
      },
      item: {
        marginTop: 8,
        flexDirection: 'row',
        padding: 4,
        shadowColor: '#000',
        shadowOffset: {
          width: 0, height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
      },
      image: {
        width: 100,
        height: 150,
      },
      wrapText: {
        flex: 1,
        marginTop: 16,
        marginLeft: 8,
      },
      ckItem: {
        width: 20,
        height: 20,
        marginTop: 5,
    
      },
    });
    
    export default App;



react formik how pass value and id from checkbox component

Here is my checkbox component:

function CheckBoxesControl(props) {
  const { label, name, options, ...rest } = props;

  return (
    <div className='checkbox-control'>
      <span className='checkbox-title'>{label}</span>
      <div className='check-elements'>
        <Field name={name}>
          {({ field, form }) => {
            return options.map((option) => {
              return (
                <React.Fragment key={option.key}>
                  <input
                    type='checkbox'
                    id={option.key}
                    {...field}
                    {...rest}
                    value={option.value}
                    checked={field.value.includes(option.value)}
                  />
                  <label htmlFor={option.value}>{option.value}</label>
                </React.Fragment>
              );
            });
          }}
        </Field>
      </div>
      <ErrorMessage component={TextError} name={name} />
    </div>
  );
}
export default CheckBoxesControl;

Code for FormikControl:

import React from 'react';
import CheckBoxesControl from './checkboxescontrol';
import RadioButtons from './radiobuttons';

function FormikControl(props) {
  const { control, ...rest } = props;

  switch (control) {
    case 'radio':
      return <RadioButtons {...rest} />;
    case 'checkbox':
      return <CheckBoxesControl {...rest} />;

    default:
      return null;
  }
}

export default FormikControl;

And parent component:

 <Formik
            initialValues={formValues || initialValues}
            validationSchema={validationSchema}
            validateOnMount
            onSubmit={onSubmit}
            enableReinitialize 
      >
        {(formikProps) => {
            return (
                <Form>
                <FormikControl
                    control='checkbox'
                    label='Categorie carte'
                    name='categorieCarte'
                    options={filtreazaCategorieCarte}
                  />
    
                </Form>
     </Formik>

filtreazaCategorieCarte - it is an array that I get from firestore that looks like this: [{key:'', value:''}]

I am a beginner, so please bear with me:
Currently all I can get is either option.value or option.key
What I want is the value from checked checkbox send to formik to look like this:
[id: option.id, name: option.value]

Is it possible ?




wanting to know how to easily add sums from a checkbox

im extremely new to c# so im having a little difficulty with the following problem.

below is my following code

int access = 1;
int onlineVideos = 2;
int personalTrainer = 20;
int dietConsultation = 20;

int extras = 0;

if (checkBox1.Checked)
{
    extras += access;
}
else if (checkBox2.Checked)
{
    extras += onlineVideos;
}
else if (checkBox3.Checked)
{
    extras += personalTrainer;
}
else if (checkBox4.Checked)
{
    extras += dietConsultation;
}

textBox6.Text = extras.ToString();

i want to be able to easily add the sums of all the boxes that are checked, and then print them to a textbox.




dimanche 17 avril 2022

Please some1 should help explain to me in detail what each line of the javascript code means. I understand the html. Am just stuck with the javascript [closed]

<!DOCTYPE HTML PUBLIC "-//W3C//DTD 
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/
loose.dtd">
<html>
<head>
<title>Graphic Checkboxes</title>
<script type="text/javascript">
function graphicBox(box) { 
//be unobtrusive
if (!document.getElementById) 
return;
//find the object and its parent
obj=document.getElementById(box);
parentobj= obj.parentNode;
//hide the regular checkbox
obj.style.visibility="hidden";
//create the image element and 
//set its onclick event
img= 
document.createElement("img");
img.onclick= Toggle;
img.src="unchecked.gif";
//save the checkbox id within the 
//image ID
img.id="img" + box;
//display the graphic checkbox
parentobj.insertBefore(img,obj);
}
function Toggle(e) {
if (!e) var e=window.event;
//find the image ID
img= (e.target) ? e.target : 
e.srcelement;
//find the checkbox by removing 
"img" from the image ID
checkid= img.id.substring(3);
checkbox=
document.getElementById(checkid);
//"click" the checkbox
checkbox.click();
//display the right image for the 
//clicked or unclicked state
if (checkbox.checked) 
file="checked.gif";
else file="unchecked.gif";
img.src=file;
}
//replace the second checkbox 
//with a graphic
graphicBox("check2");
</script>
</head>
<body>
<h1>Graphic Checkbox Example</h1>
<form name="form1" method="post" 
action="">
<p><input type="checkbox" 
name="check1" id="check1" />An 
Ordinary Checkbox</p>
<p><input type="checkbox" 
name="check2" id="check2" />A 
Graphic Checkbox, created with 
unobtrusive Javascript.</p>
</form>
</body>
</html>

// I am currently learning html, css and javascript. I am using sams teach yourself book. The book has 28 chapters and am currently on chapter 21 where i encountered this code. I am stuck and unable to fully understand what each line means and what the functions are in the code. Please some1 should please explain in detail to me. I understand the html part. Just have issues with the javascript part. Thanks in advance




React checkbox not checking the checkbox

My second checkbox is not checking the checkbox even after clicking on checkbox.Im using a simple json object in {props.data}. i.e.

If I select city name, then state will also checked automatically.

[enter image description here][1]



Issue with marking of checkboxes in the list of items

I have a Vue app: it is To Do List, where after adding some notes by clicking button Add Task we receive a list of items to do. On the front of each item we have button Delete and checkbox to have opportunity to mark it as done. The bug is when I for example mark one of the items in the list as checked and after that delete it-marker that it was checked goes to the other item which was not marked as checked initially. Can you please advice how it can be solved using Vue.js or any other option? Below is my code:

Vue.createApp({
    data(){
        return{
          placeholder: 'Start typing',
          inputvalue: '',
          notes: []
        }
    },
    mounted() {
        this.notes = JSON.parse(localStorage.getItem('note')) || [];
      },
      watch: {
            notes: {
                handler: function() {
                    localStorage.setItem('note', JSON.stringify(this.notes));
                },
                deep: true
            }
        },
    methods: {
        addnewtask(){
            if (this.inputvalue !== ''){
                this.notes.push(this.inputvalue)
                this.inputvalue=''
            }
        },
        removetask(index){
            if (confirm('Do you really want to delete?'))
            this.notes.splice(index, 1)
        }
    }
}).mount(app)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do List</title>
</head>
<link rel="stylesheet" href="style.css">
<body>
    <div class="container" id="app">
      <div class="card">
          <h1>To Do List</h1>
          <div class="form-control">
             <input
                 type="text" 
                 v-bind:placeholder="placeholder" 
                 v-model="inputvalue"
                 v-on:keypress.enter="addnewtask"
              />
              <button class="btn" v-on:click="addnewtask">Add Task</button>
            </div>
            <hr />
            <ul class="list" v-if="notes.length !== 0"...>
                <li class="list-item" v-for="(note, index) in notes">
                    <div>
                        <input type="checkbox"/>
                        () 
                    </div>
                    <button class="btn danger" v-on:click="removetask(index)">Delete</button>
                </li>
                <hr />
                <li>
                    <strong>Total: </strong>
                </li>
            </ul>
            <div v-else>No task exist, please add first one.</div>
      </div>
    </div>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="Vue3.js"></script>
</body>
</html>



samedi 16 avril 2022

How to check all checkboxes with different names in the same row

I Have html table as below code, How to check all checkboxes with different names in the same row?? Such as in the row of "Item name 1": if I check the box of "Check all", and then the box of "Date of Start: 2022-04-01" and the box of " Date of End: 2022-04-30" will be auto checked.

<table border="1" cellpadding="10" cellspacing="1" width="100%" class="tblListForm">
<tbody><tr class="listheader">
<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('tbid[]');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
</script>
<td style="width:10%"><input type="checkbox" onclick="toggle(this)">Quantity/Select All</td>
<td style="width:67%"> Item Details </td>
<td style="width:10%; text-align:right;"> Unit Price </td>
<td style="width:13%; text-align:right;"> Sub-total </td>
</tr>
<tr class="evenRow">
<td style="vertical-align:top">
    <input type="checkbox" name="tbid[]" value="238"> 1</td>
<td style="vertical-align:top">
    Item name 1     <br>
    <input type="checkbox" name="item_no[]" value="1"> Check all<input type="checkbox" name="item_date_start[]" value="2022-04-01">Date of Start: 2022-04-01<input type="checkbox" name="item_date_end[]" value="2022-04-30"> Date of End: 2022-04-30</td>
<td style="vertical-align:top; text-align:right;">
    105.00</td>
<td style="vertical-align:top; text-align:right;">
    105.00</td>
</tr>
<tr class="oddRow">
<td style="vertical-align:top">
    <input type="checkbox" name="tbid[]" value="239"> 1</td>
<td style="vertical-align:top">
    Item name 2<br>
    <input type="checkbox" name="item_no[]" value="17"> Check all<input type="checkbox" name="item_date_start[]" value="2022-05-01">Date of Start: 2022-05-01<input type="checkbox" name="item_date_end[]" value="2022-05-31"> Date of End: 2022-05-31</td>
<td style="vertical-align:top; text-align:right;">
    250.00</td>
<td style="vertical-align:top; text-align:right;">
    250.00</td>
</tr>




<tr class="listheader">
<td></td>
<td></td>
<td style="vertical-align:top; text-align:right;">  Total (HKD): </td>
<td style="vertical-align:top; text-align:right;">  355.00</td>
</tr>

</tbody>
</table>

Thank you very much for your sharing & support in advance!




How Can Add CheckBox Column in DataGridView?

I Have An API And That API Give Me A Jason Of Some Lists And I Show That In My DataGridView I Want To Set A Check Box Column To My DataGridView For Selecting A Row Of A DataGridView Easier.

That's My Answer From API And Set To DataGridView

var WorkListFromApis = serializer.Deserialize<List<Sysmexxp300WorkListFromApi>>(json.ToString());
                    dgv_tests.DataSource = WorkListFromApis;

That's My Sysmexxp300WorkListFromApi Class

 public class Sysmexxp300WorkListFromApi  //Model For WorkList OF Sysmex Xp300
    {
        public Int64 Id_ReceptionDetail { get; set; }
        public string PatientName { get; set; }
        public string MasterPriorityName { get; set; }
        public string DetailPriorityName { get; set; }
        public int Code_Patient { get; set; }
        public string CustomCode { get; set; }
        public string WBC { get; set; }
        public string RBC { get; set; }
        public string HGB { get; set; }
        public string HCT { get; set; }

    }

How Can I Add Check Box To Each Row ??




How do I check and display if multiple checkboxes are checked within a group box in vb.net

    For Each ctl As Windows.Forms.Control In Me.Controls
        If TypeOf ctl Is System.Windows.Forms.CheckBox Then
            Dim ck As System.Windows.Forms.CheckBox = ctl
            If ck.Checked Then
                intcheckboxesChecked += 1
            End If
        End If
    Next

When I display the count its results to a 0 value




Can I set a button in google sheets to alter the image url

This feels like it should be dead simple but I've not tried anything like this in google sheets before.

I have an image on a sheet but I want it to change to another image (either via altering the image url, or just hiding one and showing another etc) either via clicking the images themselves or just via a button but have no idea where to start with this and all my googling has ironically, turned up absolutely nothing.

Any help or pointers to useful sources would be greatly appreciated!




vendredi 15 avril 2022

vb.net how to trigger a treeview afterCheck event from inside MouseClick event

I have a treeview with parent and child nodes. all of them have check boxes. I did the code of checking/unchecking all the childs when the parent is checked/unchecked.

I have a problem when mouse double click on tree view parent check box, sometimes all the childs get checked some times all of them not checked. thee treeview after check code is working fine , but my problem is with mouse double click , so i need to paste the tree_after check code and trigger it from inside the mouse double click too.

     Private Sub node_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterCheck
            ' The code only executes if the user caused the checked state to change.
            If e.Action <> TreeViewAction.Unknown Then
                If e.Node.Nodes.Count > 0 Then
                    ' Calls the CheckAllChildNodes method, passing in the current 
                    ' Checked value of the TreeNode whose checked state changed. 
                    Me.CheckAllChildNodes(e.Node, e.Node.Checked)
                End If
            End If
        End Sub


 Private Sub TreeView1_MouseClick(sender As Object, e As MouseEventArgs) Handles TreeView1.MouseClick
'how i trigger the node_AfterCheck from here

    End Sub

    Private Sub TreeView1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles TreeView1.MouseDoubleClick

'how i trigger the node_AfterCheck from here
    End Sub



Close hamburger menu when a link inside of it is clicked

Following problem: When you click on the sandwich/hamburger menu icon,a menu is opened. That works already. What I am trying to achieve now is when you click on a menu item, the whole menu should close and reveal the site in the background. The links load into a div via a script, so you won't be leaving the actual site.

Important: this whole sandwich menu is done with a checkbox .. I tried copying some premade scripts that uncheck it but it just won't work. Help would be appreciated.

komic.biz/new1.html <- Site




mercredi 13 avril 2022

Get checkbox values in given range in Google Sheets

I'd like to create a function that returns 2D array containing checkbox values in given range:

  • true if checked
  • false if unchecked
  • null if no checkbox

enter image description here

function getCheckboxInfo(range): {
  const sheet =  SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  range = sheet.getRange(rangeA1);
  return /* (boolean|null)[][] */
}

Although I found similar methods for values (range.getValues()) or notes (range.getNotes()), I haven't found anything like that for checkboxes. The only solution I got so far doesn't look very optimal

return range.getValues().map((row, i) => {
  return row.map((_, j) => sheet.getRange(i + 1, j + 1).isChecked())
});

Is there a better way to do it?

EDIT: Solution using method suggested by Ricardo

  const values = range.getValues();
  const validators = range.getDataValidations()

  return validators.map((row, i) => {
    return row.map((v, j) => v && v.getCriteriaType() === SpreadsheetApp.DataValidationCriteria.CHECKBOX ? !!values[i][j] : null)
  })



Inverse the angular checkbox default values

I need to inverse the default values of checkbox. For eg. if checkbox is checked it sends the value as boolean true but i want to send value as false and vice versa.

Also if i assign the value as false in angular reactive form initialization the checkbox should be in checked state and if i assign true, checkbox should not be checked. I cannot figure out any solution, any help would mean a lot. Thanks.

Here is the code I am working on

component.html

<form [formGroup]="featureForm" (ngSubmit)="onSubmit()">
    <div class="form-group">

   <input type="checkbox" formControlName="featured" id="featured">
   <label for="featured" id="check1"> Checkbox 1</label><br>

   <input type="checkbox" formControlName="addons" id="addons">
   <label for="addons" id="check2"> Checkbox 2</label><br><br>

   <button>Send</button>
</div>
</form>

component.ts file

featureForm:FormGroup
this.featureForm=this.fb.group({
    featured:[false,Validators.required],
    addons:[false,Validators.required],
});



What is the opposite of :checked [duplicate]

I have a jquery script like this:

$(document).ready(function() {
            if ($('#type_seller_correction').is(":unchecked")) // check if the checkbox is not checked
            {
                console.log("unchecked");
            }
});

But this does not work because :unchecked is wrong.

And I don't know what is the opposite of :checked in this situation.

So how can I check if the checkbox is unchecked?




mardi 12 avril 2022

React checkbox and select all doesn't work

I tried to build a list of projects, each with a checkbox for multi-selection. I also want to have a "select all" checkbox to select and de-select all the projects.

My problem is, whatever change I made to the state valuable, the checkbox just won't change (checked state). Can anyone please help?

''' import { Checkbox, ControlGroup } from "@blueprintjs/core"; import React, { useState } from "react";

const initProjectList = [ { "id": 1234567890123456, "name": "project 1", "description": "project description", "data file": "data_file.csv", "created date": "2022-04-12", "checked": false }, { "id": 1234567890123457, "name": "project 2", "description": "project description", "data file": "data_file.csv", "created date": "2022-04-12", "checked": true }, { "id": 1234567890123458, "name": "project 3", "description": "project description", "data file": "data_file.csv", "created date": "2022-04-12", "checked": false } ]

export default function ManageProject() {

const [projectList, setProjectList] = useState(initProjectList);

const handleSelectAll = () => {
    var tmpObj = projectList
    tmpObj.map((obj) => (
        obj.checked = !obj.checked
    ))
    setProjectList(tmpObj)
}
const toggleItem = (index) => {
    var tmpObj = projectList
    tmpObj[index].checked = !tmpObj[index].checked
    setProjectList(tmpObj)
}
const ProjectListPanel = () => (
        projectList.map((project, index) => {
            return (
            <ControlGroup key={"formGroup." + project.id}>
                <Checkbox key={"checkBox." + project.id} checked={project.checked} onChange={() => toggleItem(index)} />{project.id} {project.name} {project.description}
            </ControlGroup>
            )
        })
)
return (
    <div>
        <ControlGroup><Checkbox id="checkBox.SelectAll" onChange={()=>handleSelectAll()} /> Select all</ControlGroup>
        {<ProjectListPanel />}
    </div>
)

}'''




Mulitcheckbox : I am able to check only one checkbox

There are 2 checkboxes displayed in a grid cell. I am able to check only one checkbox. If I click on the another, it' checking the first one. How to make the other checkbox active. here is my html:

    <div class="inline-div" *ngFor="let item of to.labels | keyvalue; let idx=index">
<input type="checkbox" id="item">
<label class="form-check-label" for="item"></label>
</div>

Please suggest how to make sure the other checkbox is been checked.




lundi 11 avril 2022

Multicheckbox not being clickable(not getting checked at all)

I wanted to render multiple checkbox in a grid cell. I tried with formly multicheckbox. But with that, the checkboxes were not even rendering. So I tried to do it in this way, but in this way it's not being checked at all. Right now, I don't want any event to be done on checkbox, I just want it to checkec unchecked by user. to.labels is coming from another service. In .ts file, I am having :

public ngOnInit{
console.log(this.to.labels) }

Can someone please help?

<div class="inline-div" *ngFor="let item of to.labels | keyvalue; let idx=index">
<input type="checkbox">
<label class="form-check-label"></label>
</div>

to.labels is like an array

0: { id:1, label:'P'}
1: {id:2, label:'R'}

I think the problem is the checkboxes are on a grid, so the grid cell is getting active and not the checkbox. Please how to activate checkbox in a grid cell.




Check/uncheck checkboxes in PDF with Python - pyPDF2 and with data from excel

I have written the code below that automatically fill in one of my pdf templates, getting data form an excel sheet and saves a copy of it in one of my folders. The full code is attached below. I have removed the folders and replaced the dictionary with example texts. And yes, I am a beginner:)

import os
import pandas as pd
from PyPDF2 import PdfFileWriter, PdfFileReader
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject, NumberObject

def set_need_appearances_writer(writer: PdfFileWriter):
    try:
        catalog = writer._root_object
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)})
        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
        return writer

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))
        return writer

def ReadOnlyPDFOutput(page, fields):
    for j in range(0, len(page['/Annots'])):
        writer_annot = page['/Annots'][j].getObject()
        for field in fields:
            if writer_annot.get('/T') == field:
                writer_annot.update({
                    NameObject("/Ff"): NumberObject(1),
                    NameObject("/Ff"): NameObject(1)})

if __name__ == '__main__':
    xl_filename = "Example_excel_list"
    pdf_filename = "Example_template"

    xlin = os.path.normpath(os.path.join(os.getcwd(),r'C:\.....',xl_filename))
    pdfin = os.path.normpath(os.path.join(os.getcwd(),r'C:\.....',pdf_filename))
    pdfout = os.path.normpath(os.path.join(os.getcwd(),r'C:\.....'))
    data = pd.read_excel(xlin)
    pdf = PdfFileReader(open(pdfin, "rb"), strict=False)
    
    if "/AcroForm" in pdf.trailer["/Root"]:
        pdf.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})
        
    pdf_fields = [str(x) for x in pdf.getFields().keys()] # List of all pdf field names
    excel_fields = data.columns.tolist()
    
    i = 0 #Filename numerical prefix
    for j, rows in data.iterrows():
        i += 1
        pdf2 = PdfFileWriter()
        set_need_appearances_writer(pdf2)
        if "/AcroForm" in pdf2._root_object:
           pdf2._root_object["/AcroForm"].update(
               {NameObject("/NeedAppearances"): BooleanObject(True)})
           
        # Below you must define the field names as keys in this dictionary
        # Field names found by running and printing line 15
        # Key = pdf_field_name : Value = csv_field_value
        field_dictionary_1 = {"Example1": str(rows['Example1']),
                            "Example2": rows['Example2'],
                            "Example3": rows['Example3'],
                            "Example4": rows['Example4'],
                            "Example5": rows['Example5'],
                            "Example6": rows['Example6'],
                            "Checkbox1": rows['Checkbox1'],
                            "Checkbox2": rows['Checkbox2'],
                            }
        
        

        temp_out_dir = os.path.normpath(os.path.join(pdfout,str(i) + 'out.pdf'))
        
        pdf2.addPage(pdf.getPage(0)) # Makes a copy of pdf template page
        pdf2.updatePageFormFieldValues(pdf2.getPage(0), field_dictionary_1) # Updates fields
        
        
       
        #Makes the pdf output file READ-ONLY
        ReadOnlyPDFOutput(pdf2.getPage(0), field_dictionary_1)
        
        outputStream = open(temp_out_dir, "wb")
        pdf2.write(outputStream) # Saves copy of enhanced template
        outputStream.close()

    print(f'Process Complete: {i} PDFs Processed!')

What I want to improve is the possibility to "check" the checkboxes instead of doing it with textboxes with the letter "x" which I have done in this code. For example, if I write "Yes" in a specific excel cell, the checkbox "checks". If nothing is displayed the checkboxes stays empty. I probably have to make a dictionary for the checkboxes itself, but i am not sure how I should proceed with the rest...

Any help would be gladly appreciated!




Make checkbox trigger when clicking on the whole section

I am currently using Clickfunnels to build a checkout page.

Here I have a bump offer (an upsell that you can add to your cart ticking a checkbox).

This checkbox is inside a section where I can change colors and stuff, but I would like to accomplish this:

When I click on any part of the section (text, background, etc) I want the checkbox to trigger (on/off).

So if a person clicks on the whole upsell section, it can work as a macro button.

Can somebody help me achieve this?




Enable a disabled input field by default when checkbox is checked in angular

I am creating a form group with a checkbox in Angular 13. Here, the field of receiver code is disabled by default. How can I enable this input field when the checkbox is checked and disable when it's not?

in my .ts I have:

export class IntPayComponent implements OnInit { 
     paymentDetails!: FormGroup;
     disabled = true; 

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
this.paymentDetails = this._formBuilder.group({
  receiver_code: new FormControl({value:"", disabled: true})
});
}

and in my html template I have:

<mat-stepper [linear]="isLinear" #stepper>
   <mat-step [stepControl]="paymentDetails">
      <form [formGroup]="paymentDetails">
         <div class="add-directory">
            <mat-checkbox>Add to Directory</mat-checkbox>
         </div>
         <div class="reference-field">
            <mat-form-field appearance="fill" floatLabel="always">
               <mat-label>Receiver Code</mat-label>
                  <input matInput formControlName="receiver_code" disabled/> 
            </mat-form-field>
         </div>
      </form>
   </mat-step>
</mat-stepper>



Align checkbox sat outside of Gridview to checkboxes (one column) within Gridview

I'm at a loss trying to align a standalone checkbox sat outside of the grid to a column containing checkboxes within it, the grid adjusts in width each view based on content returned.

My thinking was to try and grab the positioning of the column to then programmatically apply to the standalone checkbox but nothing was being returned.

Is there an easy way to reference the positioning of the column in question to then apply the left and height to the standalone checkbox? Which I'm wanting to be just sat below or should I be going about this in a totally different manner?




Get user roles input using checkboxes and save in an array using useState() in react

I am creating an admin page where the admin can assign roles to other users. For this, I'm creating a front end input with checkboxes:

role options

Now based on the options that the admin selects on front end, i want to send the roles data to backend in form of an array:

roles: ['admin', 'seller']

useState should be able to add / remove items to this array based on whether the associated cell is checked or unchecked.

const [roles, setRoles] = useState([]);

const checkBoxInputs = [
{
  id: 1,
  label: 'Admin',
  value: 'admin',
},
{
  id: 2,
  label: 'Seller',
  value: 'seller',
},
{
  id: 3,
  label: 'User',
  value: 'user',
},
];

const [isChecked, setIsChecked] = useState(false);
const [roles, setRoles] = useState([]);

const handleCheckboxChange = (e) => {
  setIsChecked(!isChecked);
  if (isChecked) {
    setRoles([...roles, roles.push(e.target.value)]);
  } else {
    setRoles([roles.filter(e.target.value)]);
  }
};

console.log(values);
console.log(roles);

The app code:

<div>
   <div className="mb-2 pb-1 border-b text-sm">
      Choose user roles:
   </div>
<ul className="flex items-center gap-1">
{checkBoxInputs.map((role, index) => (
  <li key={index}>
    <input
      type="checkbox"
      id={role.value}
      name="roles"
      value={role.value}
      checked={isChecked}
      onChange={handleCheckboxChange}
    />
    <label htmlFor={role.value} className="text-sm ml-1">
      {role.label}
    </label>
  </li>
  ))}
</ul>
</div>

Though the current implementation either checks or unchecks all inputs together.

Also, the values don't get removed from roles array when the checkboxes are checked out.




Excluding rows or columns from Checkbox macro

So, I have based a lot of functions on a sheet on checkboxes. It grew beyond the original scope, and now I needed to add a few more control textboxes The problem is, I wrote a script which would Unmark blank checkboxes if a cell in the row was blank (the cell in G column), and now that I have a few more checkboxes to control other functions, my script unfortunately affects the others. Here is the script:

Sub UnMarkBlankCheckBoxes()

Dim chk As CheckBox
Dim ws As Worksheet

Set ws = ActiveSheet

For Each chk In ws.CheckBoxes
    If ws.Range("G" & chk.TopLeftCell.Row).Value = vbNullString Then
        chk.Value = False
    Else
        chk.Value = True
    End If
Next chk

End Sub

I need to be able to either select within a specific range (only column E), OR Exclude everything else. I have been trying things, but cant get it to work. Any ideas? Thanks in advance!




dimanche 10 avril 2022

Why is the initial state of my inputs ignored?

Please check out my fiddle below. A checkbox with nested checkboxes. The change function works fine: if any $('#checkbox' + x) is checked, the corresponding $('.entry' + x) shows, and if unchecked, hidden.

The initial state of my checkboxes is ignored until at least one of the checkboxes are clicked. In the example, initially all $('.entry' + x) show, although #checkbox1, -2 and -3 are initially checked. But: if I then uncheck #checkbox2, only .entry1 and .entry3 show, all other elements hide. From there on, everything works as expected.

I've tried the following:

  1. $('#checkbox1').click(); so just clicking without "actually" clicking (leads to checkbox1 being unchecked but nothing else happens until I click on any of the checkboxes)

  2. setting a checkbox to .prop('checked', true) (pretty much the same result like in 1)

  3. I've also tried it with an if/else statement like

`

if ($('#checkbox' + x).prop('checked') == 'true') {
$('.entry' + x).show();
}
else{
$('.entry' + x).hide();
}`

Still nothing. How do I gain control over the initial states of the checkboxes in this example? Please help me, I just can't figure it out. Just to make clear what i want to achieve: I'd like to be able to set the props to checked and have the checked/unchecked "+ x" elements be hidden and shown accordingly, and create .on('click', ...) events to change the props later on and have them always behave accordingly.

 $(function () {
              // CHECKBOXES GROU AND NESTED CHECKBOXES HIDE/SHOW SYNCHRONIZING
              $.fn.nestedCheckboxes = function (stopPropogation) {
                this.addClass('nestedCheckboxes');
                this.on('click', ':has( > input[type=checkbox])', nestedCheckboxHandler);
                $(this).nestedCheckboxHandler;
                function nestedCheckboxHandler(evt) {
                  if ($(evt.target).is("input[type=checkbox]")) {
                    var parentContainer = $(this);
                    var checkbox = parentContainer
                      .find(' > input[type=checkbox]:eq(0)');
                    var parentCheckbox = parentContainer
                      .parent()
                      .closest(':has( > input[type=checkbox])')
                      .children('input[type=checkbox]');
        
                    if (evt.target == checkbox[0]) {
                      $('input[type=checkbox]', parentContainer)
                        .prop("checked", checkbox.prop("checked"));
                      $(function () {
                        $(new Array(5).fill(1).map((_, i) => i + 1)).each(function (idx, x) { // Array for the number of div elements
                          $('.entry' + x)[($('#checkbox' + x).prop("checked") ? "show" : "hide")](); // synchronize
        
                          $('#checkbox' + x).on('change', function () {      // toggle on change     
                            $('.entry' + x).toggle();
                          });
                        });
                      });
                    }
                    var parentCheckboxValue = !parentCheckbox
                      .parent()
                      .find("input[type=checkbox]")
                      .not(parentCheckbox[0])
                      .is("input[type=checkbox]:not(:checked)");
        
                    parentCheckbox.prop("checked", parentCheckboxValue);
                  } else if (stopPropogation) {
                    evt.stopPropagation();
                  }
                };
              };
                $('.treeX-container form').nestedCheckboxes();
            });
* {
            list-style-type:none;
            }
            .l0{
            color: #000;
            font-weight: bold;
            }
            .entry1,
            .l1{
            color: #ff3333;
            }
            .entry2,
            .l2{
            color: #003DFF;
            }
            .entry3,
            .l3{
            color: #FF8A0E
            }
            .entry4,
            .l4{
            color: #45F300;
            }
            .entry5,
            .l5{
            color: #E700EF;
            }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <div class="treeX-container">
              <ul>
                <form>
                  <li>
                    <input type="checkbox"/>
                      <span class="l0">ALL</span>
                        <ul>
                          <li>
                            <input type="checkbox" id="checkbox1" value="1" checked />
                           <label class="l1">Entry1</label>
                          </li>
                          <li>
                            <input type="checkbox" id="checkbox2" value="1" checked />
                            <label class="l2">Entry2</label>
                          </li>
                          <li>
                            <input type="checkbox" id="checkbox3" value="1" checked />
                            <label class="l3">Entry3</label>
                          </li>
                          <li>
                            <input type="checkbox" id="checkbox4" value="1" />
                            <label class="l4">Entry4</label>
                          </li>
                          <li>
                            <input type="checkbox" id="checkbox5" value="1" />
                            <label class="l5">Entry5</label>
                          </li>
                       </ul>
                   </li>
                </form>
              </ul>
            </div>
            <div class="container">
            <div class="entry1">ENTRY1</div>
            <div class="entry2">ENTRY2</div>
            <div class="entry3">ENTRY3</div>
            <div class="entry4">ENTRY4</div>
            <div class="entry5">ENTRY5</div>
            </div>