mercredi 30 septembre 2020

JavaScript Graphic Checkbox doesn't show

Second checkbox is supposed to be a graphic checkbox but it's not working properly.

index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Graphic Checkboxes</title>
        <meta name="viewport"
            content="width=device-width initial-scale=1">
    </head>
    <h1>Graphic Checkbox Example</h1>
    <form name="form1">
        <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>

    <script src="checkbox.js"></script>
</html>

checkbox.js

function graphicBox(box) {
    // Be unobtrusive.  
    if (!document.getElementById) {
        return;
    }

    // Find the object and its parent.  
    obj = document.getElemementById(box);
    parentobj = obj.parentNode;

    // Hide the regular checkbox.  
    obj.style.display = "none";

    // Create the image element and set its onclick event.  
    img = document.createElement("img");
    img.addEventListener("click", Toggle);
    img.src = "images/unchecked.bmp";

    // 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 remoiving "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 = "images/checked.bmp";
    }
    else {
        file = "images/unchecked.bmp";
    }

    img.src = file;
}

graphicBox("check2");

Pathing: https://i.imgur.com/xQITWQK.png

Result: https://i.imgur.com/x4O1CaD.png

As you can see, the check box does not have graphics.

These are my checkbox graphic images: checked.bmp and unchecked.bmp.

checked.bmp: https://i.imgur.com/HH8ukjZ.png

unchecked.bmp: https://i.imgur.com/dhYKUjX.png




making a radio button behave like a checkbox

For reasons far off topic, I have a set of 2 radio buttons that I need to behave like a checkbox. By this I mean, 1 of the radio buttons will be hidden and the other needs to be able to be cleared (and in actuality check the hidden one).

It looks something like this:

<ul id="id_member_field_request-demo-1">
    <li>
        <label for="id_member_field_request-demo-1_0"><input type="radio" name="member_field_request-demo-1" value="Please contact me to schedule a 60 minute, 1-on-1 demo" field_id="8394681" id="id_member_field_request-demo-1_0">Please contact me to schedule a 60 minute, 1-on-1 demo</label>
    </li>
    <li>
        <label for="id_member_field_request-demo-1_1"><input type="radio" name="member_field_request-demo-1" value="false" field_id="8394681" id="id_member_field_request-demo-1_1">false</label>
    </li>
</ul> 

So far I have:

var radio1 = $('#id_member_field_request-demo-1_0');
var radio2 = $('#id_member_field_request-demo-1_1');

radio2.prop('checked', true).css('display', 'none');

radio1.click(function() {
  if(radio1.is(':checked')) {
    radio2.click();
  }
});

Unfortunately, clicking on the visible radio button (radio1) always returns that it's checked... and thus can never get to the checked state. I need to know if it was previously checked/unchecked.

The only way I can think to do this is to hold the current checked radio in a variable and then go from there... so I end up with this:

var radio1 = $('#id_member_field_request-demo-1_0');
var radio2 = $('#id_member_field_request-demo-1_1');

radio2.prop('checked', true).parent().css('display', 'block');

var checkedId = radio2.attr('id');
//console.log(checkedId);

radio1.click(function() {
  if(checkedId == radio1.attr('id')) {
    radio2.prop('checked', true);
    checkedId = radio2.attr('id');
  } else {
    checkedId = radio1.attr('id');
  }
});

This works - just checking to see if there's a more straightforward way?




how to correctly display message on radio button click

Hi Can someone help me out please. see my code codepen.io/mimmym/pen/MWydLry

I have an issue where the message does not show when i select the following option. Bespoke Design and Quality Development. Does anyone know how to fix this issue?

Thanks




Generate checkboxes and read back checkbox state to PDF with PHP

I have the problem, i would generaete checkbox in pdf with php, but if i recheck checkbox state i not found checkboxs.

I tried:

  • TCPDF (Generate)
  • C# (Read, it not found checkbox)
  • Python (Read,Pypdf2, it not found checkbox)

Images:

Files:

PHP checkbox generate code:

$pdf = new \setasign\Fpdi\TcpdfFpdi('L', 'mm', 'A4');
$pages = $pdf->setSourceFile('file://C:/Users/JonDoe/Desktop/sample.pdf');


for ($i = 1; $i <= $pages; $i++)
{
    $pdf->AddPage();
    $page = $pdf->importPage($i);
    $pdf->useTemplate($page, 0, 0);

    $pdf->CheckBox('newsletter', 5, true, array(), array(), 'OK1', 600/5, 500/5, true);
}
$pdf->Output("file://C:/Users/JonDoe/Desktop/sample.pdf", 'F');

Reader script:

C#:

using System;
using iTextSharp.text.pdf;;
using System.Linq;

namespace PDF_Checkbox
{
    class Program
    {

        static void Main(string[] args)
        {

            string path = "C:\\Users\\JonDoe\\Desktop\\sample";
            PdfReader reader2 = new PdfReader(@"" + path + ".pdf");
            var fieldList = GetFormFieldNamesWithValues(reader2);


            Console.WriteLine("============================================================");
            Console.WriteLine("Fields: " + fieldList);
            Console.WriteLine("============================================================");

            Console.ReadKey();
        }

    }
}

Python 3.8:

import PyPDF2 as pypdf

pdfobject=open('sample.pdf','rb')
pdf=pypdf.PdfFileReader(pdfobject)
print(pdf.getFields())

As you read, I want to see the generated checkboxes state, whether python or c #, php Does anyone know a solution for this?




How to set AppendCheckItem to "check" by default in wxwidgets?

I have a drop down menu "menu" for which I want to add a check item which should be checked by default. How can I do the same in wxwidgets in C++?

check_option = menu->AppendCheckItem(CHECK_ID, wxT("Check"));



How to use Multiple ChechBox in React Native

Here I Want to use Multiple selected item in React Native with Stack-Navigation. How to do like that showSelectItemList.js has a stack navigator add item after click on this button we have moved to addToitemList Screen and click on item to select one or more items after that click on Done Bottom from header of this Screen after click on Done we have moved to showSelectedItemList screen and display all selected items here..

Please Help me Thanks




Get the value of a dynamic element with checkbox click

I have an HTML form as below. What I am trying to do is to get the value of the element that has an id named type when I click the checkboxes. For my case there are two elements that have value ML and PH. But when I click, it always giving the value 'PH` only. Does anyone know why?

< script src = "https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity = "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin = "anonymous" > < /script> <
  script src = "https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity = "sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin = "anonymous" > < /script> <
  script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity = "sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin = "anonymous" > < /script>                     <
  script >
  $("#multiShipment").hide(); //This is hiding multishipment button on page load
$(document).on("click", "#multiShipment", function(e) { //This is when user click multiple tags shipment at once button
  $('#tagSerial').val($("#groupedTagSerialNumber").val()); //tagSerial number text box will be updated with the value of groupedTagSerialNumber
  e.preventDefault();
});

$('#selectAllBoxes').click(function(event) {
  if (this.checked) {

    $('.checkBoxes').each(function() {
      this.checked = true;
    });
  } else {
    $('.checkBoxes').each(function() {
      this.checked = false;
    });
  }
});

$(".checkBoxes").change(function() { //This is tracking if user changed/clicked checkbox
  var searchIDs = $(".checkBoxes:checked").map(function() { // This is mapping all the checkboxes
    if ($(this).prop('id') != "selectAllBoxes") { //As long as id of the checkbox is not selectAllBoxes (Because this is a checkbox to select/deselect all checkboxes. So don't need to get value of this 'selectAllBoxes' checkbox), this will return the value of that checkbox
      return $("#type").val();
    }
  }).get(); //Getting those values and showing in the groupedTagsSerialNumber textbox
  $('#groupedTagType').val(searchIDs); //The above codes are mapping all the checked checkboxes values (value is the serial number of this tag in plannertags table) and showing in the groupedTagSerialNumber textbox

  var numberOfCheckedCheckBoxes = $("input:checked").length; //This is finding how many checkboxes checked by user
  if (numberOfCheckedCheckBoxes > 1) { //If anything more than 1, then MultiShipment button will show
    $("#multiShipment").show();
  } else {
    $("#multiShipment").hide();
  }
}); <
/script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <title>JS Bin</title>
</head>

<body>
  <form method="post" class="form-inline my-2 my-lg-0" id="navBarForm">
    <button type="submit" class="btn btn-info" name="multiShipment" id="multiShipment"> Multiple Actions</button>

    <input type="text" name="groupedTagType" id="groupedTagType" value="" readonly>
    <label class="checkboxContainer" id="selectAllCheckboxContainer">
          <input class="checkBoxes" type="checkbox" name="selectAllBoxes" id="selectAllBoxes" >
          <span class="checkmark"></span>
        </label>
  </form>
  <form method="post" id="qaForm">
    <div class="card" style="background-color:'.$vtagColour.'; color: '.$vtagTextColour.'; position: relative; border-color: black; !important ">
      <div class="card-body">

        <div class="row">
          <input type="text" name="srNum" id="srNum" value="'.$srNumber.'" hidden readonly>
          <input type="text" name="currentOa" id="currentOa" value="'.$assignedOperator.'" hidden readonly>
          <input type="text" name="type" id="type" value="PH" hidden readonly>
          <input type="text" name="tpCode" value="'.$idCode.'" hidden>
          <div class="toolTipShow serialNumberShow" title="Tag serial number" data-toggle="tooltip" data-placement="bottom"><small> <i class="fas fa-sort"></i> '.$srNumber.'</small></div>
          <div class="col-sm toolTipShow" title="Device Name" data-toggle="tooltip" data-placement="bottom"><i class="fab fa-500px"></i> '.$deviceName.'</div>
          <div class="col-sm toolTipShow" title="Type of Needle" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-atom"></i> '.$needleType.'</div>
          <div class="col-sm toolTipShow" title="ID Code" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-tag"></i> '.$idCode.'</div>
          <div class="col-sm toolTipShow" title="Customer Name" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
          <div class="col-sm toolTipShow" title="Total Pin Count" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-thumbtack"></i> '.$totalPinCount.'</div>
          <div class="col-sm toolTipShow" title="Start Date" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-tools"></i> '.$startDate.'</div>
          <div class="col-sm toolTipShow" title="Delivery Date" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-shipping-fast"></i> '.$deliveryDate.'</div>
          <div class="col-sm toolTipShow" title="Type of order" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-info-circle"></i> PH</div>
          <div class="col-sm toolTipShow" title="Current Operator" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-user"></i> '.$assignedOperator.'</div>
          <label class="checkboxContainer">
                          <input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="'.$srNumber.'">
                          <span class="checkmark"></span>
                        </label>
        </div>
      </div>


  </form>
  <br>
  <form method="post" id="qaForm">
    <div class="card" style="background-color:'.$vtagColour.'; color: '.$vtagTextColour.'; position: relative; border-color: black; !important ">
      <div class="card-body">

        <div class="row">
          <input type="text" name="srNum" id="srNum" value="'.$srNumber.'" hidden readonly>
          <input type="text" name="currentOa" id="currentOa" value="'.$assignedOperator.'" hidden readonly>
          <input type="text" name="type" id="type" value="ML" hidden readonly>
          <input type="text" name="tpCode" value="'.$idCode.'" hidden>
          <div class="toolTipShow serialNumberShow" title="Tag serial number" data-toggle="tooltip" data-placement="bottom"><small> <i class="fas fa-sort"></i> '.$srNumber.'</small></div>
          <div class="col-sm toolTipShow" title="Device Name" data-toggle="tooltip" data-placement="bottom"><i class="fab fa-500px"></i> '.$deviceName.'</div>
          <div class="col-sm toolTipShow" title="Type of Needle" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-atom"></i> '.$needleType.'</div>
          <div class="col-sm toolTipShow" title="ID Code" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-tag"></i> '.$idCode.'</div>
          <div class="col-sm toolTipShow" title="Customer Name" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
          <div class="col-sm toolTipShow" title="Total Pin Count" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-thumbtack"></i> '.$totalPinCount.'</div>
          <div class="col-sm toolTipShow" title="Start Date" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-tools"></i> '.$startDate.'</div>
          <div class="col-sm toolTipShow" title="Delivery Date" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-shipping-fast"></i> '.$deliveryDate.'</div>
          <div class="col-sm toolTipShow" title="Type of order" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-info-circle"></i>ML</div>
          <div class="col-sm toolTipShow" title="Current Operator" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-user"></i> '.$assignedOperator.'</div>
          <label class="checkboxContainer">
                          <input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="'.$srNumber.'">
                          <span class="checkmark"></span>
                        </label>
        </div>
      </div>

  </form>

</body>

</html>



mardi 29 septembre 2020

I want to trigger my custom checkbox with woocommerce shipping method checkbox

It works, but after when the form gets autoload for calculating price, it does not work anymore. Could anyone help me, please?

$('#shipping_method_0_flat_rate3').change(function() {
if ($(this).is(":checked")) {
$('.delivery-timeand-date-wholewrap').addClass('hide');
}
}); 



R shiny: checkboxGroupInput Insert a placemark between checkboxes

I need to insert text or a label between the checkboxes. How can this be done? enter image description here




Multiple check box not working when it's value same vuejs

When I check Apple it's all check Pineapple. When I unchecked Pineapple it's also unchecked Apple. both Tag id different. How can I check only one Apple instead of Pineapple?

var demo = new Vue({
  el: '#demo',
  data: {
    checkedNames: []
  },
  computed: {
    computedNames() {
      let names = this.checkedNames;
      return names.toString();
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
  <input type="checkbox" id="50" value="50" v-model="checkedNames">
  <label for="Apple">Apple</label>
  <input type="checkbox" id="51" value="51" v-model="checkedNames">
  <label for="Banana">Banana</label>
  <input type="checkbox" id="52" value="50" v-model="checkedNames">
  <label for="Pineapple">Pineapple</label>
  <br>
  <span>Checked names: </span>
  <span>Computed names (reversed order): </span>
</div>



Adding checkboxes and input field inside lightgallery not working

I have images with light gallery. If image is clicked it will trigger the light gallery it displays properly. But when I tried adding checkboxes and input field inside the light gallery it displays properly. But when I tried to get the value in the input field or catch the change event in the checkbox it doesn't seem to work.

Here is my html code.

                                <div class="row clearfix">
                                        <div class="col-sm-12 lightgallery">
                                            <a class="light-link" data-id="picKey" href=""
                                                data-sub-html='<div style="text-align: center;" class="galleryPics" >
                                                     <label class="fancy-checkbox">
                                                          <input type="checkbox" class="checkbox lg-check picKey  classicpicKey" name="flags[]"  value="0" data-name="picKey">
                                                          <span style="color: green; margin-right: 3px; font-size: 18px"><i></i><strong>Classic</strong></span>
                                                      </label>

                                                      <label class="fancy-checkbox">
                                                          <input type="checkbox" class="checkbox lg-check picKey  LockedpicKey" name="flags[]"  value="1" data-name="picKey">
                                                          <span style="color: brown; font-size: 18px"><strong>Locked</strong> <i></i></span>
                                                      </label>

                                                      <label class="fancy-checkbox">
                                                          <input type="checkbox" class="checkbox lg-check picKey HiddenpicKey" name="flags[]"  value="2" data-name="picKey">
                                                          <span style="color: red; font-size: 18px"><i></i><strong>Hidden</strong></span>
                                                      </label><br>

                                                     <label> <strong>Caption</strong> </label> <span class="required">*</span>
                                                     <input type="text" maxlength="100" class="form-control caption Cap" name="caption[]" data-name="Cap" value="" placeholder="Minimum of 100 letters." />
                                                 </div>'>

                                               <img class="img-fluid rounded img" style="object-fit: cover; width: 180px; height: 180px; " onerror="this.onerror=null; this.src=''" src="" data-toggle="tooltip" data-placement="top" alt="Thumbnail" data-original-title="Thumbnail" alt="">
                                               <input type="hidden" id="img" name="rotation[]" value="">
                                            </a>
                                        </div>
                                    </div>

And in my js, I tried to catch a simple event.

$('.lg-check').on('change', function() {
    console.log('s');
});



Formatting checkboxes in django

i'm trying to add some checkboxes into my form and to make them look nice. The thing is that when I use the output is like: Checkboxes

I would like to have them inline and readable, unfortunately using crispy forms renders them too close to each other.

I found that looping through elements will place them inline but still they're close to each other (their labels are much longer than shown below).


enter image description here

Where to put my css in this case?

filters.py:

    weights = django_filters.MultipleChoiceFilter(
        label = "Filter by weight",
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=OZ,
        method = 'filter_by_checkbox'
    )

Adding directly into static/css won't work :

   input[type=checkbox]
  {
   padding: 20px;
   margin: 20px 15px 0px 3px;
  }



UFT doesn't highlight and click a WebCheckBox of a pop-up

I'm using UFT to automatize some Web GUI Tests using VB Script, I have to click on a WebCheckBox of a pop up (called Dialog) but it doesn't work. I clicked the WebCheckBox and used object spy to drop the object and UFT pasted that line:

Browser("A").Window("B").WinObject("Internet Explorer_Server").Click

I understood that WinObject("Internet Explorer_Server") it's a generic object.

Could someone help me?




Unable to uncheck the check Box

I am using CheckboxListTile in for check box. It works good if selected : false. If selected is true then unable to un check it.

final checkBox = CheckboxListTile(
      contentPadding: EdgeInsets.all(0),
      title: Text("Remember Me", style: TextStyle(fontSize: 15.0)),
      selected: checkBoxState,
      value: checkBoxState,
      checkColor: Colors.white,
      activeColor: Colors.grey,
      controlAffinity: ListTileControlAffinity.leading,
      onChanged: (newValue) {
        setState(() {
          checkBoxState = newValue;
        });
      },
    );

This is the code what I am using.

Thanks in Advance,




How to create a switch / checkbox to turn on or off a chrome extension?

I am creating a chrome extension that has a content script that changes the style of dom text elements that it finds with regex. I want the popup of the extension to have switches that save state after closing.

For example - a turn on and off switches for the extension in the popup menu.

From what I've read online, I have to use chrome.storage to save the state of the checkboxes but I don't quite get how to read the state of the checkbox in the popup.js and how to store it.

HTML

 <input class = "power-switch" type="checkbox" id="toggle"/>
      <div class="toggle-wrap">
        <div style= "text-align: right;width: 190px;font-weight: bolder;">ON / OFF</div>
        <label class= "toggle-label"for="toggle"></label>
      </div>

CSS

*,
*::before,
*::after {
  transition: 400ms all ease-in-out 50ms;
  box-sizing: border-box;
  backface-visibility: hidden;
}

input[type="checkbox"] {
  display: none;
}

a{ color: rgba(43,43,43,1); text-decoration: none; padding: 10px; border-bottom: 2px solid rgba(43,43,43,1); }

a:hover{ background: rgba(43,43,43,1); color: rgba(255,255,255,1); }


/*Button is :CHECKED*/

input[type="checkbox"]:checked ~ div {
  background: rgba(73,168,68,1);
  box-shadow: 0 0 2px rgba(73,168,68,1);
}

input[type="checkbox"]:checked ~ div label {
  left: 27px;
  /* 110px */
  transform: rotate(360deg);
}


/*shared*/

.toggle-wrap,
.toggle-label {
  border-radius: 50px;
}


/*'un':checked state*/

.toggle-wrap {
  height: 26px;
  width: 50px;
  background: rgba(43, 43, 43, 1);
  position: relative;
  /* top: calc(50vh - 50px);
  left: calc(50vw - 100px); */

  box-shadow: 0 0 2px rgba(43,43,43,1);

}

.toggle-label {
  height: 20px;
  /* 80 */
  width: 20px;
  /* 80 */
  background: rgba(255, 255, 255, 1);
  position: absolute;
  top: 3px;
  /* 10 */
  left: 3px;
  /* 10 */
  cursor: pointer;
}

.toggle-label::before {
  content: '';
  height: 16px;
  /* 60 */
  width: 4px;
  position: absolute;
  top: calc(50% - 8px);
  /* - 30 px*/
  left: calc(50% - 2px);
  /*- 2.5px */
  transform: rotate(45deg);
}

.toggle-label::after {
  content: '';
  height: 4px;
  width: 16px;
  /* 60 */
  position: absolute;
  top: calc(50% - 2px);
    /*- 2.5px */
  left: calc(50% - 8px);
    /* - 30 px*/
  transform: rotate(45deg);
}

.toggle-label::before,
.toggle-label::after{
  background: rgba(43,43,43,1);
  border-radius: 5px;
}

/* pesduo class on toggle */

input[type="checkbox"]:checked ~ .toggle-wrap .toggle-label::before{
  height: 14px;
    /* 50px */
    top: calc(55% - 7px);
    /* 25px */
    left: calc(60% - 2.5px);
    background: rgba(73,168,68,1);
}
input[type="checkbox"]:checked ~ .toggle-wrap .toggle-label::after{
  width: 7px;
  /* 20px */
      top: calc(95% - 9px);
      /* -25px */
      left: calc(22.5% - 2px);
      /* 2.5px */
      background: rgba(73,168,68,1);

}

I'm not quite sure if the CSS is needed for the the example.




Get the value of checkboxes and push them to an array

I'm new to javascript and also jQuery but I'm working on a test and I need a method to count the checked checkboxes. I have 5 categories where I need the add the values (0 or 1). I made 5 vars and these are arrays (these are my categories of the test results). Every rows has two checkboxes (first row a01_a and a01_b). Here is a picture about the frontend: enter image description here

I want to push the values associated to the checkboxes into each array but I can't find out how.

This is my actual code:

   function myValue() {
 
            
    $('#a01_a').on('change', function(){
       this.value = this.checked ? 1 : 0;
        var v = this.value; //is it needed?
        vers.push(this.value);  
    }).change();


    $('#a01_b').on('change', function(){
       this.value = this.checked ? 1 : 0;
        var v = this.value; //is it needed?
        vers.push(this.value);  
    }).change();

    var vers = [];
    document.getElementById('test').innerHTML = vers; 

I need to have the values from 60 checkboxes into five arrays so this is just a part. I don't know how to push the value to a var outside the function.




Laravel Blade - How to make checkbox stay checked after submit

I want to create a feature to filter data. I use the checkbox to do this. But I want when the checkbox is selected and then the user submits to filter the data, the previously selected checkbox remains selected.

i tried to do it like this but it didn't work

<input type="checkbox" id="ac" name="ac" value="ac" @if(old('ac')) checked @endif>

my form method to submit this is GET.




Two way binding inside mat-table

I have a binding issue with mat-checkbox inside a mat-table. The dataSource of the table is a basic array of objects and each object has a selected boolean property. For some reason, the two way binding is not working and selected always return false when the click event is fired.

clients: Client[] = [
{ id: 1, name: `Client`, disabled: true, selected: false },
];

 onClientClick(client: Client) {
     console.log(client) // selected here is false
 }

<table mat-table [dataSource]="clients">
    <ng-container matColumnDef="client-name">
    <th mat-header-cell *matHeaderCellDef>header</th>
    <td mat-cell *matCellDef="let client">
        <mat-checkbox (click)="onClientClick(client)" [(ngModel)]="calque.selected"
        [disabled]="calque.disabled">
        
        </mat-checkbox>
    </td>
    </ng-container>
    <tr mat-row *matRowDef="let row; columns: displayedColumnsClients"></tr>
</table>



lundi 28 septembre 2020

Checking a checkbox by passing a value in a dict to fill_form in pypdftk

As the title says, I am passing a dict through fill_form with the pypdftk lib and am trying to check a checkbox with a value. I have tried to change the export value of the checkbox to see if that could affect it, but it hasn't. It seems the checkbox disappears when I pass an unaccepted value to it. I have changed the export value to 'Y'.

import pypdftk
import tkinter as tk
from tkinter.filedialog import asksaveasfilename

headers = ['1','2','3','4','checkbox']
values = ['a','b','c','d','Y']
short_dict = dict(zip(headers,y))
fName = r'file_name'
generated_pdf = pypdftk.fill_form(r'pdf_path',short_dict, asksaveasfilename(defaultextension=".pdf", initialdir="C:\\Desktop", filetypes=[('pdf file', '*.pdf')], initialfile=fName))

I'm still new to Python, so this is my attempt at an MCVE. Hopefully, all the data is there as I cannot share the full script or the pdf since they contain sensitive information.

I have tried to change the export value to different things, as I mentioned, none of which have worked. I have also tried 0/1, on/off, true/false and Yes/No, none of which worked.

Is there a way to pass a value through a dict into a pypdftk.fill_form() call and switch the checkboxes on?




Handle the list of dynamic checkboxes when the widget is added on button click in flutter

When clicking the add button, the same widget is replicated. The widget contains the list of checkboxes that are multi selectable. I am able to replicate the widget but I got problem to handle the checkboxes according to the index of the widget. In image below the checkbox checked state is replicated along with the new add widget.

enter image description here

I have implemented as follows:

Build the widget according to the addbutton click

  ListView.builder(
                  itemCount: counting,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (_, index) {
                    return _buildLayout(context, index);
                  });



                 //counting is number of **blueplus** icon is clicked
     Widget  _buildLayout(BuildContext context, int i) {       
      return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              addContainer,
              style: TextStyle(color: Colors.blueGrey),
            ),
            Container(
              width: 64.0,
              alignment: Alignment.center,
              child: IconButton(
                  onPressed: () => {i == 0 ? addRow(i) : deleteRow(i)},
                  icon: Icon(
                    i == 0
                        ? Icons.add_circle_outline
                        : Icons.remove_circle_outline,
                    color: i == 0 ? Theme.of(context).primaryColor : Colors.red,
                  )),
            ),
          ],
        ),        
        _buildCheckBoxes()
      ],
    );
  }



Widget _buildCheckBoxes() {
    return
        Container(         
            width: MediaQuery.of(context).size.width,
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  InkWell(
                      onTap: () {
                        showHide();
                      },
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text(
                              productionmareketway,
                              style: TextStyle(
                                  fontSize: 18, fontWeight: FontWeight.bold),
                            ),
                            showHidee
                                ? Icon(Icons.keyboard_arrow_up)
                                : Icon(Icons.keyboard_arrow_down)
                          ])),
                  SizedBox(
                    width: 20,
                  ),
                  showHidee
                      ? ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: widget.responseMarket.length,
                          itemBuilder: (ctx, i) {
                            return _buildSingleCheckBox(
                                context,
                                widget.responseMarket[i].name,
                                widget.responseMarket[i].isChecked,
                                widget.responseMarket[i].id,
                                widget.responseMarket[i].identifier,
                                i);
                          })
                      : Container()
                ])
           );
          } 
  



Widget _buildSingleCheckBox(BuildContext context, String name, bool isChecked,
      int i, String identifier, int j) {
    return Container(
      child: new CheckboxListTile(
        title: new Text(name),
        value: isChecked,
        activeColor: Theme.of(context).primaryColor,
        checkColor: Colors.white,
        onChanged: (bool value) {
          setState(() {
            widget.responseMarket[i].isChecked = value;
            print(value);
            print(i);

            widget._onChecked(
                value,
                widget.responseMarket[i].id,
                widget.responseMarket[i].name,
                widget.responseMarket[i].identifier,
                counting);
          });
        
        },
      ),
    );
  }

Add and delete widget function

addRow(int i) {
setState(() {
  counting = counting + 1;
});
} 

 deleteRow(int i) {
    setState(() {
      counting = counting - 1;
    });
  }

My callback function

 onMarketChecked(var value, int i, String name, String identifier, int j) {
setState(() {
  if (responseMarket[i].isChecked == true) {
    nonMarketRepated.add(name);
  } else {
    nonMarketRepated.remove(responseMarket[i].name);
  }
});
}



I need some help to write nested ngFor loops in Angular

I need some help to write nested ngFor loops in Angular. Need to have always 3 same answers(radio buttons) for a loop of questions (checkboxes). my code:

<ng-container *ngFor="let daType of daTypes"> 
 <mat-checkbox [name]="daType" [(ngModel)]="data[daType]"></mat-checkbox>
 <mat-radio-group id="daTAs" name="daTAs" [(ngModel)]="data[daType]">
   <ng-container *ngFor="let daTA of ansYNU">
     <mat-radio-button [value]="daTA">  </mat-radio-button>
   </ng-container>
 </mat-radio-group>
</ng-container>

daTypes and ansYNU are both arrays of strings. By writing it like this all radio buttons act like one - if I check "yes" in the first question, and then "no" in second, the first "yes" doesn't stay checked. Can someone see where the Problem is?




checkbox checked is not changing the data in repeater's footer template

I have a data for boolean control in repeater for checking. I created a footer template for sum price total in checked and unchecked items. But I only get all total of prices.linq query is qorking but checkbox is not firing in repeater footer even checkedbox change event changes the checked. How can I fix that issue?


 string durum;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFirmaOdemeler();
        }
    }    
 
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Footer)
    {
        var data = (DataRowView)e.Item.DataItem;

        var checkOnaySonuc = (e.Item.FindControl("checkOnaySonuc") as Label);
        if (string.IsNullOrEmpty(durum))
        {
            total = callFirma().AsEnumerable()
            .Sum(r => Convert.ToDouble(r["odemeTutari"]));
        }
        else
        {
            if (durum.Equals("1"))
            {
                total = callFirma().AsEnumerable()
                .Where(r => r.Field<string>("odemeOnayi") == "1")
            .Sum(r => Convert.ToDouble(r["odemeTutari"]));
            }
            else
            {
                total = callFirma().AsEnumerable()
                .Where(r => r.Field<string>("odemeOnayi") == "0")
            .Sum(r => Convert.ToDouble(r["odemeTutari"]));
            }
        }
    }
}

 protected void onaylandıGosterCheck_CheckedChanged(object sender, EventArgs e)
    {
        var chck = (CheckBox)sender;
        string durum = chck.Checked ? "1" : "0";
    }

and this is aspx

<FooterTemplate>
                                                <tfoot>
                                                    <tr>
                                                        <td>
                                                            <asp:Button ID="cleanTable" Text="Temizle" runat="server" CommandName="Clean" CssClass="btn btn-info" />
                                                        </td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td>
                                                            <asp:Label ID="checkOnaySonuc" Text="deneme" runat="server" />
                                                        </td>
                                                        <td></td>

                                                        <td>
                                                            <asp:CheckBox ID="onaylandıGosterCheck" Text="Onaylandı Göster" runat="server" CssClass="checkbox checkbox-info" AutoPostBack="true" OnCheckedChanged="onaylandıGosterCheck_CheckedChanged" />
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                    </tr>
                                                </tfoot>


                                            </FooterTemplate>



how to set multi data from checkbox in react?

here in my code i have 5 checkboxes that i want to push their values if they were checked but when i tick a checkbox and then tick another one an error displayes that says TypeError: Cannot read property 'value' of null

and this is my code:

import React, { useState, useEffect } from 'react';
import Label from '../../styles/Label';

function AlertReminder() {
  const [selectedReminders, setSelectedReminders] = useState([]);

  useEffect(() => {
    console.log(selectedReminders);
  }, [selectedReminders]);

  const remindersList = '1 hour before,12 hour before,24 hour before,48 hour before,1 week ago'.split(',');
  console.log(remindersList);
  const changeHandler = (e) => {
    if (selectedReminders.includes(e.target.value)) {
      selectedReminders.splice(selectedReminders.indexOf(e.target.value), 1);
      console.log(selectedReminders);
    } else {
      setSelectedReminders(selectedReminders => [...selectedReminders, e.target.value]);
      console.log(selectedReminders);
    }
  };

  return (
    <div>
      <Label>Alert Reminders:</Label>

      <form>

        {
        remindersList.map(
          (c) => (
            <label>
              {c}
              <input type="checkbox" value={c} onChange={changeHandler} />
            </label>
          )
        )
      }
      </form>
    </div>
  );
}

export default AlertReminder;



dimanche 27 septembre 2020

How to create Rectangle custom Radio Button or CheckBox?

How can I create a custom checkbox like the given image? Should I do it with radio button as the filling of color looks like a radio button? If yes, how to do it using radio button?

Custom checkbox




ASP.NET| checkbox's "checked=true" is not setted in the right checkbox

I'm working on a simple multi-staged registration page for a site I'm building, and I give the user the choice of choosing programs/programming languages he knows using checkboxes: enter image description here

but when I hit the "next" button, in order to go to the next stage, the checkbox I checked isn't set to true, but checkbox no. 18 is set to true(although I didn't check it)

I'm certain it has something to do with the stage before this one, in which I'm building dynamically radio buttons in which the user is choosing his profession (such as Artist, singer and etc'). there are 17 radio buttons, and they are somehow interfering with the next stage, in which the checkbox's checked values are only starting from checkbox no. 18 as I mentioned earlier.

here is some of the code:

 else if (int.Parse(ViewState["DivID"].ToString()) == 2)
            {
                // save the Birthday Date, Language and country of the user.
                ViewState["year"] = int.Parse(DropDownYear.SelectedValue);
                ViewState["month"] = int.Parse(DropDownMonth.SelectedValue);
                ViewState["day"] = int.Parse(DropDownDay.SelectedValue);
                ViewState["Language"] = int.Parse(langDropDown.SelectedValue);
                ViewState["Country"] = int.Parse(CountryDropDown.SelectedValue);
                // ---------------------------------------------
                // change from part 2 of the registration to part 3
                registrationP2.Visible = false;
                BindProfessions(radios, Page);
                registrationP3.Visible = true;
                radios.Visible = true;
            }
            else if (int.Parse(ViewState["DivID"].ToString()) == 3)
            {
                // change from part 3 of the registration to part 4
                ViewState["Profid"] = CheckRadio(radios);
                registrationP3.Visible = false;
                BindKnowledge(CheckboxCon, Page);
                registrationP4.Visible = true;
                CheckboxCon.Visible = true;
                // ---------------------------------------------
                //next.Visible = true;
            }
            else if(int.Parse(ViewState["DivID"].ToString()) == 4)
            {
                List<int> v = GetCheckBox(CheckboxCon);
                ViewState["Knowids"] = GetCheckBox(CheckboxCon);
            }

Binding methods:

public static void BindProfessions(HtmlControl ctrl, Page thispage)
    {
        List<Profession> Plist = Profession.GetProfessionList();
        foreach (Profession p in Plist)
        {
            HtmlInputRadioButton rd_button = new HtmlInputRadioButton();
            const string GROUP_NAME = "Professions";
            rd_button.Name = GROUP_NAME;
            string LinkID = "P" + p.ProfessionID.ToString();
            rd_button.Attributes["id"] = LinkID;
            RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
            userprofession.imgP = p.ProfPath;
            userprofession.fieldName = p.ProfName;
            userprofession.IDnum = p.ProfessionID;
            userprofession.RadioName = LinkID;
            userprofession.EnableViewState = false;
            rd_button.EnableViewState = false;
            ctrl.Controls.Add(rd_button);
            rd_button.Value = p.ProfessionID.ToString();
            ctrl.Controls.Add(userprofession);
        }
    }


    public static void BindKnowledge(HtmlControl ctrl, Page thispage)
    {
        List<Knowledge> Plist = Knowledge.RetKnowledgeList();
        foreach (Knowledge p in Plist)
        {
            HtmlInputCheckBox rd_button = new HtmlInputCheckBox();
            const string GROUP_NAME = "knowledge";
            rd_button.Name = GROUP_NAME;
            string LinkID = "Know" + p.ProgramID.ToString();
            rd_button.Attributes["id"] = LinkID;
            rd_button.Value = p.ProgramID.ToString();
            RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
            userprofession.imgP = p.ProgPath;
            userprofession.fieldName = p.PName;
            userprofession.IDnum = p.ProgramID;
            userprofession.RadioName = LinkID;
            userprofession.EnableViewState = false;
            rd_button.EnableViewState = false;
            ctrl.Controls.Add(rd_button);
            ctrl.Controls.Add(userprofession);
        }
    }

checking methods for both radios and checkbox :

public static int CheckRadio(HtmlControl ctrl)
    {
        try
        {
            int counter = 0;
            int id = -1;
            foreach (Control rdButton in ctrl.Controls)
            {
                if (rdButton is HtmlInputRadioButton)
                {
                    HtmlInputRadioButton bu = (HtmlInputRadioButton)rdButton;
                    if (bu.Checked)
                    {
                        counter++;
                        id = int.Parse(bu.Value);
                        
                    }
                }
            }
            if (counter > 1)
            {
                return -1;
            }
            return id;
        }
        catch (Exception e)
        {
            return -1;
        }
    }

    public static List<int> GetCheckBox(HtmlControl ctrl)
    {
        List<int> id_list = new List<int>();
        foreach (Control rdButton in ctrl.Controls)
        {
            if (rdButton is HtmlInputCheckBox)
            {
                HtmlInputCheckBox bu = (HtmlInputCheckBox)rdButton;
                if (bu.Checked)
                {
                    id_list.Add(int.Parse(bu.Value));
                }
            }
        }
        return id_list;
    }
}

I should mention that after I create the dynamic usercontrols and checkbox/radion buttons, I'm creating them again at postback in protected void Page_Load.

I'm stuck on this for days, and I don't know from where the problem emanates, is it because of ViewState, or the way I'm creating the controls... I really don't know.

Thanks in advance, Idan.




Checking when there is already approved checkbox in the gridview in C#

I have a checkbox in a gridview row.

I know how to disable it using RowDataBound and using a database value as a condition to disable or not.

protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.DataItem != null)
        {
            int status = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "tstatus"));
            CheckBox chkRow = (CheckBox)e.Row.FindControl("chkRow");

            if (status > 0)
            {
                chkRow.Enabled = false;
                chkRow.Checked = true;
                chkRow.ToolTip = "Approved";
            }
        }
    }
}

my problem is checking when there is already approved checkbox in the gridview

foreach (GridViewRow row in gvProducts.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (CheckBox)(row.Cells[0].FindControl("chkRow"));

        if (chkRow.Checked && chkRow.ToolTip == "to be approved")
        {
            int oIndividualID = Convert.ToInt32((gvProducts.DataKeys[row.RowIndex].Value));

            using (MySqlConnection myConnectionString =
              new MySqlConnection(ConfigurationManager.ConnectionStrings["cn2"].ConnectionString))
            {
                using (MySqlCommand cmd =
                    new MySqlCommand(sql, myConnectionString))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection.Open();
                    cmd.CommandText = "SP";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("tid", oIndividualID.ToString());
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    Bindgrid();
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Approved');", true);
                }
            }
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Not checkbox selected');", true);
        }
    }
}

in this case, i.e. when there is already a grid row with checkbox selected, if I try to select a new checkbox the return on the browser is

'Not checkbox selected'

even if the database table updates correctly

this is the page markup

<asp:TemplateField HeaderText="Select">
    <ItemTemplate>
        <asp:CheckBox ID="chkRow" runat="server"
            ToolTip="to be approved" />
    </ItemTemplate>
</asp:TemplateField>

Can anyone help please?




php in array function doesn't return true

I am a beginner in PHP, I am stuck with this problem. I am doing this for my checkbox.

I have a result from my database with the following data which is stored in this variable print_r($adoptive_parent->sector); with a type of string:

["Solo Parent","Indigenous Person","PWD"] 

now I tried using the explode function:

$checkbox_array = explode(",", $adoptive_parent->sector);

then i tried something like this:

if (in_array("Solo Parent", $checkbox_array)) {
     echo "true";
}else {
    echo "false";
}

why is this return false? can anyone help me? i want it to apply with my checkbox like this:

<label class="checkbox-inline"><input type="checkbox" name="sector[]" value="Solo Parent" <?php if(in_array("Solo Parent", $checkbox_array)){ echo " checked=\"checked\""; } ?> >Solo Parent</label>
<label class="checkbox-inline"><input type="checkbox" name="sector[]" value="Indigenous Person" <?php if(in_array("Indigenous Person", $checkbox_array)){ echo " checked=\"checked\""; } ?> >Indigenous Person</label>
<label class="checkbox-inline"><input type="checkbox" name="sector[]" value="PWD" <?php if(in_array("PWD", $checkbox_array)){ echo " checked=\"checked\""; } ?>>PWD</label>
      



samedi 26 septembre 2020

Change Label Background Color When Checkbox Checked

I need help about this code please, how can i make the whole label's background color change when i check the checkbox ? I want the whole td or change it's background when the checkbox checked

I think I can do it by using css only

https://codepen.io/Haitham1000/pen/ZEWPMeY

<table class="choices">
  <tr>
    <td>
      <div class="checkbox">
        <label><input type="checkbox" value="">All categories</label>
      </div>
    </td>

    <td>
      <div class="checkbox">
        <label><input type="checkbox" value="">1</label>
      </div>
    </td>

    <td>
      <div class="checkbox disabled">
        <label><input type="checkbox" value="" disabled>2</label>
      </div>
    </td>

    <td>
      <div class="checkbox">
        <label><input type="checkbox" value="">3</label>
      </div>
    </td>

    <td>
      <div class="checkbox">
        <label><input type="checkbox" value="">4</label>
      </div>
    </td>
  </tr>
</table>



I need to check the checkbox with javascript

<div class="checkbox_container">
  <label for="acord_regulament" class="checked">
    Am luat la cunoștință  
    <a href="https://www.bereciucas.ro/static/pdf/regulament_premii.pdf"
         target="_blank">
      Regulamentul Oficial al Campaniei
    </a>.
  </label>
  <input type="checkbox" name="acord_regulament" value="1" 
          id="acord_regulament"
          class="validate[required] req_checkbox noinputError"
          tabindex="6">
</div>

Am luat la cunoștință Regulamentul Oficial al Campaniei. * Optiune obligatorie

I need to check that box with javascript. But when it is checked the code changes to this.

Am luat la cunoștință Regulamentul Oficial al Campaniei. '''


How to tie prices to individual form times?

I'm making a food ordering form wherein the user can select multiple food items, and then the quanitity of each individual item.

The way I'm tackling this is by creating an accordion with multiple checkboxes and adding a quantity field to each checkbox (which shows up when the checkbox is checked). So far, I've only been able to fetch the name of the item and quantity. Here's how the code for the checkboxes looks like right now:

<!-- Option1 -->
<div class="form-row">
  <div class="form-group col-md-8">
    <div class="form-check">
      <input class="form-check-input showman" type="checkbox" name="items[1][chosen]" onchange="showqt()" value="Button Chicken Amritsari" id="c1">
      <label class="form-check-label" for="c1">
        Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
      </label>
    </div>
  </div>
    <div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">
      <!-- <label for="qtcounter">Quantity:</label> -->
      <div class="input-group" id="qtcounter">
        <input type="button" value="-" class="button-minus" data-field="items[1][quantity]">
        <input type="number" step="1" max="" value="1" name="items[1][quantity]" class="quantity-field">
        <input type="button" value="+" class="button-plus" data-field="items[1][quantity]">
      </div>
    </div>
</div>
<!-- Option 1 ends -->

As you can see, I'm using associative arrays to read both the name and the quantity. The problem is, I also need to (dynamically) calculate the order total. That would mean attaching a numeric value(the price) to each checkbox but the checkbox value is already set to the name of the item.

Is there any way I can work around this? I need to show the total right before the submit button, on an order review page that'll come up after submitting the form and I'll need to save this value in a database along with the other form details, of course.




Custom listview adapter with textview, checkbox and image button

Hello everyone, there are certainly numerous examples online, but I can't find a suitable example for my code. I hope someone can help. So I just want the existing functions to be retained, but also to save the CheckboxStatus. It would be great if someone could tell me how this works with a code example. LG

row:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:text="Example"
        android:textSize="20sp" />

    <ImageButton
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="1dp"
        android:layout_marginEnd="2dp"
        android:layout_marginRight="2dp"
        android:background="#F44336"
        android:onClick="deleteTask"
        android:src="@android:drawable/ic_menu_delete" />

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="2dp"
        android:layout_marginEnd="36dp"
        android:focusable="false"
        android:focusableInTouchMode="false" />


</RelativeLayout>

MainActivity:

    private void loadTaskList() {

        ArrayList<String> taskList = dbHelper.getTaskList();
        if (mAdapter == null) {
                    mAdapter = new ArrayAdapter<String>(this, layout.row, id.task_title, taskList);
            lstTask.setAdapter(mAdapter);
                    lstTask.getAdapter().getCount();
            Toast.makeText(getApplicationContext(), "Aufgabenanzahl:" + lstTask.getAdapter().getCount(), Toast.LENGTH_LONG).show();
            textView3.setText("" + lstTask.getAdapter().getCount());

            } else {
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        Drawable icon = menu.getItem(0).getIcon();
        icon.mutate();
        icon.setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_IN);

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case  id.action_add_task:
                final EditText taskEditText = new EditText(this);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Aufgabe hinzufügen");
                builder.setMessage("Was möchtest du als nächstes tun?");
                builder.setView(taskEditText);
                builder.setPositiveButton("Hinzufügen", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    String task = String.valueOf(taskEditText.getText());
                                    dbHelper.insertNewTask(task);
                                    loadTaskList();
                                lstTask.getAdapter().getCount();
                                textView3.setText("" + lstTask.getAdapter().getCount());
                                Toast.makeText(getApplicationContext(), "Aufgabenanzahl:" + lstTask.getAdapter().getCount(), Toast.LENGTH_LONG).show();
                                }
                             });

                builder.setNegativeButton("Zurück", null);
                AlertDialog dialog = builder
                        .create();
                dialog.show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void deleteTask(View view) {
        View parent = (View) view.getParent();
        TextView taskTextView = (TextView) parent.findViewById(id.task_title);
        Log.e("String1", (String) taskTextView.getText());
        String task = String.valueOf(taskTextView.getText());
        dbHelper.deleteTask(task);
        loadTaskList();
        lstTask.getAdapter().getCount();
        Toast.makeText(getApplicationContext(), "Aufgabenanzahl:" + lstTask.getAdapter().getCount(), Toast.LENGTH_LONG).show();
        textView3.setText("" + lstTask.getAdapter().getCount());

        }

Database:

public class Dbhelper extends SQLiteOpenHelper {

    private static final String DB_NAME="EDMTDev";
    private static final int DB_VER = 1;
    public static final String DB_TABLE="Task";
    public static final String DB_COLUMN = "TaskName";
    public static final String DB_ANZAHL = "Anzahl";


    public Dbhelper(Context context) {
        super(context, DB_NAME, null, DB_VER);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = String.format("CREATE TABLE %s (ID INTEGER PRIMARY KEY AUTOINCREMENT,%s TEXT NOT NULL);",DB_TABLE,DB_COLUMN,DB_ANZAHL);
        db.execSQL(query);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query = String.format("DELETE TABLE IF EXISTS %s",DB_TABLE);
        db.execSQL(query);
        onCreate(db);

    }



    public void insertNewTask(String task){
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DB_COLUMN,task);
        db.insertWithOnConflict(DB_TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }

    public void deleteTask(String task){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(DB_TABLE,DB_COLUMN + " = ?",new String[]{task});
        db.close();
    }


    public ArrayList<String> getTaskList() {
        ArrayList<String> taskList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(DB_TABLE, new String[]{DB_COLUMN}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            int index = cursor.getColumnIndex(DB_COLUMN);
            taskList.add(cursor.getString(index));
        }
        cursor.close();
        db.close();
        return taskList;
    }

}



How to delete rows in a QtableWidgit(Pyqt5) using Python which are checked?

I'm trying to delete rows which are checked in column 4: TodoApp

Here is a code:

 def AddActivity(self,columns):
    task = self.Input_task.text()
    date = self.date.text()
    duedate = self.due_date.text()

    chkBoxItem = QtWidgets.QTableWidgetItem()
    chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
    chkBoxItem.setData(LastStateRole, chkBoxItem.checkState())

       
    rowPosition = self.Activities_table.rowCount()
    self.Activities_table.insertRow(rowPosition)

    self.Activities_table.setItem(rowPosition, 0, QtWidgets.QTableWidgetItem(task))
    self.Activities_table.setItem(rowPosition, 1, QtWidgets.QTableWidgetItem(date))
    self.Activities_table.setItem(rowPosition, 2, QtWidgets.QTableWidgetItem(duedate))
    self.Activities_table.setItem(rowPosition, 3, chkBoxItem)

Input data into QtableWidgit

Clear all checked button:

self.clear_all_checked_button.clicked.connect(self.delete)

Delete Button

And finally function which deletes all checked rows:

def delete(self):
    for i in range(self.Activities_table.rowCount()):
        item = self.Activities_table.item(i,3)
        
        if item.checkState() == QtCore.Qt.Checked:
           it = self.Activities_table.item(i,3)
           del it

Delete Function

However I receive this message: in delete if item.checkState() == QtCore.Qt.Checked: AttributeError: 'NoneType' object has no attribute 'checkState'

Is there any way to fix this code so it works properly.




Reporting Checkboxes Question in Google Data Studio

my name is Bella

I want to create a function name 'result' (google apps script) to reporting my checkboxes question but when i run it, gsheet say :"TypeError: Cannot read property "length" from undefined." Can anyone can help me to fix it or help with your code.

I use step in : https://support.google.com/datastudio/thread/41265682?hl=en




How to select one checkbox at a time in swift?

I have implemented four checkboxes. Now, I want to select one checkbox at a time and if there's other checkbox selected, I want it deselected at the same time.

This is what I've tried but it selects all the checkboxes.

@IBAction func checkboxTapped(_ sender:UIButton){               
     if (sender.isSelected == false){
          sender.setImage(UIImage(named: "selected"), for: UIControl.State.normal)
          sender.isSelected = true;

     } else {
          sender.setImage(UIImage(named: "unselected"), for: UIControl.State.normal)
          sender.isSelected = false;
     }
}

Here, I have given same IBAction connection to all the checkboxes.




vendredi 25 septembre 2020

Flask isn't getting pre-selected active checkbox [duplicate]

Using Flask, I'm trying to retrieve the option selected by the user. I want one of the buttons to be the default selection, being active when the user accesses the webpage. However, using class="active", is not enough, as request.form returns empty if the user accepts the pre-selection choice and does not click on it.

Using <link href="/static/styles/bootstrap.min.css" rel="stylesheet">, option 1 shows as pre-selected:

enter image description here

Without using <link href="/static/styles/bootstrap.min.css" rel="stylesheet">, it is possible to see that there is no real pre-section:

enter image description here

How to make a default selection of a checkbox, to be able to later request its value?

Full codes:

app.py

from flask import Flask, render_template, request, redirect

app=Flask(__name__)
app.secret_key = "secret key"

@app.route('/')
def upload_form():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def index():
    global uniqueId, nomeArquivos

    if request.method == 'POST':
    
        print(request.form)
    
        return redirect('/')

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="/static/styles/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <form method="post" action="/" enctype="multipart/form-data">
        
        <div class="btn-group" data-toggle="buttons">
            <label class="btn btn-primary active">
            <input type="radio" name="options" id="option1" value="option1"> option1
            </label>
            <label class="btn btn-primary">
            <input type="radio" name="options" id="option2" value="option2"> option2
            </label>
        </div>
    
        <input type="submit" value="Submit">
        
    </form>
</body>
</html>



a few checkboxes with a click function to confirmation and after it should display a button for PayPal

my website visitors have to agree to some conditions before they pay. only then should the paypal button appear. unfortunately I don't know how to add multiple buttons to my code. one goes but how others agree? Please help

<head>
    <center><meta charset="utf-8">
    <style type="text/css">
input[type=checkbox],label{
    cursor: pointer;
}
#formdiv{
    padding-top: 30px;
}
    </style>
</head>
<body>


<input type="checkbox"  class= "larger" id="AGB" <name="AGB" <br> <strong></name>AGB</name></strong>

<style>
      input.larger {
        transform: scale(126px);
        margin: 15px;
      }
    </style>
    
    <input type="checkbox"  class= "larger" id="Wid" <name="Widerruf" <br> <strong></name>Widerruf</name></strong>

<style>
      input.larger {
        transform: scale(126px);
        margin: 15px;
      }
    </style>

<center><div id="formdiv">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
        <input type="hidden" name="cmd" value="_s-xclick">
        <input type="hidden" name="hosted_button_id" value="AQPGG3BXQ7JMJ">
        <input type="image" id="submitimage" src="https://www.paypalobjects.com/de_DE/DE/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="Jetzt einfach, schnell und sicher online bezahlen – mit PayPal.">
        <img alt="" border="0" src="https://www.paypalobjects.com/de_DE/i/scr/pixel.gif" width="1" height="1">
    </form></center>
</div>

<script>
    function button_klick(ids) {
        if (document.getElementById('AGB').checked) {
            document.getElementById('submitimage').style.width = '126px';
            document.getElementById('submitimage').style.height = '47px';
        }
        else {
            document.getElementById('submitimage').style.width = '0px';
            document.getElementById('submitimage').style.height = '0px';
        }
    }
    document.getElementById('AGB').onclick = function() {
        button_klick();
    };
    button_klick(); // 
</script>

</body>

my website visitors have to agree to some conditions before they pay. only then should the paypal button appear. unfortunately I don't know how to add multiple buttons to my code. one goes but how others agree? Please help




Checking checkboxes from colon-delimited string

Our online form receives a colon-delimited string from the database for one of our fields. For example, we have a checkbox group called "Favorite Fruits", which contains eight checkboxes:

 Apples - AP
 Bananas - BA
 Blueberries - BL
 Cherries - CH
 Grapes - GR
 Oranges - OR
 Raspberries - RA
 Strawberries - ST

Let's say a user submits a form with three checkboxes checked: Cherries, Grapes and Strawberries. When users submit the form, the 'fruits' field receives the following: CH,GR,ST. When the user revisits the page, instead of comma-separated, it's received like this CH::GR::ST. For this example, I'm trying to figure out how to check the checkboxes so that Cherries, Grapes and Strawberries are checked on page load.

Here's what I have so far:

   <div id='fruits'>
    <input type='checkbox' id='AP' value='Apples' />Apples<br />
    <input type='checkbox' id='BA' value='Bananas' />Bananas<br />
    <input type='checkbox' id='BL' value='Blueberries' />Blueberries<br />
    <input type='checkbox' id='CH' value='Cherries' />Cherries<br />
    <input type='checkbox' id='GR' value='Grapes' />Grapes<br />
    <input type='checkbox' id='OR' value='Oranges' />Oranges<br />
    <input type='checkbox' id='RA' value='Raspberries' />Raspberries<br />
    <input type='checkbox' id='ST' value='Strawberries' />Strawberries<br />
   </div> 

    var faveFruits = ['CH','GR','ST'];

    $("#fruits").find('[id=' + faveFruits.join('], [id=') + ']').prop("checked", true);

That works fine, because of the way the faveFruits variable/array is defined. It actually loads on the page like this:

    var faveFruits = CH::GR::ST

https://jsfiddle.net/Codewalker/mw9746pq/12/




jeudi 24 septembre 2020

React input checkbox checked

I have use React-redux and styled components for my app. I store my initial state theme as a string which is light and dark. then I connect my styled components intial light theme and dark theme in my root app. My dark mood works fine when i used select options but when i used input checkbox it does not work. I never used input checkbox, after reading couple example I used checked and put my initial theme(which is coming from my redux store), then in my handleChange I did, if the event target has dark then dispatch the dark theme. But nothing happening in that handle change. don't know what i am doing wrong.

Here is my toggle component

import React, { useState } from 'react';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { appSettings } from '../../state/appSettings';
import { TRootState } from '../../state/index';

export default function Toggle({ }: IProp) {
  const dispatch = useDispatch();
  const { "appSettings": appSettingState } = useSelector((state: TRootState) => state);
  const { theme } = appSettingState || {};
  console.log(theme); // inital state which is "light". 

  return (
    <>
      {/*  This input checkbox  does not work */}
      <CheckBoxWrapper>
        <CheckBox
          onChange={(e) => { // This function does not work
            e.target.value === `dark` ?
              dispatch(appSettings?.actions?.enableDarkTheme()) :
              dispatch(appSettings?.actions?.enableLightTheme());
          }}
          id="toggleSwitch"
          type="checkbox"
          Checked={theme === `light`}
        />
        <CheckBoxLabel htmlFor="toggleSwitch" />
      </CheckBoxWrapper>
      <br></br>

      {/*  THIS SELECT OPTIONS WORK FINE. AND I CAN GET DARK AND LIGHT THEME */}
      <h2>Theme</h2>
      <select
        name="theme"
        id="theme-select"
        value={theme}
        onChange={(e) => {
          if (e.target.value === `dark`) {
            dispatch(appSettings?.actions?.enableDarkTheme());
          } else {
            dispatch(appSettings?.actions?.enableLightTheme());
          }
        }}
      >
        <option value="dark">Dark</option>
        <option value="light">Light</option>
      </select>
    </>
  );
}

// This toogle input styled
const CheckBoxWrapper = styled.div`
position: fixed;
top:10px;
right:10px;
`;

const CheckBoxLabel = styled.label`
  position: absolute;
  top: 0;
  left: 0;
  width: 42px;
  height: 26px;
  border-radius: 15px;
  background: #bebebe;
  cursor: pointer;
  &::after {
    content: "";
    display: block;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    margin: 3px;
    background: #ffffff;
    box-shadow: 1px 3px 3px 1px rgba(0, 0, 0, 0.2);
    transition: 0.2s;
  }
`;
const CheckBox = styled.input`
  opacity: 0;
  z-index: 1;
  border-radius: 15px;
  width: 42px;
  height: 26px;
  &:checked + ${CheckBoxLabel} {
    background: #4fbe79;
    &::after {
      content: "";
      display: block;
      border-radius: 50%;
      width: 18px;
      height: 18px;
      margin-left: 21px;
      transition: 0.2s;
    }
  }
`;



Making all checkboxes mandatory with submit button going to a URL

How do I create a form with all checkboxes being mandatory and a submit button going to a URL? I've searched all over and all the examples just do one or the other. I've found samples that can make checkboxes mandatory, and samples that make submit button go to URL, but not both.

Help.




React native elements checkbox selecting multiple items

So I am working on a project where I am using react native elements checkbox and I finally got it working where it does not select all of the fetched items at one. It only selects one time at a time, and if I try to select another item it will unselect the first item and select the second. But now it will not allow me to select multiple items at once. I have searched google, on this platform, and also reddit and I can not find any solutions.

Here is my code

constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            checked: null,
        }
    }

    render() {

        const  { navigation } = this.props;
        const cust = navigation.getParam('food', 'No-User');
        const other_param = navigation.getParam('otherParam', 'No-User');
        const cust1 = JSON.parse(cust);
    
        const data = cust1;
        console.log(data);

        return (
            <View style={styles.container}>
                <BackButtonMGMT navigation={this.props.navigation} />

                <FlatList
                    data={data}
                    extraData={this.state}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={({ item, index }) => (
                        <CheckBox
                        center 
                        titleProps=
                        title={item}
                        iconRight
                        checked={this.state.checked == item}
                        size={30}
                        onPress={() => this.setState({checked: item})}
                        containerStyle={styles.checkBox}
                        />
                        
                    )}
                />

            </View>
        )
    }

I have tried to change the checked line within the CheckBox. I have tried to checked={!!item.checked} and it does not work. I have tried checked={!this.state.checked} and this does not work either. Has anyone came across this problem, and if so how did you solve this?




Ion-checkbox event not working properly on else

I have a problem with my ion-checkbox event function. The else part its not working properly when I try to split some ingredients from a groceryList that I have. Splice its working but its removing the common ingredients from both recipes that I have.

What I am trying to achieve is : when i uncheck 1 recipe i need the ingredients from that recipe to not be in the groceryList anymore , but to keep the common ingredients from the recipes and also when I tick them back to see the correct amounts again.

My code looks like this :

else {
      let tickedRecipe = ev.detail.value;
      for (let recipe of this.recipes) {
        if (recipe.name === tickedRecipe) {
          recipe.ingredients.forEach((el) => {
            let matchedIng = this.groceryList.find(function (foundIng) {
              return foundIng.name === el.name;
            });
            if (matchedIng) {
              let index = this.groceryList.findIndex(
                (ingF) => ingF.name === matchedIng.name
              );
              this.groceryList.splice(index, 1);
            }
            let matchedH = this.untickedGroceryList.find(function (
              foundIngred
            ) {
              return foundIngred.name === el.name;
            });

            if (matchedH) {
              matchedH.quantity === matchedH - el.quantity;
              console.log(matchedH);
            }
          });
        }
      }
    }

This is looks like when both recipes are ticked

This is how it looks when I untick 1

As you can see when I untick one 2 of the ingredients that are in both recipes are gone , and I want to keep them separately if possible. How can I achieve that ? Thanks for help




How to implement checkbox in swift?

I am using this code for implementing checkbox but it is not working. Can anyone tell where I went wrong?

@IBAction func tapped(_ sender: UIButton){ if (checkBox.isSelected == false){

            checkBox.setImage(UIImage(named: "selected"), for: .normal)
            checkBox.isSelected = true;


        } else {
            checkBox.setImage(UIImage(named: "unselected"), for: .normal)
            checkBox.isSelected = false;
        }
    }



Column Title for auto generated checkbox column in ListGrid SmartGWT

How can we set the column title for the auto-generated checkbox column using the following property in the ListGrid?

thisGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);

We don't want the selectAll button in the header, so we have removed that using cowGrid.setCanSelectAll(false);




getElementById is not working if a checkbox's value is passed as variable

Here is JS function. this function is an event handler for a checkbox. so the element is the checkbox.

function updateSelect(element) {
        // this works
        document.getElementById("file_update_" + 1).disabled = !element.checked;
        // this does not works. the element.value is also 1
        document.getElementById("file_update_" + element.value).disabled = !element.checked;
}

the console has the following error.

Uncaught TypeError: Cannot set property 'disabled' of null
    at updateSelect (<anonymous>:21:75)
    at HTMLInputElement.onchange (updateuser:1)

any idea....what is unique about the element.value?




Change Checkbox in Javascript

how I can change this CheckBox in javascript? Checkboxes doesnt have Id or something :/

<ul class="DirectionFilter__filterlist__288E1AGnOl">

<li>
<label>
<input type="checkbox">Eingehend
</label>
</li>

<li>
<label>
<input type="checkbox" checked="">Ausgehend
</label>
</li>

</ul>

Thanks Guys.




mercredi 23 septembre 2020

Laravel: How to save checkbox value

I get this error, when I submit the form

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'onloan' cannot be null

Please help. Sorry for the noob question. I've been searching but the examples are different.

edit.blade.php

<div class="form-group">
  <input type="checkbox" class="" id="onloan" value="1" >
  <label for="onloan">On Loan</label>
</div>

controller

    public function update(Request $request, Item $item)
    {
        $item->update([
            'name' => $request->name,
            'description' => $request->description,
            'barcode' => $request->barcode,
            'onloan' => $request->onloan //Not Working
        ]);
    }



Laravel: How to set value of Checkbox from database

The checkbox does not take the value from the database. Help please. Thank you.

edit.blade.php

                                    <div class="form-group">
                                        <input type="checkbox" class="" id="onloan" value="">
                                        <label for="onloan">On Loan</label>
                                    </div>



Adobe Acrobat javascript loop to erase every 2nd and 3rd checkbox

I'm attempting to convert a handful of wingdings to checkbox form fields within Adobe Acrobat, and then erase each 2nd and 3rd checkbox with a loop akin to this.eraseField(["CheckBox1, CheckBox2, CheckBox4, CheckBox5]); and so on for all checkboxes.

I've hacked together this code, but loops are my weakness.

for (var i = 0; i < this.numFields; i++) {
    var f = this.getField(this.getNthFieldName(i));

    if (f != null && i % 3 != 0) {
    this.removeField("f");
    }
}

I know I'm doing this wrong, I cannot figure out how to correctly set up this loop. Any help would be appreciated.




Problem with checkbox function event ionic

I have a problem with my event on ion-checkbox.

I have a grocery list that I take from database and when I check a recipe I display the ingredients for the recipe. I have 2 recipe in the database and every recipe has 4 ingredients.

What I do right now , I display all the ingredients if I check the recipes and if an ingredient is present in both recipes i just add up the quantities.

I am stuck where I uncheck the ion-checkbox , because I get under the common ingredients that are in both recipes I get NaN when I tried to decrease the quantities so I can get the initial recipe ingredients.What it looks like in UI

My function code :

onCheckboxF(ev) {
    if (ev.detail.checked === true) {
for (let recipe of this.recipes) {
        if (recipe.name === ev.detail.value) {
          recipe.ingredients.forEach((singleIng) => {
            let matchedIng = this.groceryList.find(function (foundIng) {
              return foundIng.name === singleIng.name;
            });

            // console.log(this.groceryList);

            if (matchedIng) {
              this.untickedGroceryList.push(matchedIng);
              // console.log(this.untickedGroceryList);

              matchedIng.quantity = matchedIng.quantity + singleIng.quantity;
            } else {
              this.groceryList.push(singleIng);
            }
          });
        }
      }
    } else {
      let tickedRecipe = ev.detail.value;
      for (let recipe of this.recipes) {
        if (recipe.name === tickedRecipe) {
          recipe.ingredients.forEach((el) => {
            let matchedIng = this.groceryList.find(function (foundIng) {
              return foundIng.name === el.name;
            });
            if (matchedIng) {
              let index = this.groceryList.findIndex(
                (ingF) => ingF.name === matchedIng.name
              );
              this.groceryList.splice(index, 1);
            }
            let matchedSub = this.untickedGroceryList.find(function (
              foundIngred
            ) {
              return foundIngred.name === el.name;
            });

            if (matchedSub) {
              matchedSub.quantity = matchedSub - el.quantity;
              console.log(matchedSub);
            }
          });
        }
      }
    }
  }


As you can see I get NaN grams , the adding its working but to - the quantities its not working. What I am doing wrong , please help . Thank you for your time.




Styling of checkbox input in React and Sass

There is a input like this:

<input
  type="checkbox"
  id="vehicle1"
  name="vehicle1"
  value="Bike"
  className="address-checkbox"
/>

but no matter what I write in .address-checkbox it doesn't take that styling.

Tried like:

.address-checkbox > input {
  color: red;
  border: 1.5px solid #e3e6eb;
}

or

.address-checkbox {
  color: red;
  border: 1.5px solid #e3e6eb;
}

or with !important, no change on the styling of it.

Is there a way to change its styling?




Check previous checkboxes when clicking a checkbox and saving all to localstorage

I've been trying to find what I'll explain in a moment, but I only found parts of it and when I tried to put them together, it always failed. Rather than to show what I tried, I think it's better to explain and show a simple example of what I would like and hopefully someone can help me. Here's the example:

<div class="checkbox a">        
    Class A<br>                 
    <input type="checkbox" name="checkbox"  id="a1" value="a1">                 
    <label>A1</label>
    <input type="checkbox" name="checkbox"  id="a2" value="a2">                 
    <label>A2</label>
    <input type="checkbox" name="checkbox"  id="a3" value="a3">                 
    <label>A3</label> 
</div>                          
                        
<div class="checkbox b">        
    Class B<br>                 
    <input type="checkbox" name="checkbox"  id="b1" value="b1">                 
    <label>B1</label>
    <input type="checkbox" name="checkbox"  id="b2" value="b2">                 
    <label>B2</label>
    <input type="checkbox" name="checkbox"  id="b3" value="b3">                 
    <label>B3</label> 
</div>

<div class="checkbox c">
    Class C<br>                 
    <input type="checkbox" name="checkbox"  id="c1" value="c1">                 
    <label>C1</label>
    <input type="checkbox" name="checkbox"  id="c2" value="c2">                 
    <label>C2</label>
    <input type="checkbox" name="checkbox"  id="c3" value="c3">                 
    <label>C3</label>
    <input type="checkbox" name="checkbox"  id="c4" value="c4">                 
    <label>C4</label> 
    <input type="checkbox" name="checkbox"  id="c5" value="c5">                 
    <label>C5</label>  
</div>

PART 1
When you click A3, both A2 and A1 will be checked too. If you check B2, only B2 and B1 will be checked.
Not a button to select all. It kind of works like star ratings perhaps?

PART 2
When I refresh or close and reopen the link, all the checkboxes are still checked in the way I clicked them, so basically I'd like a code that save those choices preferably to the LocalStorage but if you think there's another way that allows me to save the choices, without connecting it to a database or something like that, then it should be okay too.


In all honesty I always had a hard time trying to explain or find what's in my mind, so hopefully all of it makes sense. In this example it only has Class A, B and C, but the thing I want to make will have much more classes. So no matter how many classes it has, it should remember all the checkboxes and unlock the previous checkboxes when clicked.
e.g. when clicking C4, C1 to C3 will also be checked




How to check a checkbox in Google Apps Script?

So I'm trying to make a sign-in/sign-up form on Google Sheets, and I have two checkboxes, one that says login, and one with sign up. In my apps script, I'm trying to make it so that only one of them can be checked. This is my code, and it's not working. Help?

function signupLogin() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  if (sheet.getRange('A13').isChecked() === 'TRUE') {
    sheet.getRange('B13').setValue('FALSE');
  } else {
    sheet.getRange('B13').setValue('TRUE'); 
  }
}

The code will always make the second checkbox ticked, even if the first one is ticked.




mardi 22 septembre 2020

Create radio button from textbox input in javascript

I'm creating a to-do list using javascript and HTML where the user has the ability to enter an item into a textbox and then click the 'add' button which creates a radio button with the user's item as it's label. The user will also have the ability to remove, highlight, and sort all the items in their list but right now I'm concerned with getting the 'add' button to work.

I created an array called itemsList to keep track of all the items the user has on their to-do list. I'm struggling right now with actually getting a radio button to appear on the to-do list when the user adds a valid item. I just started learning javascript a week ago and I'm very overwhelmed with the amount of different terms and functions there are to use and I would appreciate some help or a push in the right direction.

I found an example that is sort of similar to what I'm trying to create but instead of the item appearing in a menu, it should just appear as a radio button with a label next to it.

Example: How to add textbox value into a list?

I also found this which helped but I'm having trouble adding a label next to my button with the user's input: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_radio_create

Code:

let itemsList[];

function init(){
    console.log("Loaded");
    let button = document.getElementById("add").addEventListener("click", addItem);
    button.onclick = buttonClicked();
    let item = document.getElementById("item");
    item.onblur = validate;
}

function addItem(){
    console.log("validate");
    let item = document.getElementById("item");
    if(item.value.length < 1){
        alert("You need to enter at least 1 character.");;
    }else{
        itemsList.push({name: item, light: false, checked: false));
    }
}

function buttonClicked(){ //create radio button

    var x = document.getElementById("list");
    var radio = document.createElement("INPUT");
    radio.text = document.getElementById("item").value;
    radio.add(radio);

}
<html>
    <head>
        <title>To-Do List</title>
    </head>
    <body onload="init()">
        <div><h1>To-Do List</h1></div><br />
        <div>Enter item: <input type="text" id="item"></input><button type="button" id="add">Add Item</button></div>
        
        <div id = "list"></div>
        
        <div>
            <button type="button" id="remove">Remove Items</button>
            <button type="button" id="toggle">Toggle Highlight</button>
            <button type="button" id="sort">Sort Items</button>
        </div>
        
        <script src="t2.js"></script>
    </body>
</html>