mercredi 31 août 2022

Checked Check Process

I can't solve a problem and need help.

Let me briefly explain what to do.

Here

As you can see above, I have the data I pulled from the database and these are the radio inputs.

Each one has unique database ids and I want to check here with jquery.

For example, if the phone does not select the memory partition, I want to give a warning. Since the data coming here comes with a loop, the same thing will enter the loop.

If it is selected, I want to get the values in it.

I would be glad if you could help me.

HTML

<form action="" type="POST" onsubmit="return false;">
                                    <div id="form_step_1">
                                        <div class="container">
                                            <div class="row">
                                                <?php
                                                $features_title_query   =   $db->prepare("SELECT * FROM features_title WHERE features_title_product_id = ?");
                                                $features_title_query->execute([Guvenlik($product_id)]);
                                                $features_title_number  =   $features_title_query->rowCount();
                                                $features_title_fetch   =   $features_title_query->fetchAll(PDO::FETCH_ASSOC);

                                                foreach ($features_title_fetch as $features_title) {
                                                ?>
                                                <div class="talepler mb-3">
                                                    <H4><?php echo $features_title["features_title_name"]; ?></H4>
                                                    <?php
                                                        $features_data_query    =   $db->prepare("SELECT * FROM features_data WHERE features_data_features_title_id = ?");
                                                        $features_data_query->execute([Guvenlik($features_title["id"])]);
                                                        $features_data_number   =   $features_data_query->rowCount();
                                                        $features_data_fetch    =   $features_data_query->fetchAll(PDO::FETCH_ASSOC);
                                                            if ($features_data_number > 0) {
                                                                foreach ($features_data_fetch as $features_data) {
                                                    ?>
                                                            <div class="row mb-3" style="display: inline-block">
                                                                <div class="col-sm-3 col-md-4 col-lg-3 titles">
                                                                    <input style="display: none" class="inputs" type="radio" id="<?php echo Guvenlik($features_data["id"]); ?>" name="<?php echo Guvenlik($features_data["features_data_features_title_id"]);?>">
                                                                    <label class="btn btn-pill" style="display: inline-block" for="<?php echo Guvenlik($features_data["id"]); ?>"><?php echo Guvenlik($features_data["features_data_name"]); ?></label>
                                                                    <style>
                                                                        .inputs:checked + label {
                                                                            background-color: #0034d0;
                                                                            color: white;
                                                                        }
                                                                        .inputs + label {
                                                                            border: 1px solid blue ;
                                                                        }
                                                                    </style>

                                                                </div>
                                                            </div>

                                                    <?php
                                                                }
                                                            }
                                                            ?>
                                                </div>
                                                <?php } ?>
                                                <button type="submit" class="btn btn-success" id="gonder">Gönder</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>

JS

$(document).ready(function () {
    $('.inputs').on('click', function () {
        var $id =   $(this).val();
        var $ids =   "#" + $(this).val();
        if ($($ids).attr('checked', true)) {
            $($ids).attr('checked', false);
        } else {
            $($ids).attr('checked', true);
        }
    })
});



mardi 30 août 2022

Change checkBox Size of Datagridview Checkbox Cell and increase the clickable area

I have a checkbox column in my .net core Winform data GridVew.
I already made the checkbox bigger to be easier for the user to click.

My code inside CellPainting,

                e.PaintBackground(e.CellBounds, true);
                ControlPaint.DrawCheckBox(e.Graphics, e.CellBounds.X + 1, e.CellBounds.Y + 5,
                    e.CellBounds.Width - 10, e.CellBounds.Height - 10,
                    (bool)e.FormattedValue ? ButtonState.Checked : ButtonState.Normal);
                e.Handled = true;

Those are my reference links,
How to change checkBox Size in DatagridviewCheckboxCell
Increase the size of Checkbox in #DataGridView in C#

The result is like below,

enter image description here

But the problem is the click area, even though the size of the checkbox is bigger, I realize the clickable area is still in its original size.
As I show below, the green area is clickable area,
enter image description here

I want to make the clickable area as big as the checkbox's size as show below,
enter image description here

Is there any solution?




Checkbox is not selected for Firefox ESR 102 version

There is an issue occurring when selecting the checkbox. The checkbox is not working properly for Firefox ESR 102. But it is working fine with Firefox ESR 68.4.2 version as well as google the google chrome.

As a test, I just disable all the styles (View > Page Style > No Style ). But it is also not successful.

style.min.css file

Thank you




Checkbox trigger multiple select with React

I'm building a React application for my clients. Each Client, when log-in, can access different views for each his location office. So first I list all the office of the client, and for each its office, he cans select the views he wants to display.

My Problem :

Let say I have office 1 that can choose to access to view 1 and view 2 and office 2 that can access to the same views. When I click on view 1 for office 1, it triggers view 2 for office 2 also !

I click on view 1 for office 1, it selects view 1 for office 2 also

Here is the code :

<div >
        {
          //I take all the offices of a client
          officesArray.map((office, index) => {
            return (
              <div key={index}>
                <h3>site {(office.name)}</h3>
                <div key={index}>
                  //For each office I display the views available to select
                  viewsArray.map((view, index) => {
                    return (
                      <div>
                        <label
                          for={`${view.name}${office.name}`}
                        >
                          <input
                            key={`${index}${office.id}`}
                            type="checkbox"
                            id={`${view.name}${office.name}`}
                            name={`${view.name}${office.name}`}
                            value={`${view.name}${office.name}`}
                            checked={checkedState[index]}
                            onChange={() => handleOnChange(index, office.id)}
                          />
                          {view.name}
                        </label>
                      </div>
                    )
                  })}
                </div>
              </div>
            )
          })
        }
      </div>

And here is the handleonchange function :


const handleOnChange = (position, office) => {
    const updatedCheckedState = checkedState.map((item, index) =>
      index === position ? !item : item
    );
    prop.set({ id: (prop.views)[position].id_view, officeId: office })
    setCheckedState(updatedCheckedState);
  }





AntBlazor tree with checkboxes. How to check some tree items with code, when replacing the tree data

I'm searching for a way how to set the check boxes in an AntBlazor Tree component by code for example on button press. Not at startup. In the end I would like to replace the tree data with a filtered set of tree data, and keep the check boxes checked that were checked before. In my attempts the check boxes are cleared when a new DataSource is set, and I found no way to re-set them again. I'm using AntBlazor 0.12.0.1. which is the latest version at this time. I used a simple test implementation : Checkable="true", @bind-CheckedKeys="checkedKeys" , DefaultCheckedKeys="DefaultCheckedKeys", DataSource="People" (where people is List< Person > and Person has Children of List< Person > ) and no way to get to the checkbox item in the code using : @ref="PeopleTree". I also found no example code on how to do this. Any suggestions on how to approach this would be welcome.




lundi 29 août 2022

how to filter or map the object when checkbox event fired and how to set display 'block' when checkbox selected

I'm new to angular 13 and am having some issues and would be grateful for any pointers. On my project there are components for rendering opportunities(opps) object, a component for filter list...etc. When Event fired, I want to capture the Event.target.value, loop through opportunities object, compare Event.target.value with opp.CATEGORYID, opp.PROVIDERNAME or opp.TAGS and then set display 'block' or 'none' to render on the screen. In summary, opportunities are already rendered and I want to show opportunities when its display is 'block' but I'm struggling how to set display 'block' or 'none' conditionally. Thank you so much any advice.

opp-list-component.html

<mat-card *ngFor="let opp of opps" 
 class="oppContainer"
 [attr.data-opp-id]=" 'opp_' + opp.PLACEMENTID "
 [attr.data-filters-cat]="opp.CATEGORYID"
 [attr.data-filters-tags]="opp.TAGS"
 [attr.data-filters-provider]="opp.PROVIDERNAME"
 [attr.data-filters-location]="opp.LOCATIONTYPE"
 [attr.data-filters]="opp.TAGS + ',' +opp.CATEGORYID + ',' + opp.PROVIDERNAME + ','+ opp.LOCATIONTYPE + ',' + opp.BADGEASSETID "
 [style.border-left]="'10px solid ' + 'rgb'+ '(' + opp.COLOURCODE +')' "
 [style.display]="displayOpps"
>
   <mat-card-header >
     <img  mat-card-image src="https://images.unsplash.com/photo-1582213782179-e0d53f98f2ca?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="Photo of a Shiba Inu">
   </mat-card-header>
     <p >
       <a [routerLink]="'/about'"></a> > <a [routerLink]="'/about'"></a>
     </p>
 
     <p> 
       <a [routerLink]="'/about'"></a>
     </p> 
 
     <p textColor></p>
 
     <p><mat-icon> place</mat-icon> miles away</p>
    
       <mat-card-footer >
         <p><mat-icon> local_offer</mat-icon> </p>
       </mat-card-footer> 
   </mat-card> 

filter-list-component.html

<mat-card-title><h2>Filters</h2></mat-card-title>

   <div class="filter-contents">

    <h3>Category</h3>
    <div  *ngFor = "let cat of cats">
      <p class="bb">
      <label class="cat-label" for=""
      [style.border-left]="'10px solid ' + 'rgb'+ '(' + cat.COLOURCODE +')' "
      >
         (  )
      <input type="checkbox" 
      (change)="onChange($event)"
      value=""
      >
      </label>
    </p>
    </div>
  

  
    <h3>Organizations</h3>
    <div *ngFor="let provider of providers">
      <p class="bb">
      <label for="">
         (   )
      <input type="checkbox" 
      (change)="onChange($event)"
      value="">
      </label>
    </p>
    </div> 
  
  
  
    <h3>Tags</h3>
    <div  *ngFor="let tag of tags">
      <p class="bb">
      <label for="">
         (  )
        <input type="checkbox" 
        (change)="onChange($event)"
        value="">
      </label>
     </p>
    </div>

  </div> 
  
   </mat-card>  

search-component.ts (parent component)

receiveEvent(event:any) {
 
 this.checkboxEvent = event;
 this.eventValue = event.target.value;
 this.eventChecked = event.target.checked;;
 
 console.log(this.eventValue," this.eventValue from search c!!")
 console.log(this.eventChecked ,"this.eventChecked  from search c!!")


   if(event){
    this.displayOpps = 'block'
   }  

 
   
   //how to do that ??
   //loop through this.opps object

   //check event.target.value === opp.CATEGORYID or 
   //event.target.value === opp.PROVIDERNAME or
   //opp.TAGS.includes(event.target.value.toLowerCase())

   //if false
   //this.displayOpps = 'none'

  

} 



How to pass checkbox checked values as parameter to controller action and return Json data which bind to Listbox in view in C# MVC?

checkbox checked values as parameter to controller action and return Json data which bind to Listbox in view




checkbox search by php [closed]

I have several checkboxes by php. I want to search the database and display the selected conditions when I select the first and second checkboxes. When I select one checkbox, I have no problem, but when I select two checkboxes, the conditions are not displayed.

enter code here

<form name="f1" action="">
  <label>ALL</label>
  <input type="checkbox" name="ch[]" id="ch1" value="all">
  <label>GIRL</label>
  <input type="checkbox" name="ch[]" id="ch2" value="girl">
  <label>BOY</label>
  <input type="checkbox" name="ch[]" id="ch3" value="boy">
  <label>NONE</label>
  <input type="checkbox" name="ch[]" id="ch3" value="none">
  <input type="submit" name="sub1" value="search"
</form>



Select Multiple values from checkboxes in Angular js and pass it to controller

I have array of object containing

vm.array = [
{key: 'text 1', value: 'false'},
{key: 'text 2', value: 'false'},
]

These values are being shown in the controller which is fine

           <div layout="column">
                    <div class="md-dense" layout="column" style="margin: 0px auto;">
                        <md-input-container ng-repeat="t in a.array" style="margin: -3px;">
                            <md-checkbox ng-model="t.value" aria-label="t.key">
                                
                            </md-checkbox>
                        </md-input-container>
                    </div>
                </div>

What I need is to let say a user selects the first check box and click a button so I could see the results whether which checkbox is selected and which in not selected.




dimanche 28 août 2022

How to put or embed a fully Ajax checkout form on WooCommerce single product page?

I’m using this code snippet to show WooCommerce checkout form on the single product page :

    add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr($description){
  $text="[woocommerce_checkout]";
  return $description.$text;
}

It's working, But this form lacks the Ajax functionality. Like when you click the 'pass order' button, the form doesn't submit using AJAX but redirect to check out page

So, how can I enable the AJAX functionality?




palpay checkout payment integration in php

I want to move from sandbox to live payment but when I click on paypal button nothing happens, every thing worked fine on sandbox. The Code is as follow:

paypal.Buttons({ // Sets up the transaction when a payment button is clicked https://ift.tt/htK8MDZ
    createOrder: (data, actions) => {
        
      return actions.order.create({

        purchase_units: [{

          amount: {

            value: document.getElementById('amount').value // Can also reference a variable or function

          }

        }]

      });

    },
    

    // Finalize the transaction after payer approval

    onApprove: (data, actions) => {

      return actions.order.capture().then(function(orderData) {

        window.open('verify_transactions.php','_self');

      });

    }

  }).render('#paypal-button-container'); 



Unchecking checkboxes programmatically

I have a certain requirement that, if the first checkbox in a row of checkboxes is unchecked, then all the other checkboxes must be unchecked. Here is a sample UI

I am using DevExpress 21.2.3 and RepositoryItemCheckEdit as the check box

Can anyone help me to achieve this functionality?

Thanks




How to pass array of objects to another screen and display them react native

How do i pass the data of selected checkboxes to the previous screen in react native.

The following is what i have done so far:

This is my SelectProducts screen

import React, {useState, useEffect} from 'react'
import { StyleSheet, Text, View, Alert, Image, ScrollView, TouchableOpacity } from 'react-native';
import Checkbox from 'expo-checkbox';


const SelectProducts = ({route}) => {

    const [checkedBox, setCheckedBox] = useState([]);
    const [selectedBoxesItem, setSelectedBoxesItem] = useState([]);
    const [itemList, setItemList] = useState([]);

    
    const includeSelectedItem = (item, index) => {
        const newCheckedBox = [...checkedBox];
        newCheckedBox[index] = !newCheckedBox[index];
        setCheckedBox(newCheckedBox);
        setSelectedBoxesItem({
            selectedUniqueKey: item.id,
            selectedItemName: item.ad_headline,
            selectedItemPrice: item.ad_price,
            selectedItemPic: item.ad_picture
        });
    }

This is the function that I'm using to send the data to the RecordASale screen after clicking on the Done button that is below the list of checkboxes.

    const handleSelectedSubmit = () => {
        navigation.navigate({
            name: 'RecordASale',
            params: {
                post: [selectedBoxesItem],
            },
            merge: true,
        })
    }

And this is the checkbox:

    return (
         {itemList.map((item, index) => (
                <DataTable.Row>
                  <DataTable.Cell>
                  <View style={styles.checkboxContainer}>
                     <Checkbox
                      key={item.id}
                      value={checkedBox[index]}
                      onValueChange={() => includeSelectedItem(item, index)}
                      color={checkedBox ? '#800080' : undefined}
                      style={styles.checkbox}
                    />
                  </View>
                  </DataTable.Cell>
                  <DataTable.Cell>
                  <Image source =  style =  />
                  </DataTable.Cell>
                  <DataTable.Cell>{item.ad_headline}</DataTable.Cell>
                  <DataTable.Cell>{item.ad_price}</DataTable.Cell>
                </DataTable.Row>
             ))}
        
            <View style = {styles.submitButton}>
               <Text style = {styles.submitButtonText} onPress={() => handleSelectedSubmit()}>Done</Text>
            </View>
          </DataTable>

    );
}

What i want to achieve is to get the following details for every checkbox selected:

  1. item.id,
  2. item.ad_headline,
  3. item.ad_price,
  4. item.ad_picture

All the above data should be passed from this SelectProducts screen to RecordASale screen

To my own understanding, what I did was that I passed objects to the function of the state below:

const [selectedBoxesItem, setSelectedBoxesItem] = useState([]);
setSelectedBoxesItem({
            selectedUniqueKey: item.id,
            selectedItemName: item.ad_headline,
            selectedItemPrice: item.ad_price,
            selectedItemPic: item.ad_picture
});

So when i did this, I only get the last selected checkbox details passed to the RecordASale screen even though i selected more than one checkbox.

This is how i'm getting the details into the RecordASale screen:


const RecordASale = ({route}) => {

   return (
           {(route.params?.post) ? route.params?.post.map((item, index) => (
        <View>
           <View key={index}>
                <Image source =  style =  />
                <Text>{item.selectedItemName}</Text>
                <Text>{item.selectedItemPrice}</Text>
           </View>
        </View>
           )) : <Text></Text>}
   );

}

I want the same details as above for all selected checboxes to be passed to the other screen, and not just one.

I believe I'm quite close to that but some things are missing in my code. Please help. Thanks.

I only shared the parts I'm having problems with.




vendredi 26 août 2022

Rails HAML View: checkbox is always false on add a new record

I'm working on a view which contains a textfield and a checkbox, for some reasons the checkbox value is always false during the create method. This is the code from the view:

  =form_for :student_loan, url: admin_students_loan_path do |f|
    =f.text_field :name, placeholder: "Full Name"
    =f.check_box :active_loan
    =f.label :active_loan
    =button_tag( :class => "btn") do
      Add               

This is the create method from the controller:

def create
  @student_loan = current.school.student_loans.create(student_loans_params)

  if @student_loan.valid?
    redirect_to admin_student_loans_path
  else
    flash[:errors] = @program_type.errors.full_messages
    redirect_to admin_student_loans_path
  end
end              

def student_loans_params
  params.require(:student_loan).permit(:name, :active_loan, :_destroy)
end    

If I run the edit view and change the checkbox's value from false to true (checked) this change is stored in the database, this is the code from the edit view:

=form_for @student_loan, :url => {:controller => :student_loans, action: :update} do |f|
  %tr
    %td=f.text_field :name, placeholder: "Full name"
    %td
      =f.check_box :active_loan
      =f.label :active_loan
      %br
      =f.submit

And this is the update method from the controller:

def update
  @student_loan = current.school.student_loans.find(params[:id])
  @student_loan.update(student_loans_params)

  redirect_to admin_program_types_path
end

So I've been hours trying to find the difference or the bug in the create workflow, I would like to request your help in these two questions:

  1. how can I be sure about the checkbox's value passed to the controller?
  2. do you see anything in my code that is avoiding to catch the real value from the checkbox control?

Thank you so much




(Google Sheets) Is there a way to have a checkbox toggle the text color of a set range?

I have a Google Sheets document and there is a dynamic list that gets created in a certain range (J19:L26) that has some personal data in it. Is there a way to make a checkbox or something quick I can click (even a button?) that can set the text to white or background to black to hide it to onlookers? I currently have the checkbox in cell M17

I have the following code that executes fine but then when I check the box in M17 nothing happens. Maybe I missed a step somewhere? I am new to Google sheets coding. I just wrote the function, tested it Runs, then closed it. Maybe I am just missing a step(s) in implementing the function to my sheet or my function Runs but doesn't do what I need it to?

function Privacy() {
  var TheBoard = SpreadsheetApp.getActiveSpreadsheet();
  var TheRange = TheBoard.getRange("Board!J19:L26");
  if(TheBoard.getRange("Board!M17") == "TRUE")
  {
    TheBoard.getRange(TheRange).setFontColor('white');    
  } 
}



How to get the value of selected expo-checkbox in a loop react native

Please i need help trying to get the value/state of each selected checkbox in my react native project.

What I'm trying to do actually is to click on a button that navigates to "SelectProducts" screen. then the screen shows a list of items to select using checkboxes. I put the checkbox I imported from expo in a loop like the following:

import React, {useState, useEffect} from 'react'
import { StyleSheet, Text, View, Alert, Image, ScrollView, TouchableOpacity } from 'react-native';
import {useNavigation} from '@react-navigation/native';
import Checkbox from 'expo-checkbox';

const SelectProducts = ({route}) => {

const navigation = useNavigation();
const [checkedBox, setCheckedBox] = useState([]);
const [itemList, setItemList] = useState([]);

{itemList.map((item, index) => (
  <View key={item.id} style={styles.checkboxContainer}>
     <Checkbox
      value={checkedBox[index]}
      onValueChange={() => {
      let checkedBox = [];
      checkedBox[index] = !checkedBox[index];
      setCheckedBox(checkedBox);
      // console.log(setCheckedBox(checkedBox));
      }}
      color={checkedBox ? '#800080' : undefined}
      style={styles.checkbox}
    />
  </View>
))}
}
export default SelectProducts;

The code above is just a part of the entire code in the "SelectProducts" screen where I'm having issues. Please let me know what I'm not during right here.

So, after selecting the checkboxes for the items I want to include when recording a sales order, the system should get the price, item name, and picture to send back to the previous screen in order to calculate the total sum, etc. when done with the item selection.

But the result I'm getting is very weird. There is now a list of items with checkboxes as expected, but once I select one of the checkboxes, then try to select another one, the previous checkbox will be unselected automatically for the current one to be selected. The checkbox selection is behaving exactly like normal radio buttons that only accept one input at a time. Meaning that my checkbox implementation isn't allowing multiple selections. This is the main challenge I'm facing at the moment.

I have even tried to print out the output of the value when selected but it's showing 'undefined'. I'm so confused here. I know this is simple to some of the developers here but I'm quite finding it hard to implement. It has already taken me some days now. Please help. Thanks!




jeudi 25 août 2022

Multiple custom checkboxes in Vue3 react differently when clikcing label vs input

I have a custom checkbox where the input and a separate (custom) label flip the checked value. When checked is changed, a watch picks it up and $emits the value to the parent.

In the parent, I have two of the same Toggle components, however when I click the Toggle input, it only triggers the first toggle (unexpected). If I click the label, it triggers the correct toggle switch (as expected).

Can someone please explain what is happening here?

https://codesandbox.io/s/vue3-base-forked-3ppj0j?file=/src/components/Toggle.vue

The event being emitted is the same, regardless of clicking the label or the input, so why does one work and the other doesn't?




checkbox color becomes darker when hovering over it

I have changed the color of my checkboxes when they are checked to not be the default light blue using the following CSS:

  input[type="checkbox"] {
  accent-color: var(--red);
  }

the problem is that when I hover over the checkbox it makes the color darker. I tried using the :hover pseudo-selector which somewhat works as it will change the color to whatever you set it to, but still takes it and makes it darker. Does anyone know how to keep it from doing this?




v-checkbox is selected by default after second call to service

I have an issue and any help will be appreciated I have this loop with checkboxes

<div v-for="(check, i) in alarms" :key="check.value">
  <v-checkbox
    v-if="check.contenido"
    v-model="checksModels[i]"
    :label="'Baja ' + check.contenido"
    :value="check"
  />
</div>

and the function that fetch the elements is this one

async fetchAlarms () {
    this.loading = true
    const alarmsAuhors = this.$axios.$get(`/service/getalarms/5`)
    const alarmsThemes = this.$axios.$get(`/service/getalarms/6`)
    const [resAuthors, resThemes] = await Promise.all([alarmsAuhors, alarmsThemes])
    this.alarms = [...resAuthors, ...resThemes]
    this.tipo5 = Boolean(resAuthors.length)
    this.tipo6 = Boolean(resThemes.length)
    this.loading = false
},

in the data I have both variables

  data: () => ({
    checksModels: [],
    alarms: [],
  }),

alarms fetch the results of the axios calls (everything is normal) the first time. But if I launch the fetchAlarms () for the second time the checkboxes are checked even when the checksModels where I save the selected elements is empty. Anyone knows how can I uncheck them. Thanks in advance

enter image description here




Angular mat-table with input fields and checkboxes

I'm getting some data from backend and displaying it in my UI. The problem is I want to be able to modify each row's input field and checkbox and then submit the whole form and process the information.

I can render the page, no problem, but I have no clue where to start with creating the FormArray and how to place them in my HTML to be able to click on the save button and submit the entire form.

Here is my type script code

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { AttributeSetRootObject } from '../../models/attribute-set.model';
import { AttributeSetService } from '../../services/attribute-set.service';

@Component({
  selector: 'app-attribute-set-standard',
  templateUrl: './attribute-set-standard.component.html',
  styleUrls: ['./attribute-set-standard.component.scss'],
})
export class AttributeSetStandardComponent implements OnInit {
  attributeSets: AttributeSetRootObject;
  attributeSetForm: FormGroup;

  displayedColumns = [
    'attributeName',
    'englishLabel',
    'frenchLabel',
    'dataType',
    'fieldType',
    'defaultValue',
    'mandatoryIndicator',
  ];

  constructor(
    private route: ActivatedRoute,
    private attributeSetService: AttributeSetService,
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    const attributeSetId = parseInt(this.route.snapshot.paramMap.get('id'));
    console.log(attributeSetId);

    this.attributeSetForm = this.fb.group({
      defaultValue: [],
      mandatory: [],
    });

    this.attributeSetService.getStandardAttributes(attributeSetId).subscribe({
      next: (data: AttributeSetRootObject) => {
        console.log(data);
        this.attributeSets = data;
      },
    });
  }

  onSubmit() {
    console.log(this.attributeSetForm.value);
  }
}

HTML Code

<app-breadcrumb [crumbs]="attributeSets?.data.parentlinks"></app-breadcrumb>

<div class="container py-3 my-3 bg-light">
  <h3></h3>
  <div class="table-container" *ngIf="attributeSets?.data?.attributes?.length">
    <form [formGroup]="attributeSetForm" (ngSubmit)="onSubmit()">
      <table
        mat-table
        #attributeSetSort="matSort"
        [dataSource]="attributeSets.data.attributes"
        matSort
        matSortDisableClear
      >
        <ng-container matColumnDef="attributeName">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>
            Attribute Name
          </th>
          <td mat-cell *matCellDef="let element">
            
          </td>
        </ng-container>

        <ng-container matColumnDef="englishLabel">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>
            English Label
          </th>
          <td mat-cell *matCellDef="let element">
            
          </td>
        </ng-container>

        <ng-container matColumnDef="frenchLabel">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>
            French Label
          </th>
          <td mat-cell *matCellDef="let element">
            
          </td>
        </ng-container>

        <ng-container matColumnDef="dataType">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>Data Type</th>
          <td mat-cell *matCellDef="let element">
            
          </td>
        </ng-container>

        <ng-container matColumnDef="fieldType">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>Field Type</th>
          <td mat-cell *matCellDef="let element">
            
          </td>
        </ng-container>

        <ng-container matColumnDef="defaultValue">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>
            Default Value
          </th>
          <td mat-cell *matCellDef="let element">
            <mat-form-field>
              <mat-label class="asterix"
                >
              </mat-label>
              <input
                type="text"
                matInput
                formControlName="defaultValue"
                [value]="element.defaultValue"
              />
            </mat-form-field>
          </td>
        </ng-container>

        <ng-container matColumnDef="mandatoryIndicator">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>Mandatory</th>
          <td mat-cell *matCellDef="let element">
            <mat-checkbox
              formControlName="mandatory"
              [checked]="element.mandatoryIndicator === 'Y'"
            ></mat-checkbox>
          </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
      </table>

      <button mat-raised-button color="primary">
        
      </button>
    </form>
  </div>
</div>

The UI

This is how the page looks like

Right now when I click on save, it only submits one value. I would like to be able to submit all the values for the form.




mercredi 24 août 2022

Checkboxes are not working properly in React js

I am assigned a simple task to render permissions of different users using React JS. There is a little problem and I think the page is not rendered according to the received props data. Here is my code with little bit explanation.

// my App.js file
import { useState } from "react";
import "./App.css";
import Dropdown from "./components/Dropdown";
import Permissions from "./components/Permissions";

function App() {
  const users = [
    {
      id: 1,
      name: "Cirilla",
      permissions: ["Post"],
    },
    {
      id: 2,
      name: "Michael Scofield",
      permissions: ["Post", "Fetch", "Write"],
    },
    {
      id: 3,
      name: "Thomas Shellby",
      permissions: [],
    },
    {
      id: 4,
      name: "Jon Snow",
      permissions: ["Fetch", "Post"],
    },
  ];
  let [currentUser, setCurrentUser] = useState(users[0]);
  const permissions = [
    {
      id: 1,
      name: "Post",
      val: currentUser.permissions.includes("Post"),
    },
    {
      id: 2,
      name: "Fetch",
      val: currentUser.permissions.includes("Fetch"),
    },
    {
      id: 3,
      name: "Write",
      val: currentUser.permissions.includes("Write"),
    },
    {
      id: 4,
      name: "Read",
      val: currentUser.permissions.includes("Read"),
    },
  ];

  const dropDownChangeHandler = (value) => {
/*this function is executed whenever the dropdown is value is changed. setCurrentUser causes the app function to run again and the array permissions is created again according to the selected user*/
    const user = users.find((item) => item.name === value);
    setCurrentUser(user);
  };

  console.log(currentUser);

  return (
    <div className="container">
      <Dropdown list={users} onChange={dropDownChangeHandler} />
      <Permissions list={permissions} />
    </div>
  );
}

export default App;

Here is the permissions.js file

import PermissionsItem from "./PermissionsItem";

const Permissions = (props) => {
  return (
    <div>
      {props.list.map((item) => (
        <PermissionsItem key={item.id} item={item} />
      ))}
    </div>
  );
};

export default Permissions;

And finally, here is the permissionItem.js file

import React, { useEffect, useState } from "react";

const PermissionsItem = (props) => {
  /* const [checkboxValue, setCheckBoxValue] = useState(props.item.val); // here useState does not provide the correct value so I have to use useEffect for this */

   useEffect(() => {
     setCheckBoxValue(props.item.val);
   }, [props.item.val]);

  const checkBoxChangeHandler = (event) => {
    setCheckBoxValue(event.target.checked);
  };

  return (
    <div className="permission-item">
      <label htmlFor={props.item.id} className="perm-li">
        {props.item.name}
      </label>
      <input
        id={props.item.id}
        type="checkbox"
        checked={checkboxValue}
        onChange={checkBoxChangeHandler}
      />
    </div>
  );
};

export default PermissionsItem;

The problem is that when I check any checkbox value of any user (suppose Cirilla), and then select the other user from dropdown (suppose Michael Scofield), the checked permission of first user, Cirilla, is also checked in Michael Scofield's permission. The Micheal's data is displayed correctly in the console but checkboxes are not rendered accordingly.

Please Help I have already wasted my whole week on this :( Any kind of help or suggestion is much appreciated. Thank you in advance !

Here is the image




How to make required atleast one checkbox when one of the main check box is checked

I want to require at least one checkbox from all when one of the upper checkboxes is enter image description hereclicked. the snap is attached herewith.

here is the javascript code

function toggleOtherTextboxVisiblewh()
{
    var check = document.getElementById('wh');
    var chk2=document.getElementsByName('s1[]');
   var chk3=document.getElementsByName('q1[]');
    if (check.checked) {
        document.getElementById('sizewh').style.display = 'block';
        
    }
    else {
           document.getElementById('sizewh').style.display = 'none';
      
           for (i=0;i<chk2.length;i++)
                chk2[i].checked=false;
                
           for (b=0;b<chk3.length;b++)
                chk3[b].value = "";
    }            
            


}



mardi 23 août 2022

LabeledCheckbox (Checkbox) on the left side of the text in Flutter?

I'm using CheckboxListTile, by default the checkbox is to the right of the text. How do I move the checkbox to the left of the text?

My code:

 @override
   Widget build(BuildContext context) {
     return LabeledCheckbox(
       label: 'Text of my Checkbox',
       padding: const EdgeInsets.symmetric(horizontal: 20.0),
       value: _isSelected,
       onChanged: (bool newValue) {
         setState(() {
           _isSelected = newValue;
         });
       },
     );
   }

Preview:

enter image description here




lundi 22 août 2022

Javascript Filter Table then select all checkboxes

I have an html table with a checkbox on each row. My javascrpt filters rows based on a text box above the table. I need a function that will only check the boxes on visible rows. I'm stumped.

chkbuild is the name of all the checkboxes in the table. ID is unique. chkallnone is my header checkbox to select all or none.

example of table row cell

<td><input type="checkbox" id="(counter)" name="chkbuild" value="(unique ids)"></td>

Javascript code for selecting checkboxes.

  function checkCheckboxes( id, pID ){
var ele=document.getElementsByName('chkbuild');  
var TrueFalse = true;
//determine if the select all checkbox is checked or unchecked.
if (document.getElementById('chkallnone').checked) {
    TrueFalse = true;
} else {
    TrueFalse = false;
}
//cycle through all table checkboxes and set their checked value
for(var i=0; i<ele.length; i++){  
    ele[i].checked=TrueFalse;  
}

}




Better way to add a free text field option to a mat-select-list in Angular

I have several lists of mat-select-list check boxes in a form on one of my apps that are all structured like this:

    <div class="question">
      <div class="row">
        <h5>13. Alliance/Decision Support</h5>
      </div>
      <mat-selection-list #allianceDecisionSupport (selectionChange)="onApplicationSelection(1, $event.options)">
        <mat-list-option  class="col-md-3" checkboxPosition="before" value="Crystal Reports Access">Crystal Reports Access</mat-list-option>
        <mat-list-option  class="col-md-3" checkboxPosition="before" value="ADS Database Access">ADS Database Access</mat-list-option>
        <mat-list-option  class="col-md-3" checkboxPosition="before" [value]="other13.value">Other <input #other13 type="text" class="form-control other" id="other13" name="other13" placeholder="Enter data as required..."/></mat-list-option>
      </mat-selection-list>
    </div>

The only problem I have is that when the user clicks on the text field to type it checks the box beside it and my client doesn't like that. They want the user to have to check the check box and then type or vise versa. Either way, I just need the box to not be checked just by typing; the user should have to click checkbox itself. If it isn't clear, the free text field is the value of the the last checkbox option. Everything else works correctly, the client just doesn't like that the check appears when the user clicks to type.

Maybe what I have done is not the best way to do this and maybe there's a completely better method. I'm open to pretty much any option here.

If you need any additional information please let me know.




dimanche 21 août 2022

I want to use a checkbox in a function - Maxscript

My question is about maxscript. Is it possible to use a checkbox in a function? this checkbox works correctly when it is not in the function. but when it's in the function, it doesn't work, and this is the error :

-- Error occurred in anonymous codeblock; filename: G:_BN Scripts\Checkbox problem.ms; position: 307; line: 18 -- Syntax error: at ), expected while -- In line: )

My code :

rollout AK "AK" width:200 height:400
(   checkbox 'FlipF' "Flip Face"   pos:[77,69] 

fn flip=
   (
        on FlipF changed theState do
    (
        if theState then
        (
         $.EditablePoly.flipNormals 1
        )
        else
        (
            $.EditablePoly.flipNormals 0
        )
    )
        
    )   
flip()  
)
createDialog AK



Array to string conversion in Laravel Checkbox

I am trying to insert the data to a one-to-many relationship table but when I insert I get the Array to string conversion error

Controller code

public function store(Request $request)
{
    //
    $data = Personas::create([
        'idSede' => $request->idSede,
        'idTpdoc' => $request->idTpdoc,
        'identificacion' => $request->identificacion,
        'nombre' => $request->nombre,
        'correo' => $request->correo,
        'telefono' => $request->telefono,
        'idTpasistente' => $request->idTpasistente,
        'empresa' => $request->empresa,
        'carrera' => $request->carrera,
    ]);

    $eventos = $request->eventos;

    foreach($eventos as $evento){
        $datos = detalle_persona_evento::create([
            'idPersonas' => $data->id,
            'idEventos' => $eventos,
        ]);
    }

    foreach([$request->correo] as $recipient){
        Mail::to($recipient)->send(new ProyectandoMail());
    }

}

Input code

<input type="checkbox" value="" id="E0" name="eventos[]">



samedi 20 août 2022

How to use checkbox with select all in Recyclerview android

In my application I want use checkbox in recyclerview.
I want when users click on item check/unchecked checkbox and when click on Select All or clear, checked/unchecked all of items.
I write below codes, when click on select all checked all of checkboxes but after click on one of checkbox not unchecked!
I should click twice on checkbox after unchecked!
My UI is :
enter image description here My Adapter codes :

class DataListAdapter @Inject constructor() : RecyclerView.Adapter<DataListAdapter.ViewHolder>() {

    private lateinit var binding: ItemWithCheckboxBinding
    private lateinit var context: Context
    private var moviesList = emptyList<String>()
    private var isSelectedAll = false
    private var checkBoxState = SparseBooleanArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        binding = ItemWithCheckboxBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        context = parent.context
        return ViewHolder()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(moviesList[position])

        holder.checkBox.isChecked = checkBoxState.get(position, false)

        var state: String
        if (!isSelectedAll) {
            holder.checkBox.isChecked = false
            state = LIST_STATE_REMOVE
            onItemClickListener?.let { it(moviesList[position], state) }
        } else {
            holder.checkBox.isChecked = true
            state = LIST_STATE_ADD
            onItemClickListener?.let { it(moviesList[position], state) }
        }
    }

    override fun getItemCount() = moviesList.size

    inner class ViewHolder : RecyclerView.ViewHolder(binding.root) {

        val checkBox = binding.itemCheck

        @SuppressLint("SetTextI18n")
        fun bind(item: String) {
            binding.apply {
                //Views
                itemTitle.text = item
                //Click
                var state: String
                binding.root.setOnClickListener {
                    if (!checkBoxState.get(adapterPosition, false)) {
                        checkBox.isChecked = true
                        checkBoxState.put(adapterPosition, true)
                        state = LIST_STATE_ADD
                    } else {
                        checkBox.isChecked = false
                        checkBoxState.put(adapterPosition, false)
                        state = LIST_STATE_REMOVE
                    }
                    onItemClickListener?.let { it(item, state) }
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun selectAll() {
        isSelectedAll = true
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun unSelectAll() {
        isSelectedAll = false
        notifyDataSetChanged()
    }

    private var onItemClickListener: ((String, String) -> Unit)? = null

    fun setOnItemClickListener(listener: (String, String) -> Unit) {
        onItemClickListener = listener
    }

    fun setData(data: List<String>) {
        val moviesDiffUtil = NotesDiffUtils(moviesList, data)
        val diffUtils = DiffUtil.calculateDiff(moviesDiffUtil)
        moviesList = data
        diffUtils.dispatchUpdatesTo(this)
    }

    class NotesDiffUtils(private val oldItem: List<String>, private val newItem: List<String>) : DiffUtil.Callback() {

        override fun getOldListSize(): Int {
            return oldItem.size
        }

        override fun getNewListSize(): Int {
            return newItem.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldItem[oldItemPosition] === newItem[newItemPosition]
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldItem[oldItemPosition] === newItem[newItemPosition]
        }
    }
}

For control select all and clear checkboxes I write codes in Fragment:

    selectAllTxt.setOnClickListener { dataListAdapter.selectAll() }
    clearTxt.setOnClickListener { dataListAdapter.unSelectAll() }

How can I fix it?




how to create multiple checkbox groups with maximum 2 values in each group in react js

I want to create teams selection checkbox group wise. also user can only select 2 teams from each group. I am using react js 18.2v, I have tried some logic but how to get all values in one array / on single submit with validation, thanks in advance here is example https://codesandbox.io/s/group-checkbox-syr7ix?file=/src/data.js:0-2589

import { useEffect, useState } from "react";
const data = [
  {
    group: "A",
    teams: [
      {
        country: "Ecuador",
        country_code: "ECU",
        selected: false,
        admin_selected: true,
        points: 0
      },
      {
        country: "Netherlands",
        country_code: "NED",
        selected: false,
        admin_selected: false,
        points: 0
      },
      {
        country: "Qatar",
        country_code: "QAT",
        selected: false,
        admin_selected: false,
        points: 0
      }
    ]
  },
  {
    group: "B",
    teams: [
      {
        country: "IR Iran",
        country_code: "IRN",
        selected: false,
        admin_selected: false,
        points: 0
      },
      {
        country: "United States",
        country_code: "USA",
        selected: false,
        admin_selected: false,
        points: 0
      },
      {
        country: "England",
        country_code: "ENG",
        selected: false,
        admin_selected: false,
        points: 0
      }
    ]
  },
  {
    group: "C",
    teams: [
      {
        country: "Argentina",
        country_code: "ARG",
        selected: false,
        admin_selected: false,
        points: 0
      },
      {
        country: "Mexico",
        country_code: "MEX",
        selected: false,
        admin_selected: false,
        points: 0
      },
      {
        country: "Poland",
        country_code: "POL",
        selected: false,
        admin_selected: false,
        points: 0
      }
    ]
  }
];
export default function App() {
  const [allTeams, setAllTeams] = useState([]);
  const handleSubmit = (e) => {
    e.preventDefault();
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        {data.map((team, index) => {
          return (
            <SingleGroup
              key={index}
              data={team}
              setAllTeams={setAllTeams}
              allTeams={allTeams}
            />
          );
        })}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

const SingleGroup = ({ data, setAllTeams, allTeams }) => {
  const [values, setValues] = useState([]);
  const handleChange = (e) => {
    if (e.target.checked) {
      if (values.length < 2) {
        setValues((prev) => [...prev, e.target.value]);
      } else {
        e.target.checked = false;
        alert("You can select only 2 countries from the given group");
      }
    } else {
      let newArr = values.filter((d) => d !== e.target.value);
      setValues(newArr);
    }
  };
  useEffect(() => {
    if (values.length === 2) {
      setAllTeams((prev) => [...prev, values]);
    }
  }, [values, setAllTeams]);

  return (
    <div>
      <h4>Group: {data.group}</h4>
      {data.teams.map((team, index) => {
        return (
          <label key={index}>
            <input
              type="checkbox"
              name={team.country_code}
              value={team.country_code}
              onChange={(e) => handleChange(e)}
            />
            {team.country}
          </label>
        );
      })}
    </div>
  );
};



RowFilter using checkbox

I have a dataset with the a column name preferred location and some of the values are yes and remaining are blank in it. I have to place a checkbox in the page and if the checkbox is selected the rows which has the values of yes should be filtered and display. can anyone help how should I use row filter code in the backend of ASPX.VB . what is the exact syntax would be




Checkbox result affecting unrelated cells

I am trying to have the result of a Checkbox copy a value from a cell to another cell that are different to where the formula is for determining this.

So below, if the box is ticked C10 gets the value in C8. If it is not ticked you can enter into C10 a value. The same will go for G10 being filled with G8 if ticked, but there will be a second tick box. The formula for these can go anywhere I guess.

enter image description here

Regards, Tony H




PHP checkbox only showing first value

I am trying to iterate the row data of each message for each value in the database by a checkbox as when clicked you get the string value on this row

the Code:

  <div id="Ticket" style="display:none;" class="tabcontent">
    <table class="table">
    <thead>
        <tr>
            <th>Ticket ID </th>
            <th>username</th>
            <th>Data published</th>
            <th>Subject</th>
            <th>problem</th>
            <th>Statues</th>
            <th>Solved?</th>
            <th>More Details</th>
            
        </tr>
    </thead>
    <tbody>
        <?php
        $query=" Select * FROM tickets where resolved=0";
        $result_opened = mysqli_query($db, $query);
                    while($row = mysqli_fetch_array($result_opened)){ ?>


        <tr>
            <td data-label="id"><?php echo $row['id']?></td>
            <td data-label="username"><?php echo $row['username']?></td>
            <td data-label="publish"><?php echo $row['published']?></td>
            <td data-label="subject"><?php echo $row['subject']?></td>
            <td data-label="problem"><?php echo $row['problem']?></td>
            <td data-label=""><a href="#" class="btn btn__active">Open</a></td>
         <td>    <a href="resolve.php?id=<?php echo $row['id']?>" class="btn btn-warning" ><i class="fa-solid fa-circle-check"></i> </a> <br/><br/>
                    </td> 
<td><input type="checkbox" id="toggle">
   <label for="toggle">see more</label>

   <dialog >
    <h>Message</h><br><br>
      <p>
   //Here I am getting only the first value//
    <?php echo $row['message'] ?>
     </p>


    <label for="toggle">close</label>
    </dialog></td></tr>
                    <?php }?>
      </tbody>
  </table>
     </div>
   

but I keep on getting only the last value in the specific row

image:

I tried many ways to fix it but the main problem is its only getting the first value in the while loop.




vendredi 19 août 2022

How to enable optional chaining -React

I want to add a checkbox to each row in the table I have already created. In addition, there should be a select all button and it should be able to select all rows. I tried this but I'm getting the support for the experimental syntax 'optional chaining' isn't currently enabled error.

import React, { useState, useEffect } from 'react';


/* 
const userData = [{name: "Didem1"}, {name : "Didem2"}] */

const UserTable = props => {

    const [users, setUsers] = useState([]);
    const userData = [props.users];



    useEffect(() => {
        setUsers(userData)
    }, []);

    const handleChange = (e) => {
        const { name, checked } = e.target;

        if (name === "allSelect") {
            let tempUser = users.map(user => {
                return { ...user, isChecked: checked }
            });
            setUsers(tempUser);
        }
        else {
            let tempUser = users.map(user => user.name === name ? { ...user, isChecked: checked } : user);

            setUsers(tempUser);
        }
    }


    return (
        <table className="table table-dark">
            <thead>
                <tr>

                    <th scope="col">


                        <input
                            type="checkbox"
                            className="form-check-input"
                            name="allSelect"
                            onChange={handleChange}
                            checked = {users.filter((user) => user?.isChecked !== true ).length < 1}
                        />Select All


                    </th>
                    <th scope="col">Hostname</th>
                    <th scope="col">Username</th>
                    <th scope="col">Stop</th>
                    <th scope="col">Sleep</th>
                    <th scope="col">Start</th>
                    <th scope="col">Status</th>
                    <th scope="col">CPU Temperature(°C)</th>
                    <th scope="col">GPU Info</th>
                    <th scope="col">Edit/Delete</th>
                </tr>
            </thead>


            <tbody>
                {

                    props.users.length > 0 ? (
                        props.users.map(user => (

                            <tr key={user.id}>

                                <th scope="row">
                                    <input
                                        type="checkbox"
                                        className="form-check-input"
                                        /* user?.isChecked || false  */
                                        name = {user.name}
                                        checked = {user?.isChecked || false}
                                        onChange={handleChange}
                                    />


                                </th>
                                <td>{user.name}</td>
                                <td>{user.username}</td>
                                <td><button onClick={() => props.editStopPC(user)} className="btn btn-danger">Stop</button></td>
                                <td><button onClick={() => props.editSleepPC(user)} className="btn btn-warning">Sleep</button></td>
                                <td><button onClick={() => props.editStartPC(user)} className="btn btn-success">Start</button></td>
                                <td>{user.status}</td>
                                <td>{user.cpu}</td>

                                <td>{user.info}</td>

                                <td className="center-align">
                                    <button
                                        className="btn btn-info"
                                        onClick={() => props.editRow(user)}>
                                        edit
                                    </button>

                                    <button
                                        className="btn btn-danger"
                                        onClick={() => props.deleteUser(user.id)}>
                                        delete
                                    </button>
                                </td>
                            </tr>
                        ))
                    ) : (
                        <tr>
                            <td colSpan={9}>{props.users[0]} No Users</td>
                        </tr>
                    )
                }
            </tbody>
        </table>
    )
};

export default UserTable;

So I installed react-scripts@3.3.0 and @babel/plugin-proposal-optional-chaining and now I am getting TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined error. I'm not sure what causes this. I would be glad if you help.




jeudi 18 août 2022

Using MultiSelect Listbox with Pivot Table

I am fairly new to Excel and am wondering if this is even possible. Right now I have a dynamic listbox that will show the values from a pivot table. I have the listbox set with multi select, and am wondering if there is a way to connect the multiselect check boxes with the list box, where if I unselect the checkbox, it will remove that selection from a pivot table filter which will in turn change the totals shown in the userform linked below. If there is a better route to go as well, that would be much appreciated. Thank you!

Total Cost Table


    Me.StartUpPosition = 0
    Me.Top = Application.Top + Application.Height - Me.Height * 1.08
    Me.Left = Application.Left + Application.Width - Me.Width * 1.12

    Description = Sheet8.Range("A1").Value
    Material = Sheet8.Range("A2").Value
    Labor = Sheet8.Range("A3").Value
    SubContractor = Sheet8.Range("A4").Value
    Equipment = Sheet8.Range("A5").Value
    Other = Sheet8.Range("A6").Value
    TotalCost = Sheet8.Range("A7").Value
    Overhead = Sheet8.Range("A9").Value
    Profit = Sheet8.Range("A10").Value
    Phoenix = Sheet8.Range("A11").Value
    Bond = Sheet8.Range("A12").Value
    TotalPrice = Sheet8.Range("A14").Value
    DescriptionTotal = Sheet8.Range("B1").Value
    MaterialTotal = Sheet8.Range("B2").Value
    MaterialTotal = Format(MaterialTotal, "$#,##0.00")
    LaborTotal = Sheet8.Range("B3").Value
    LaborTotal = Format(LaborTotal, "$#,##0.00")
    SubContractorTotal = Sheet8.Range("B4").Value
    SubContractorTotal = Format(SubContractorTotal, "$#,##0.00")
    EquipmentTotal = Sheet8.Range("B5").Value
    EquipmentTotal = Format(EquipmentTotal, "$#,##0.00")
    OtherTotal = Sheet8.Range("B6").Value
    OtherTotal = Format(OtherTotal, "$#,##0.00")
    TotalCostTotal = Sheet8.Range("B7").Value
    TotalCostTotal = Format(TotalCostTotal, "$#,##0.00")
    OverheadTotal = Sheet8.Range("B9").Value
    OverheadTotal = Format(OverheadTotal, "$#,##0.00")
    ProfitTotal = Sheet8.Range("B10").Value
    ProfitTotal = Format(ProfitTotal, "$#,##0.00")
    PhoenixTotal = Sheet8.Range("B11").Value
    PhoenixTotal = Format(PhoenixTotal, "$#,##0.00")
    BondTotal = Sheet8.Range("B12").Value
    BondTotal = Format(BondTotal, "$#,##0.00")
    TotalPriceTotal = Sheet8.Range("B14").Value
    TotalPriceTotal = Format(TotalPriceTotal, "$#,##0.00")
    
Dim List As New Collection
Dim Rng As Range
Dim lngIndex As Long

LastRow = Sheet8.Columns("A").Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Set Rng = Sheet8.Range("A18:B" & LastRow - 1)

TotalCostList.ColumnCount = 2

With TotalCostList
    .ColumnCount = 2
    .List = Rng.Value
    .BorderStyle = fmBorderStyleSingle
End With

With Me.TotalCostList
    For lngIndex = 0 To .ListCount - 1
        .List(lngIndex, 1) = Format(.List(lngIndex, 1), "$#,##0.00")
        .TextAlign = 1 - frmTextAlignLeft
    Next lngIndex
End With

Dim i As Long

For i = 0 To TotalCostList.ListCount - 1
    TotalCostList.Selected(i) = True
Next i
    
End Sub



In MUI how can I keep the checkbox checked after refresh?

I am trying to get the checkboxes to stay checked after refresh. How can I go about doing that?My code

Im assuming its something I have to do in the Notes.js file?




mercredi 17 août 2022

Como Marcar caixinha de confirmação de exclusão de arquivo da Lixeira via CMD? [closed]

Olá, estou tentando criar um arquivo bat para configurações e queria marcar aquela caixinha nas propriedades da lixeira via cmd, que faz mostrar a caixa de confirmação de exclusão de um arquivo no Windows 10, já tentei alguns scripts na net mas nenhum resolveu.




mardi 16 août 2022

Trying to make grocery list on google sheets where checkbox auto clears the row, then unchecks itself

I have a grocery list im trying to make a touch more efficient on google sheets, ideally, i'd need the checkbox on a row to clear out its active row, then uncheck itself. Im fairly new to scripting and not sure how to get this working.

https://docs.google.com/spreadsheets/d/1qPL5yNFGdeUsLw-6TT4xKfkM7qg1TT2DIT5mErHdcZY/edit?usp=sharing




"Empty list doesn't contain element at index 0" error when implementing Android Recycler View with checkbox

I am implementing a recycler view with it's items as checkbox. My data is coming from ROOM database and this recycler view is inside a dialog fragment.

Dialog Fragment :

 override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = ScheduleFloorDialogBinding.inflate(layoutInflater)
        createProfileViewModel = CreateProfileViewModel(Application())
        floorProfileDialogAdapter = FloorProfileDialogAdapter()

        binding.rvFloorsForScheduling.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvFloorsForScheduling.adapter = floorProfileDialogAdapter

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val floorList: MutableList<String> = mutableListOf()

        //Getting list of all floors
        createProfileViewModel.totalFloors.observe(viewLifecycleOwner) {
            Timber.d("List of floors received : $it")

            val intList = it.map(String::toInt)
            val maxFloorValue = intList.last()
            var count = 0

            try {
                while (count <= maxFloorValue) {
                    floorList.add(count.toString())
                    count++
                }
            } catch (e: Exception) {
                Timber.d("Exception: $e")
            }
            floorProfileDialogAdapter.getAllFloors(floorList)
            Timber.d("Floor List : $floorList")
        }
    }

I am able to send list of data from here to my adapter.

Adapter:

class FloorProfileDialogAdapter() : RecyclerView.Adapter<FloorProfileDialogAdapter.MyViewHolder>() {

    var floors = emptyList<String>()

    inner class MyViewHolder(val binding: ScheduleFloorDialogItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ScheduleFloorDialogItemBinding.inflate(inflater, parent, false)

        return MyViewHolder(binding)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentFloor = floors[position]
        Timber.d("Current floor: $currentFloor")
        holder.binding.floorCheckBox.text = "Floor $currentFloor"
    }

    override fun getItemCount(): Int {
        return floors.toString().length
    }

    fun getAllFloors(floorsReceived: List<String>) {
        Timber.d("Floors received : $floorsReceived")
        this.floors = floorsReceived
    }
}

Log inside the Adapter's getAllFloor method shows that list has been received:

  • enter image description here

But inside onBindViewHolder() when I use the position I get the error saying :

java.lang.IndexOutOfBoundsException: Empty list doesn't contain element at index 0.



lundi 15 août 2022

Dark mode on-off button with checkbox

Console.logs are not showing. And my functions are not working. I tried several different functions and solutions but none of them worked for me. Where is the problem can anyone help?

this my html

<div class="switch-toggle darkmodecheckbox">
              <input type="checkbox" name="checkbox" id="darkmodeonoff" />
              <label for="darkmodeonoff"></label>
            </div>

this my js;

var checkbox = document.querySelector("input[name=checkbox]");
    console.log(checkbox);

    checkbox.addEventListener("change", (e) => {
      if (e.target.checked) {
        darkmode();
        console.log("Checkbox is checked..");
      } else {
        darkmodeoff();
        console.log("Checkbox is not checked..");
      }
    });



Don't work checkbox with React Bootstrap Modal in ReactJS

My code is not working. Please help.

import React, { useEffect, useState } from "react";
import { Form, Modal } from "react-bootstrap";
import "react-datepicker/dist/react-datepicker.css";

const OccasionModal = ({ setOccasionModalShow }) => {
  const [occasions, setOccasions] = useState([]);

  useEffect(() => {
    fetch("occasions.json")
      .then((res) => res.json())
      .then((data) => setOccasions(data));
  }, []);
  return (
    <div>
      <div className="container">
        <Modal
          show={true}
          fullscreen={true}
          onHide={() => setOccasionModalShow(false)}
        >
          <Form>
            {["checkbox", "radio"].map((type) => (
              <div key={`inline-${type}`} className="mb-3">
                <Form.Check
                  inline
                  label="1"
                  name="group1"
                  type={type}
                  id={`inline-${type}-1`}
                />
                <Form.Check
                  inline
                  label="2"
                  name="group1"
                  type={type}
                  id={`inline-${type}-2`}
                />
                <Form.Check
                  inline
                  disabled
                  label="3 (disabled)"
                  type={type}
                  id={`inline-${type}-3`}
                />
              </div>
            ))}
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default OccasionModal;

My code is not working. please help. My code is not working. please help. My code is not working. please help. My code is not working. please help. I try it many times but can't find a solution. I can't identify which problem is happening.




React Native checkbox icon from "Tick" to "-"(hyphen)

I am using react native checkBox from "@react-native-community/checkbox". I am able to use it correctly. But, my question is how can I change the tick icon inside the checkbox to hyphen inside the checkbox(indeterminate checkbox).

<CheckBox
   value={isSelected}
   onValueChange={setSelection}
   style={styles.checkbox}
 />



samedi 13 août 2022

i want to create checkbox inside a button

i have created checkbox inside button i have already assigned some task to button , now problem is as I check on checkbox it is affecting my button's functionality here is code i wrote for

let btn = `<div class = "btn-btn-div${index}"> </div>`;
    eachDiv.insertAdjacentHTML("beforeend", btn);
    let { varients } = dataObject;
    varients.forEach((keys) => {
        let buttonHtml = document.querySelector(`.btn-btn-div${index}`);
        buttonHtml.innerHTML += `<button id="${keys.id}${index}" class="btn-class${index}" style="border: solid black"> ${keys.title}
        <span><input type="checkbox" id="check-inside-btn${index}" value = "${keys.id}${index}">
        <label for="check-inside-btn${index}"></label>
        </span></button>        
        `;
        // console.log(buttonHtml);
    });

I want as I click on checkbox it gave me id of that checkbox and does not affect the functionality of button




How to click the Checkbox with Selenium and Python

I am new on selenium and in this case I'm trying build code with selenium python to click checkbox from this HTML:

<div class="checkBox" xpath="1"><input type="checkbox" name="registerPrivacyAgreement" id="registerPrivacyAgreement" value="1"><label for="registerPrivacyAgreement" lang="lang_9" class="privacyAgreement">I acknowledge that my data will be processed in accordance with the <a target="_blank" href="PrivacyPolicy.html">Privacy Policy.</a> &amp; <a target="_blank" href="UserAgreement.html">User Agreement.</a></label></div>

Snapshot of the checkbox:

This Capture From chrome

I already try to click that checkbox from xpath with this code:

driver.find_element(By.XPATH,"/html/body/div[4]/div[1]/div[12]/div/div[4]/input").click()

I also tried by ID, & CSS_Selector but when I run, its doesn't click the checkbox but open newpage about UserAgreement I already try with other way but it always open newpage about UserAgreement not click the checkbox. Then I try with selenium IDE and record after that I play and then its work, but when I copy code from selnium IDE it show like this:

xpath=//div[@id='container']/div/div[12]/div/div[4]/label

Then i try back to my python code and it still open newpage about UserAgreement not click that checkbox. can someone explain me what happen and how to solve that?

Element Snapshot:

Checkbox I want to click




vendredi 12 août 2022

JavaScript: how to undo a checkbox change event? [duplicate]

I have a list of articles in a HTML table and each row has a cell with a checkbox at the end, so that an article can be (un)selected. When the user clicks a checkbox, its onchange event performs a test in the database, that can either return true or false. When false is returned, i want to undo the click action, so that the old checkbox value is restored:

chb.checked = !chb.checked

Unfortunately, this does not work. The chb.checked value changes, but not the checkbox itself. I think that this is due to the fact that the assignment is taking place inside the onchange event.

The checkbox is created in this way:

chb = document.createElement("input");
chb.type = "checkbox";
chb.onchange = () => toggle_movi_status(chb,imdb)

The onchange function looks as follows:

async function toggle_movi_status(chb,imdb) {
  var url;

  var formData = new FormData();
  formData.append("user", JSON.stringify(g_user));
  url = "util.php?func=toggle_movi_status&imdb=" + imdb;
  await fetch(url, {
    method: 'POST',
    body: formData})
    .then((resp) => resp.json())
    .then(function(data) {
      if (data.status != "ok")
        chb.checked = !chb.checked; /* = undo */
    })
    .catch(function(error) {
    });
}

Could anybody please clarify this for me and/or offer me a solution that works? Plain vanilla JS please.




Change the background colour of a CheckBox using DataTriggers

I'd like the background of my CheckBox to change colour depending on if it matches a pre-defined bool (not just if it's Checked or Unchecked). The problem is that this looks poor if you do it to the CheckBox alone, so I've wrapped the CheckBox in a Grid and set the background of the Grid instead. My issue now is that I want to pull out this style so I can reuse it for my other Checkbox

Here is my XAML:

<Grid Margin="5 10 0 0">
    <CheckBox Name="cbJimbo" Content="JIMBO" FontSize="12"
    IsChecked="{Binding MyObject.Jimbo}"                                                                
    Style="{StaticResource CheckBoxStyle}"/>
    <Grid.Style>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=cbJimbo, Path=Background}" Value="Yellow">
                    <Setter Property="Background" Value="Yellow" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>
</Grid>

What is the best way to refactor this?

In the interest of completeness (Although not entirely relevant) here is the CheckBox style, which determines if the CheckBox matches the default value and then sets the CheckBox background in a too subtle fashion. Also relevant as my Grid is currently bound to the background of this Checkbox:

<Style x:Key="ValidationCheckBox" TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <StackPanel>
                    <AdornedElementPlaceholder x:Name="placeholder"/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
        Path=(Validation.Errors)/ErrorContent.ErrorType}" Value="{x:Static wrapper:ErrorTypeEnum.Default}">
            <Setter Property="Background" Value="Yellow"/>
        </DataTrigger>
    </Style.Triggers>
</Style>



I added checkbox in flutter but it can't clickable

I added checkbox but it can't click please tell me reason

enter image description here




Checkbox count Vue js

Hi all I am new in Vue js and have a question. I have created such a checkbox

<input v-model="compared" type="checkbox" name="compare" value="compare"> And I want to create a function to control this. In the function I want to limit the number of selected boxes to 3 and arrange it to redirect to another page when it reaches 3. Is there anyone who can help with this?




jeudi 11 août 2022

Database and Checkbox don't match

I have a database set for Clients that require special things when shipping. I am attaching pictures but if I am to search a client it should read the database and check the boxes that are checked there. programming

This is how I programmed it so not b code but just filling in the databindings

Database

This is what the database looks like

Client Search Database This is the database for a client for example no check marks

Client Shows

And as you see it still shows boxes that are checked for the same client.

I am not sure why its reading different values? And the client above or below this one doesnt match the actual search either. What did I do wrong?




Why I am keep getting "Element type is invalid" error with react-native-community checkbox?

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import CheckBox from '@react-native-community/checkbox';

export default function Checkbox() {
    const [state, setState] = useState({ react: false });
    return (
        <View>
            <CheckBox
                value={state.react}
                onValueChange={value =>
                    setState({
                        ...state,
                        react: value,
                    })
                }
            />
            <Text>React js</Text>
        </View>
    );
}



Unable to submit a multi-select checkbox input using formik in react

My form using formik does not currently return a value for the multi-select checkbox input component. I know I need to wrap the check box function component in the formik Field for formik to recognise and grab the component data. However, when ever I do so, It throws an error and the page goes blank.

How best can I integrate this component with formik so I can successfully submit the form.

Checkbox multi-select input compoenet

import React, { useState } from "react";
import { MultiSelect } from "react-multi-select-component";

const options = [
  { label: 'Sunday', value: 'sunday' },
  { label: 'Monday', value: 'monday'},
  { label: 'Tuesday', value: 'tuesday'},
  { label: 'Wednessday', value: 'wednessday'},
  { label: 'Thursday', value: 'thursday'},
  { label: 'Friday', value: 'friday'},
  { label: 'Saturday', value: 'saturday'},
  { label: "Week", value: "week", disabled: true },
];

const SelectFields = ({name}) => {
  const [selected, setSelected] = useState([]);

  return (
    <div>
      {/* <pre>{JSON.stringify(selected)}</pre> */}
      <MultiSelect
        options={options}
        value={selected}
        onChange={setSelected}
        labelledBy="Select"
        name={name}
      />
    </div>
  );
};

export default SelectFields;

Parent component where I'm using formik

import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const NewRates = () => {
  
 // code here were removed...

  const initialValues = {
    rateName: '',
    price: '',
    availableForPurchase: '',
    availableType: '',
    accessLevel: false,
    validationType: '',
    durationOfRate: '',
    startTime: '',
    endTime: '',
    startTimeDate: '',
    endTimeDate: '',
  };

  const validationSchema = Yup.object().shape({
  });
  const handleRates = (formValue) => {
       console.log('formValue', formValue)
  };
  
  return (
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleRates}
          >
            <Form>
              {!successful && (
                <FormWrapper>
                      // codes here were removed.
                      <>
                        <h6>Purchase Availability</h6>
                        <FormGroup>
                          <label htmlFor="AvailabilityForPurchase">
                            Select Days as required
                            <SelectFields name='availableForPurchase'/>
                            <ErrorMessage
                              name='availableForPurchase'
                              component='div'
                              className='alert alert-danger'
                            />
                          </label>
                        </FormGroup>

                         ....other codes

I have checked other similar solutions. But none come close to solving my issue.




mercredi 10 août 2022

Clear cells when checking a checkbox

I had this spreadsheet/script combo working perfectly, then made some visual/organization changes, and now it's not and I'm stumped why.

On the 1st sheet 'Filter' the checkbox in G1 is supposed to clear all of the cells in row 3 (which are my filter conditions).

Any pointers what I'm missing are appreciated!

https://docs.google.com/spreadsheets/d/1syLb6XaAWzmDecMzKWP9TpxZrMprYhLxBqQ4E8hTmmM/edit?usp=sharing

I'm not sure if you're able to view the script or not – here's what I've got currently:

function onEdit(e) {
  if (e.range.columnStart === 7 && e.range.getValue() === TRUE)
    ClearCells();
}

function ClearCells() {
 var sheet = SpreadsheetApp.getActive().getSheetByName('Filter');
 sheet.getRange('A3:F3').clearContent();
}



mardi 9 août 2022

Validating old method in control does not work correctly with empty value

In laravel 9, breeze form I use old method in controls like :

<x-input id="text" type="text" name="text" value="" />
...
<input type="checkbox" @if (old('published') ? old('published') : $subscription->published) checked @endif

But it does not work correctly in case when in text input I leave empty text and I leave published field unchecked :

text input shows $subscription->text(If it had some content from db) and published checkbox is checked (If ($subscription->published) was checked priorly from db)

How can it be fixed ?

Thanks!




lundi 8 août 2022

Trigger the function of checked boxes to one button js

I wanted to if I could do this with only using javascript. I have a pdf links on each of my checkboxes. So if the selected checkboxes are checked then it would go to that links but only when the button is clicked.

$(function() {
  $("input[name='check[]']").bind("myCustomButtonClick", function() {
    var item = $(this);
    if (item.is(":checked")) {
      item.siblings('a.dev-link').trigger('click');
    }
  });
})

$(document).on('click', '#dl-link', function() {
  $("input[name='check[]']").trigger("myCustomButtonClick");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label id="link" class="w-checkbox dl-check-wrap">
  <div class="w-checkbox-input w-checkbox-input--inputType-custom dl-check dev-check w--redirected-checked"></div>
  <input type="checkbox" name="check[]" data-name="check[]" id="mode">
  <a href="https://drive.google.com/uc?export=download&amp;id=17XNOXQ3dKZM9tznx4xGk8I0O5hcvw0kc" class="dl-link dev-link">Link</a>
  <span class="d-none w-form-label" for="check[]">Checkbox 4</span>
</label>

<a id="dl-link" href="#" class="dl-btn w-button">Download All</a>



How to get the value of the selected checkbox in jQuery

I have a filter function whereby a user can check one or multiple amenities and get the values which will be sent to the database using AJAX.

In this case upon clicking one checkbox I also want to get the values of the other checkboxes if they are checked.

On clicking the #balcony input I will get the value of the balcony, also when I click the #wifi checkbox I want to get the 'yes' value

How can I achieve this? I have tried the following logic but it doesn't work.

$("#balcony").on('click', function() {
  var balcony = $(this).val();
  var wifi = $("#wifi").prop('checked');
  var parking = $("#parking").prop('checked');
  var generator = $("#generator").prop('checked');

  console.log(wifi);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="card-body">
  <div class="card-title" style="margin:0px; padding:3px;">
    <h5 style="color: black; font-size:18px;">Amenities</h5>
  </div>
  <div class="checkbox checkbox-success">
    <input type="checkbox" name="filterbalcony" value="yes" id="balcony">
    <label for="rentalcat" class="control-label">Balcony</label>
  </div>
  <div class="checkbox checkbox-success">
    <input type="checkbox" name="filtergenerator" value="yes" id="generator">
    <label for="rentalcat" class="control-label">Generator</label>
  </div>
  <div class="checkbox checkbox-success">
    <input type="checkbox" name="filterwifi" value="yes" id="wifi">
    <label for="rentalcat" class="control-label">Wifi</label>
  </div>
  <div class="checkbox checkbox-success">
    <input type="checkbox" name="filterparking" value="yes" id="parking">
    <label for="rentalcat" class="control-label">Parking</label>
  </div>
</div>



dimanche 7 août 2022

How Can I Create Data in Bar Chart in Response to Checkboxes?

This is my first time creating a bar chart which I just watched from a tutorial on youtube. (It was pretty much me typing-along.) I'd like to know how I can make it responsive when a user clicks on a checkbox, which will then increase the values of [x], [y], and/or [z] by 25.(There are box 4 checkboxes for each.) I read that I need to create an event listener, but I'm not sure how to access the data. I really appreciate the help!

let myChart = document.getElementById('myChart').getContext('2d');

let barChart = new Chart(myChart, {
    type: 'bar',
    data: {
        labels:['x', 'y', 'z'],
        datasets:[{
        label: "numbers",
        data:[
            [x],
            [y],
            [z]
        ]
    }]
    },
    options: {},
});



samedi 6 août 2022

How can I set checkbox to checked in a datatable column when a master checkbox is checked

I have a datatable for class attendance that is comprised of a student name and 4 columns of checkboxes per row. The Select All column is for the user to dynamically set checked/unchecked attribute for the remaining checkboxes in the row. Ultimately, the form will be saved and the database updated with the value of the checkboxes. When the form is presented, the database does not contain a record of what is presented to the user, it will be inserted when the form is saved.

Select All  Student Name    On Time  Present  Contributing  Prep Lesson 
     x      Mickey Mouse        o       o          o            o

HTML:

<table id="UserTable" class="table table-bordered"> 
    <thead>
      <th style="text-align:center;">Select All</th>
      <th style="text-align:center;">Student Name</th>
      <th style="text-align:center;">On Time</th>
      <th style="text-align:center;">Present</th>
      <th style="text-align:center;">Contributing</th>
      <th style="text-align:center;">Prep. Lesson</th>
    </thead>

    <tbody>
        <?php if(!empty($students)) { ?>
        <?php foreach($students as $student) { ?>
          <tr>
            <div class="container content">
              <!-- select all -->
              <td style="text-align:center;"><input type="checkbox" id="select-all" onchange="selectAll(this)"></td>
              <!-- student -->
              <td class="student-name"><?php echo $student['first_name'] . ' ' . $student['last_name'] ?></td>
              <!-- on-time -->
              <td class="on-time" style="text-align:center;"><input type="checkbox" id="on-time"></td>
              <!-- Present -->
              <td class="present" style="text-align:center;"><input type="checkbox" id="present"></td>
              <!-- contributing -->
              <td class="contribute" style="text-align:center;"><input type="checkbox" id="contribute"></td>
              <!-- prepared lesson -->
              <td class="prep-lesson" style="text-align:center;"><input type="checkbox" id="prep-lesson"></td>            
          </tr>  
      <?php }} ?>
    </tbody>
</table>
Attempts at Javascript code which do not work:
<script type="text/javascript">

      $(document).ready(function(){
        $('#UserTable').DataTable();
      });

      $('#UserTable tbody').on( 'click', 'tr td:eq(0)', function () {
        //var onTime = $(this).parents('#userTable tbody").siblings('#on-time');         
        //$(onTime).attr('checked', true);
        alert("col1");
      });

      function selectAll(elem) {
        alert('in onChange');
        var table = $('#UserTable').DataTable();
        if(elem.checked) {
          // var onTime = $(this).parents('#userTable tbody').siblings('.on-time');     
          // var colData = table.column(this).data();          
          // $(onTime).attr('checked', true);

          alert('checked');
        }
        else {
          alert ('unchecked');
        }
      }
</script>
Thanks for your help,
Dennis



vendredi 5 août 2022

Extendscript Optimization/State Toggle

I am working on an InDesign plugin using ExtendScript that uses dialog checkboxes to generate variables based on user inputs. These variables are intended to store user-selected option data to be referenced later in the script when assembling a larger document. (Option A brings in pages 5-10 of a document to a new master, Option B brings in pages 11-14, etc.) Currently, I have two main issues:

  1. When selecting an option, the readonly textbox populates with the selected option's name as intended, however ticking a checkbox off removes all of the text instead of just the option name. I realize the subtraction operator is likely at fault here. Is there a better recommendation for removing text from a string? Here is a visualization for TL;DR: 1 2 3 4 5
  2. I cannot seem to properly optimize the dynamic code. I can grab all of the checkboxes and their values and plug them into arrays after the window.show() function, however the only way I am able to dynamically change the text within the readonly text window is by initializing a function to run for each option as shown here, and doing so before window.show():
//Variable Declaration for context
var AOpt = w.tabs[0].add('edittext', [0, 0, 350, 70], 'No Options Selected', {readonly: true});
var A1 = AOps.add ('checkbox {text: "Option 1"}'); //AOps is the panel which the checkboxes populate
const origResp = 'No Options Selected'; //Original Response in textbox

//How might I optimize this for each option?
A1.onClick = function() {
 if(AOpt.text !==origResp) {        
        if (A1.value == true) {           
                    AOpt.text = AOpt.text + A1.text;                
        } else if (A1.value == false) {
                    AOpt.text = AOpt.text - A1.text;
                                      }
        }else{
                    AOpt.text = A1.text;    
             }
}

A1 is a single unit in a series of 10 options (A1-A10) for Model A, and there are at least 6 models. Incorporating functions for each option in the full project would add close to 600 lines of code alone. This snippet will not run, but I've included a codepen with the full, functional code for this section of the script.

var aArray = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10]; grabs the checkboxes, and I can check their value if I add this code after window.show(), however I can't get the text to dynamically populate after the window is shown:

for (i=0; i<aArray.length; i++){
        alert(aArray[i].value);}

Are there better management options for state control and optimization with Extendscript?