samedi 30 septembre 2023

Why is my setState in useState working the opposite way?

I am implementing a select all checkbox in typescript.

This is what it looks like: enter image description here The checkbox besides "Songs" is the select all checkbox,but when it turns to checked, the other checkboxed become unchecked,and become checked when it is unchecked,just like the picture shows.

It works fine in the first few change, but failed after about three change.

Here is my code:

const [check, setCheck]=useState(false);
async function allCheck(e:any){
  console.log(e.target.checked);
  setCheck(e.target.checked);
  console.log(check);
  e.stopPropagation();
  cards.forEach(async (card) =>{
    console.log(card);
    await updateCard(card.id, {
      checked : check,
    });
    let song=document.getElementById(card.id);
    console.log(song);
    if(song){
      let checkbox=song.querySelector('input[type="checkbox"]') as HTMLInputElement;
      if(checkbox){
        checkbox.checked = card.checked;
      }
    }
  });
  fetchCards();
}

Here is what the javascript console prints when the top checkbox is checked: enter image description here true is for console.log(e.target.checked) and false is for console.log(check)

Why is this happening?And I also want to know how to fix it. Thanks!




vendredi 29 septembre 2023

Is the CSS property appearance: none a valid tool for hiding checkboxes style?

I've been looking for a way to restyle checkboxes using icons no matter where the label is or whether it's present or not. In the end I found https://developer.mozilla.org/en-US/docs/Web/CSS/appearance
And it looks like appearance: none works for both Firefox and Chrome, but I read it's been removed from the CSS 3 specification but it's still present in the CSS Basic User Interface Module Level 4, caniuse reports this being supported by essentially all major browsers https://caniuse.com/css-appearance .
So my question is can I safely use appearance: none for customizing checkboxes or am I at risk of having browser incompatibilities or having it being changed/removed in a not so distant future?




How to required a date input field when checkbox checked is true in react hook form?

Suppose i have a checkbox , it's not a required field. if user checked it a date input field will be shown. and date field is required and date must be a past date. if user unchecked the checkbox , date field will not be a required field. and no error will be shown when user submit the form . and form will be submitted . I am using react-hook-form version "^7.43.9" .

I have tried to do this like this. it's working fine but it's givinig me initially error when  i give defaultValue="" and it's giving me date field is required when I checked the checkbox then did not select any date and unchecked the checkbox. Where as i want date field will be required only when checkbox is checked true, if user unchecked checkbox , date will be not required.


const validationSchema = yup.object().shape({
  roofDate: yup
    .date()
    .typeError("Please enter a valid date")
    .max(
      new Date(Date.now() - 86400000),
      "Date can not be future or current date"
    )
    .when("roofCheck", {
      is: true,
      then: yup.date().required("Roof date is required"),
    })})

                  <div className="col-md-6 col-lg-3">
                    <div className="mb-3">
                      <label className="brand-label d-grid">
                        <div className="form-check form-check-inline">
                          <input
                            className="form-check-input"
                            type="checkbox"
                            id="roofCheck"
                            name="roofCheck"
                            value="Roof"
                            {...register("roofCheck")}
                          />
                          <label
                            className="form-check-label"
                            htmlFor="roofCheck"
                          >
                            Is Roof Updated?
                          </label>
                        </div>
                      </label>

                      {watch("roofCheck") && (
                        <>
                          <input
                            type="date"
                            id="roofDate"
                            className="form-control"
                            rules=
                            placeholder="Enter Roof Date"
                            {...register("roofDate")}
                          />
                        </>
                      )}
                      {errors.roofDate && (
                        <p className="text-danger">
                          {errors.roofDate?.message}
                        </p>
                      )}
                    </div>
                  </div>



jeudi 28 septembre 2023

How to keep the state of a checkbox component in dynamic list with Angular?

I have a problem with my “Affect Subject Page”, I would save the state from the checkbox after reloading or refreshing page. I am using dynamic data retrieve from a MySQL database using the Restful ws to communicate with a back project developed with Spring boot.

Below is the scenario for assigning the subject to a learner:

  1. The trainer chooses the subject to assign:
  1. It can assign the subject to one or more learners, by clicking on the checkbox button:



mercredi 27 septembre 2023

How to create a WPF CheckBox with a larger mark?

In a previous question, I tried to look for an already existing solution for creating a CheckBox with a larger mark, but that question got downvoted as a duplicate, which I don't understand.

So I went further, and found an intermediate solution, based on "triggerable" LinearGradients.

This is what I currently have:

    <UserControl.Resources>
        <Style x:Key="CustomCheckBoxStyle"
               TargetType="CheckBox">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="40"/>
                                <ColumnDefinition Width="auto"/>
                            </Grid.ColumnDefinitions>
                            <CheckBox IsChecked="{TemplateBinding IsChecked}"
                                      Content="{TemplateBinding Content}"
                                      Grid.Column="1"
                                      HorizontalAlignment="Stretch"
                                      VerticalAlignment="Stretch">
                             </CheckBox>
                            <Rectangle x:Name="checkBoxRectangle"
                                           HorizontalAlignment="Left"
                                           Width="40"
                                           Height="40">
                                <Rectangle.Fill>
                                    <LinearGradientBrush StartPoint="1,0" EndPoint="0,1">
                                        <GradientStop Color="White" Offset="0.0" />
                                        <GradientStop Color="White" Offset="0.4" />
                                        <GradientStop Color="Black" Offset="0.4" />
                                        <GradientStop Color="Black" Offset="0.6" />
                                        <GradientStop Color="White" Offset="0.6" />
                                        <GradientStop Color="White" Offset="1.0" />
                                    </LinearGradientBrush>
                                </Rectangle.Fill>                                               
                            </Rectangle>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsChecked"
                                     Value="True">
                                <Setter TargetName="checkBoxRectangle"
                                        Property="Fill"
                                        Value="Green"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
...
<CheckBox Style="{StaticResource CustomCheckBoxStyle}" 
          Grid.Row="1" Grid.Column="0" FontSize="26" Name="Chk_Something" 
          Content="Geladen?"
          HorizontalContentAlignment="Left"
          VerticalContentAlignment="Center">
</CheckBox>

... and it looks like this:

enter image description here

So, now the idea becomes:

  • How do I get rid of the small square, at the left side of the word?
  • How to I take the union of two LinearGradientBrushes? (I know that, by changing the start- and endpoint from (1,0) and (0,1) into (0,0) and (1,1), I get the black bar in the other direction, so a union of both would make a beautiful cross)
  • How can I use this as a value in the trigger's setter?

Of course, if you know an easier way to make a WPF CheckBox with a larger mark, don't hesitate informing me :-)




mardi 26 septembre 2023

Is there a CheckBox control with adjustable mark size? [duplicate]

I'm developing a C# WPF application, where some screens are to be shown on a separate touch screen, and the regular WPF CheckBox's mark (the square where you need to click) is quite small.

I've been looking for a solution, but I don't understand the MSDN reference from this other question, therefore I'm asking for another solution).

Until now, I've managed to get the height in order (by setting VerticalContentAlignment to "Stretch"), but now the mark isn't a square anymore, and HorizontalContentAlignment does not seem to solve this).

Without vertical stretching: (Ok, it's square but NOK, it's too small)

<CheckBox Grid.Row="1" Grid.Column="0" 
          Content="Geladen?" 
          HorizontalContentAlignment="Stretch"
          VerticalContentAlignment="Center">

Screenshot:

Screenshot_without_VerticalContentAlignment

With vertical stretching:(Ok, it's large enough but NOK, it's not a square)

<CheckBox Grid.Row="1" Grid.Column="0" 
          Content="Geladen?"
          HorizontalContentAlignment="Stretch"
          VerticalContentAlignment="Stretch">

Screenshot:

enter image description here

Thanks in advance




lundi 25 septembre 2023

How to display checkboxes options at multiple columns in contact form 7?

I have a checkbox with 30 options, and I want to show them in 3 responsive columns. How can I do this with Contact Form 7?

Three Column CheckboxesI'm expectig the first, but i'm getting the second image. The inline checkboxes




samedi 23 septembre 2023

Javascript set checkbox checked value to false [closed]

I'm having an issue with Javascript. I'm trying to limit the number of checked checkbox to 5. I have a Javascript script that shows me the alert I ask to show but the still put the checkbox on checked.

To do so I'm using this Javascript script:

function change(_this) {
   if ($('input[type=checkbox]:checked').length > 5) {
      alert("allowed only 5");
      this.checked = false;
   }
}

I've tried also

$(this).prop('checked', false);

And my checkboxes are the classical one

<input type="checkbox" name="memberName" value="Name1" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name2" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name3" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name4" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name5" onchange="change(this)">
<input type="checkbox" name="memberName" value="Name6" onchange="change(this)">

What can cause this issue?




Dynamically added checkbox is not clickable when inserted to a html table (typescript)

I am trying to create a simple website that displays bank transactions on credit card (side project for learning TS and html).

The website displays all transactions between two dates (after dates are chosen) in a dynamically created table and it also creates a column with checkboxes to choose which transactions should be submitted for approval (uppon pressing a dedicated button for approval, the checked transactions are posted through restful api to an independant backend service).

The table is formed through the typescript correctly with all it's rows and correct data, but when I add the checkboxes, they don't respond to clicks (impossible to check / uncheck).

This is the code for the dynamic addition of rows to the table:

const addCells = (table: HTMLElement, currTransaction:any, color:string) => {
  const descriptors = ["Description", "TransactionDate", "Amount", "Currency", "Status"];
  const row = document.createElement("tr");
  for (let i in descriptors) {
    const createdCell = createCell(currTransaction, descriptors[i]);
    row.appendChild(createdCell);
  }

  applyRowStyling(row, color);
  addCheckBox(row, currTransaction);

  table.appendChild(row);
}

const createCell = (currTransaction:any, currDescriptor:string):HTMLTableCellElement => {
  const tableCell = document.createElement("td");
  tableCell.style.border = "black solid 1px";
  const descriptorText = document.createTextNode(currTransaction[currDescriptor]);
  tableCell.appendChild(descriptorText);
  return tableCell;
}

const addCheckBox = (row:HTMLTableRowElement, currTransaction:any) => {
  const tableCell:HTMLTableCellElement = document.createElement("td");
  tableCell.style.border = "black solid 1px";
  const checkbox:HTMLInputElement = document.createElement('input');
  checkbox.setAttribute('type', 'checkbox');
  checkbox.checked = false;
  checkbox.disabled = false;
  // checkbox.name="approvalCheckbox"
  checkbox.id = currTransaction['TransNum'];

  tableCell.appendChild(checkbox);
  checkBoxes.push(checkbox);

  row.appendChild(tableCell);
}

const applyRowStyling = (row:HTMLTableRowElement, color:string) => {
  row.style.backgroundColor = color;
  row.style.border = 'black solid 1px';
  row.style.textAlign = 'center';
}

const checkBoxes = [];

const addCells = (table/*: HTMLElement*/, currTransaction/*: any*/, color/*: string*/) => {
    const descriptors = [
        "Description",
        "TransactionDate",
        "Amount",
        "Currency",
        "Status",
    ];
    const row = document.createElement("tr");
    for (let i in descriptors) {
        const createdCell = createCell(currTransaction, descriptors[i]);
        row.appendChild(createdCell);
    }

    applyRowStyling(row, color);
    addCheckBox(row, currTransaction);

    table.appendChild(row);
};

const createCell = (
    currTransaction/*: any*/,
    currDescriptor/*: string*/,
)/*: HTMLTableCellElement*/ => {
    const tableCell = document.createElement("td");
    tableCell.style.border = "black solid 1px";
    const descriptorText = document.createTextNode(
        currTransaction[currDescriptor]
    );
    tableCell.appendChild(descriptorText);
    return tableCell;
};

const addCheckBox = (row/*: HTMLTableRowElement*/, currTransaction/*: any*/) => {
    const tableCell/*: HTMLTableCellElement*/ = document.createElement("td");
    tableCell.style.border = "black solid 1px";
    const checkbox/*: HTMLInputElement*/ = document.createElement("input");
    checkbox.setAttribute("type", "checkbox");
    checkbox.checked = false;
    checkbox.disabled = false;
    // checkbox.name="approvalCheckbox"
    checkbox.id = currTransaction["TransNum"];

    tableCell.appendChild(checkbox);
    checkBoxes.push(checkbox);

    row.appendChild(tableCell);
};

const applyRowStyling = (row/*: HTMLTableRowElement*/, color/*: string*/) => {
    row.style.backgroundColor = color;
    row.style.border = "black solid 1px";
    row.style.textAlign = "center";
};

addCells(
    document.getElementById("the-table"),
    {
        "Description": "The description",
        "TransactionDate": new Date(),
        "Amount": 42,
        "Currency": "USD",
        "Status": "pending",
    },
    "white"
);
#the-table {
    margin-top: 50px;
}
<table id="the-table"></table>

I've tried to manually create a checkbox in the table in the html file in the form:

        <tr>
          <td><input type="checkbox"></td>
        </tr>

Which caused the checkbox to work (but of course does not help as I need the checkboxes to be added dynamically).

I tried to use addEventListener and onclick on both the element and the checkbox and it still does not respond (does not call the callback function I registered).




vendredi 22 septembre 2023

ag-grid: Multiple independent headerCheckSelection Boolean columns which toggle states of entire column values?

One or more ag-grid Boolean checkbox columns need to have a check(true)/uncheck(false) all capability.

The headerCheckSelection column property nicely shows a checkbox in the column header name (see below). It though is used for row selection which is not the intent.

Three Boolean columns, two with headerCheckSelection Image

Can the headerCheckSelection column property be used with other properties/functions to toggle the Boolean values of its column entries without selecting any rows? This needs to work for multiple Boolean columns where each is independent of the others.

If not, what other options are available for having a column specific check/uncheck all capability?




jeudi 21 septembre 2023

Equipment Log Google Sheets - fixing while/for loop in Google Apps Script for check in/check out based on checkbox

I am trying to create a script on google sheets where when I click a checkbox, another sheet is updated with a new row with a log of that click. My issue right now:

I'm trying to get it so that when I uncheck the checkbox, it logs when it was unchecked. My issue is, I can't find a workaround from a while loop or a conditional loop where after it's set to false it does the action once and does not continually do so. Here is my code:

function hours12(today=(new Date())) { 
  let hours = (today.getHours() + 24) % 12 || 12;
  return hours;
}

function TIMESTAMP() {
  let today = new Date();
  let mins = ('0'+ today.getMinutes()).slice(-2);
  let seconds = ('0'+ today.getSeconds()).slice(-2);
  let hours = hours12(today)
  let date = (today.getMonth()+1)+'-'+today.getDate()+'-'+ (today.getYear()-100);
  let time = hours + ":" + mins + ":" + seconds;
  let dateTime = date+' '+time;
  return dateTime;
}  
function onEdit() {
  let ss = SpreadsheetApp.getActive();
  let sheet = ss.getSheetByName('check-out');
  let logSheet = ss.getSheetByName("equip-log");
  let selectedRow = sheet.getActiveRange().getRow();
  let checkbox = sheet.getRange(selectedRow, 5).getValue();
  let person = sheet.getRange(selectedRow, 2).getValue();
  let equip = sheet.getRange(selectedRow, 1).getValue();
  let condition = sheet.getRange(selectedRow, 4).getValue();
  let checkout = sheet.getRange(selectedRow, 3).getValue();
  
  while (checkbox == true) {
    if (person == '' || equip == '' || condition == '' || checkout == '') {
      Logger.log('Incomplete row information while true');
      break;
    } else {
      addValues(checkbox, logSheet, equip, person, condition, checkout);
      break;
    }
  }
  if (checkbox == false) {
    let logRange = logSheet.getDataRange().getValues();
    for (i=0; i<logRange.length;i++) {
      let rangeValue = logRange[i];
      console.log(selectedRow)
      if (!rangeValue.includes(equip, person, condition)) {
        Logger.log('Incomplete row information while false');
      } else {
        addValues(checkbox, logSheet, equip, person, condition, checkout);
        sheet.getRange(selectedRow, 2).clearContent();
        sheet.getRange(selectedRow, 4).clearContent();
      }
    }
  }
}

function addValues(checkbox, logSheet, equip, person, condition, checkout) {
  const current = TIMESTAMP()
  if (checkbox == true) {
    logSheet.appendRow([equip, person, checkout, '', condition])
  } else {
    logSheet.appendRow([equip, person, '', current,  condition])
  }
} 



Checkbox requirements for random generator not going into sum

I have a password generator that when you hit generate, you get a password. It has 4 options with 0.5 chance to change a character generated at length if checked. When I add the checkboxes for NUMBERS and SYMBOLS it stops working.

const generateBtn = document.getElementById('generate')
const passwordDisplay = document.getElementById('passwordInput')

const checkUpper = document.getElementById('checkUppercase')
const checkLower = document.getElementById('checkLowercase')
const checkNumber = document.getElementById('checkNumber')
const checkSymbol = document.getElementById('checkSymbol')

function rangeSlider() {
  let slider = document.getElementById('slider')
  let output = document.getElementById('numCount')
  output.innerHTML = slider.value
  slider.oninput = function() {
    output.innerHTML = this.value
  }
}

function generatePassword() {
  passwordArray = []
  let length = document.getElementById('slider').value
  let password = ''
  let upper = checkUppercase.checked
  let lower = checkLowercase.checked
  let number = checkNumber.checked
  let symbol = checkSymbol.checked

  let characters = `abcdefghijklmnopqrstuvwxyz`;
  let uppercaseCharacters = `ABCDEFGHIJKLMNOPQRSTUVWXYZ`

  if (upper && Math.random() < 0.5) {
    characters += uppercaseCharacters
  }
  if (lower && Math.random() < 0.5) {
    characters = characters.replace(uppercaseCharacters, '')
  }
  if (number && Math.random() < 0.5) {
    characters += `0123456789`
  }
  if (symbol && Math.random() < 0.5) {
    characters += `!@#$%^&*()_+~\`|}{[]\:;?><,./-=`
  }

  let charactersLength = characters.length;
  let counter = 0;

  while (counter < length) {
    password += characters.charAt(Math.floor(Math.random() * charactersLength))
    counter++
  }

  passwordDisplay.value = password

}

rangeSlider()
generateBtn.addEventListener('click', generatePassword)

I'm not sure when I add the two variables of number and symbol, it stops generating.Thank you for any help




mercredi 20 septembre 2023

Custom background for a checkbox not responding

I'd like the checkboxes I have to have ideally black or transparent backgrounds. Right now they're the default white. I cannot for the life of me figure out how to change it.

#checkboxes {
  position: absolute;
  top: 33%;
  left: 23%;
  right: 10%;
  width: 450px;
  height: 55px;
  font-size: 20px;
  font-weight: 700;
  border: none;
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 1rem;
  scale: 1.3;
}

input[type="checkbox"] {
  background: var(--black);
  accent-color: var(--green);
}
<aside id="checkboxes">
  <input type="checkbox" id="checkUppercase">
  <input type="checkbox" id="checkLowercase">
  <input type="checkbox" id="checkNumbers">
  <input type="checkbox" id="checkSymbols">
</aside>

Do I need to make custom boxes out of divs instead?




jQuery Multidimensional array in each loop with dynamic inputs

I have a search form with filter that has multiple input types, checkboxes and select. Also there is multiple forms on a single page so i create have a container that has a dynamic ID and feeds that value to the function as deal.

The problem I'm having is managing the checkboxes in the form. The checkboxes is grouped using the input names. All the data is collected but when there is multiple checkboxes selected only the last option gets passed on.

Example of HTML

<div class="filter__container" id="months_specials_filter">
  <button class="filter__triger_btn">Filter</button>
    <div class="filter__wrapper">
      <div class="filter__colm star_rating col-3">
        <h4>Property rating</h4>
        <select name="class" id="class">
          <option value="">Select Option</option>
          <option value="1605">2 Star</option><option value="1586">3 Star</option><option value="1593">4 Star</option><option value="1601">5 Star</option><option value="1595">Not Star Graded</option>
        </select>                  
      </div>
      <div class="filter__colm room_type col-3">
        <h4>Room Types</h4>
        <select name="room-type" id="room-type">
          <option value="">Select Option</option>
          <option value="3784">Double</option><option value="3782">Single</option><option value="3785">Triple</option><option value="3783">Twin</option>
        </select>
      </div>

      <div class="filter__colm child_friendly col-3">
        <h4>Child Friendly</h4>
        <label><input type="checkbox" value="3787" name="child-friendly" id="child-friendly"> Children Allowed</label>
        <label><input type="checkbox" value="3786" name="child-friendly" id="child-friendly"> Infants Allowed</label>
      </div>

      <button id="months_specials_apply_filter" class="filter__sumbit_btn">Apply Filter</button>  
  </div>
</div>

jQuery

var filters = {};
$('#' + deal + '_filter :input').each(function(index,elem){

  filters[elem.name] = {};
  if (elem.name != "") {
    if (elem.type == 'checkbox') {
      if($(this).prop("checked") == true){
        filters[elem.name] = elem.value;
      }
    } else {
      filters[elem.name] = elem.value;
    }
  }
  
});

I have tried using .map and .push but the variable kept getting replaced for the checkboxes. Sure its just a simple thing I'm missing. I mainly work in server side code so not that familiar with Javascript / jQuery.




Flutter Multi CheckBox List

enter image description here

Multi CheckBox List

I want to make this type of checkbox list Where I can Select One category that enables another catogery filter list to select options.

Could anyone help me to convert that logic into code ?




mardi 19 septembre 2023

A gridview that consist of two columns named as Present and pres [duplicate]

The problem is I have a lot of rows in gridview but when I checked a certain or any Checkbox, I wasn't able to add 1 in present column.

I just try that whenever I click a any Checkbox under column name "pres" it Will add 1 in "Present" column that is used for counting number of time when checkbox checked... I just need a code that whenever in any row of gridview under "pres" column I check a specific checkbox it will automatically add 1 to corresponding "Present" column value




buttonTint coverd the whole checkbox

Hi I'm having a problem with the checkbox in android I'm using minSdk24, when I use android:buttonTint to make color for the checkbox, it seems normal for the unchecked state but when the state is checked, the color covers the whole checkbox, and no tick shows up




lundi 18 septembre 2023

A Checkbox and a court column is within a gridview problem

The problem is I have a lot of rows in gridview but when I checked a certain or any Checkbox, I wasn't able to add 1 in count column.

I just need a code that whenever in any row of gridview I check a specific checkbox it will automatically add 1 to corresponding count value

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // Check if the clicked cell is in the "Attendance" column
    if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Attendance"].Index)
    {
        // Toggle the "Attendance" value in the "Attend" column
        DataGridViewCheckBoxCell checkBoxCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;

        if (checkBoxCell != null) // Check if the cell exists
        {
            // Get the current value of the "Attend" cell (assuming it contains numeric data)
            int currentAttendance = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Attend"].Value);

            // Toggle the value between "1" and "0" when the checkbox is clicked
            int newAttendance = (currentAttendance == 0) ? 1 : 0;

            // Update the "Attend" cell with the new value
            dataGridView1.Rows[e.RowIndex].Cells["Attend"].Value = newAttendance;
        }
    }
}



autofill value with the checkbox

I have created interactive grid in oracle apex now I want to make checkbox when I marked it so check by and checked date should be autofill with the SysData and user can someone tell me what I should apply code behind this.




dimanche 17 septembre 2023

Dynamically passing value to .click event Jquery

I am getting the values of a CSS class using Jquery. When I click the header, I want all of the radio boxes to be marked as checked. I loop through and find the values, using console.log to check if I am returning the correct values which I am. However when I try to use the function, it will only run it correctly on the first element in the array, where I would like it to apply to all names found in the loop.

var skil = $('.Routes');
var skills = new Array();
skil.each(function(i) {
  skills.push($(this).text());
  var Route = '#'+skills[i].replaceAll(' ','');
  console.log(Route);
   $(Route).on('click', function() {
    $(Route).prop("checked", true); //This only performs the function on the First value (in this case for "Purchased")
   });
});

Below is an extract of code which runs correctly on both headers. I could replicate this, but there are 17 classes, so ideally I would like to dynamically pass the value in and run through one function if possible.

$('#Purchased').on('click', function() {
    $('.Purchased').prop("checked", true);
});

$('#BST').on('click', function() {
    $('BST').prop("checked", true);
});

See HTML to build table below

<th class="rotate"><div><span class ="Routes" id ="Purchased"> Purchased</span></div></th>
    <th class="rotate"><div><span class ="Routes" id ="BST> BST</span></div></th>

<td bgcolor="#8DB255" class=""> <input type="radio" class="get_value Purchased" name="48215:4G1" id="r8215:4201" value="4:716:597:18.25:200:0:200:NA:PBJB_18223_JTC:375:8215:4:20:2023/09/13:284:284:284:284:284:0::0" checked=""></td>
    <td bgcolor="#8DB255" class=""> <input type="radio" class="get_value BST" name="48215:4G1" id="r8215:4201" value="4:716:597:18.25:200:0:200:NA:PBJB_18223_JTC:375:8215:4:20:2023/09/13:284:284:284:284:284:0::0" checked=""></td>



vendredi 15 septembre 2023

Is there a way to inspect the exact styling properties of checkboxes in Windows 11 and apply them as custom CSS Code while overwriting native styles?

This approach is intended to overwrite the iOS native styles for checkboxes while applying Windows' native styles instead. The problem that I want to address is that checkboxes on my page appear properly on Windows and Android but they have the wrong position and they seem to have adapting size depending on the container size on iOS devices no matter which Browser I'm using.

This is what it looks like on iOS:

This is what it looks like on Windows/Android (appearance I also want to apply on iOS devices)

This is the Code I'm using:

<div class="input-container" style="width:60%;margin-left:auto;margin-right:auto;">
                <input type="checkbox"/>
                <p>
                    Anschließende Zentrifugation der Probe, Gegengewicht nicht vergessen! 8.000 rpm für 10 min.
                </p>
            </div>
  .input-container {
        display: flex;
        text-align: justify;
        hyphens: auto;
    }
    
  .checkboxes {
    display: flex;
    justify-content: left;
    align-items: right;
    vertical-align: middle;
    word-wrap: break-word;
  }

I was not able to find the CSS Code for Windows' native checkbox styles yet. Is there a way to inspect them?




jeudi 14 septembre 2023

Why does react input checkbox not check when ticking and unticking the checkbox?

Cypress always reads it as checked if opened in edit mode and the checkbox was ticked previously and always reads it as unchecked during initial instance even if I tick it or untick it

This one is not working:

checkOnly.getCheckOnly().contains('test')
.siblings().children('input')
  .then(($ele) => {
    if (!($ele.is(':checked'))) {
      $ele.trigger("click")
    }
  })



mercredi 13 septembre 2023

Retain the search value in Autocomplete textbox even after search

I want to prevent the search text from disappearing after selecting an item from the filtered options in the Autocomplete component in mui autocomplete checkbox.

Tried setting the state variable for input as well.But it does not work. here is code sandbox link.enter image description here

https://codesandbox.io/s/zx49gs?file=/Demo.tsx:572-583

search text click on any option from search options, search text disappears




mardi 12 septembre 2023

How to read and save booleans from a repository with DataStore in Jetpack Compose

I have a repository including a list of words which I connected with a unique checkbox. Each time I close the app I want the checkbox value to be saved. So I am using Jetpack DataStore for that. It saves properly but it does it for all the words and I wish it does it for each of them separately.

I know how to retrieve that when they are String but can't figure out when they are Boolean.

My Repository

object WordRepo {

    fun getWord(wordId: String, context: Context): Words =
        getWordsList(context).find { it.wordId == wordId }!!

    fun getWordsList(context: Context) = listOf(

        Words(
            wordId = context.getString(R.string.a),
            wordName = context.getString(R.string.a),
            wordCheckBox = false
        ),

        Words(
            wordId = context.getString(R.string.cold),
            wordName = context.getString(R.string.cold),
            wordDone = false

        ),

        Words(
            wordId = context.getString(R.string.star),
            wordName = context.getString(R.string.star),
            wordCheckBox = false

        ),
)
}

My CheckBox

val scope = rememberCoroutineScope()
val dataStore = DataStore(context)
var checkBool by remember { mutableStateOf(value = word.wordCheckBox) }



    Checkbox(
        checked = checkBool,
        onCheckedChange = {
            checkBool = it
            scope.launch { dataStore.saveBool(word.wordCheckBox) }
        }
    )
}

My DataStore

    
class DataStore(private val context: Context){

    companion object {
        val Context.dataStore:
                DataStore<Preferences> by preferencesDataStore(name = "MyPreferences")

        val BOOL = booleanPreferencesKey("checked")


    }

    val getBool: Flow<Boolean> = context.dataStore.data.map {
            preferences -> preferences[BOOL]?: false }

    suspend fun saveBool(value: Boolean) {
        context.dataStore.edit { preferences-> preferences[BOOL] = value }
    }
}




Custom Checkboxes don't work in Safari on iPad. They also don't work in Firefox or Chrome on the same device

as mentioned above the css styles appear not to be applied to the checkboxes on iPad 10. Problem first discovered on safari, which then made me think that there might be some default browser styles which I couldn't overwrite yet, but since this problem also occurs in firefox and chrome on the same device it's more likely that the reason for this might be the iPad itself.

In detail:

  • the checkboxes appear like this:

Safari/Firefox/Chrome on iPad 10

They hang above the text instead of being aligned in the center of the block. They also shrink in size depending on the size of the subsequent paragraph.

They should appear like this:

Firefox on Samsung Galaxy Tab S6 lite and Firefox on Windows PC

The CSS code for the checkboxes is as following:

`.input-container {
    display: flex;
    text-align: justify;
    hyphens: auto;
}

.checkboxes {
display: flex;
justify-content: left;
align-items: right;
vertical-align: middle;
word-wrap: break-word;
}`

In HTML:

<div class="input-container" 
     style="text-align:justify; hyphens:auto; width:60%; 
            margin-left:auto; margin-right:auto;">
      <input type="checkbox"/>
      <p>
         Anschließende Zentrifugation der Probe, Gegengewicht nicht vergessen! 8.000 rpm für 10 min.
      </p>
</div>

I already tried 'appearance: none;' or '-webkit-appearance: none;' to remove default browser styles as well as !important, put the css styles at the end of the stylesheet to avoid lastrule but nothing worked so far. Apple customer support could not help me with getting insight into default browser styles (I don't have access to a mac to connect the iPad with and use Webinspector...).

So here I am hoping that there might be someone who has any idea why the checkboxes don't appear properly on that iPad 10.

Bare with me if the code looks sloppy since I needed to learn some basic html only for this project.

Thank you in advance.




lundi 11 septembre 2023

How to disable the check box in listview c#

In windows forms I have a listview with checkbox(listview1.CheckBoxes = true). I want to disable it from the begin and once double click the selected row,then loading a button in a separate tab. once clicked that button need to automatically check the listview checkbox. How can I do it?

I used this for disable the check box.

  private void listview1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
            e.NewValue = e.CurrentValue;
    }



Word 2016 VBA: UserForm Checkbox Feeds 2nd MSDOC Checkbox

Title: Word 2016: VAB Checkbox: Display a variable of a UserForm CheckBox to another variable CheckBox inside the overlying Word Doc.

I have a Word Document that has 6 Checkboxes as 2 sets of 3 each to choose between. (i,e. yes/no and does/does not) Each set of the Checkboxes are verified to only have one box checked with the below code, as well as other fill in the form - text variables.

To simplify filling the document, I chose to "Create" a UserForm with 6 Checkboxes and other text data fields. Each 6 variables from the UserForm checkbox are assigned variable named Checkbox1 thru Checkbox 6.

Private Sub Checkbox1_Click() 
       If Checkbox1.Value = True Then
   Checkbox2.Value = False
End If 
End Sub

Private Sub Checkbox2_Click() 
       If Checkbox2.Value = True Then
   Checkbox1.Value = False
End If 
End Sub

Once all data is entered and boxes checked in the UserForm, the OK Button is pressed, which runs the VAB code to fill in the overlaying Word Document with all the variables including the selected Checkboxes1-6.

PROBLEM: When the OK Button is clicked, All the text (which is assigned to various variables) BUT: None of the Checkbox are filled on the overlying Word Document.

Current Sample of many tries what I have tried, but the .Text can’t be changes to the correct VBA object type .Checkbox

Private Sub ToggleButtonOK_Click()

Dim COTTPower1 As Range
If Checkbox1 = True Then
    Set COTTPower1 = ActiveDocument.Bookmarks(True).Range
Else
    Set COTTPower1 = ActiveDocument.Bookmarks(False).Range
End If

COTTPower1.Text = Me.CheckBox1.Value
 .
 .
 .        
      {Repeat of the checkbox VBA Coding with changing variables.}
 .
 .
 .

End Sub

Can anyone help with the appropriate code to accomplish this task?




The error message "Cannot read properties of undefined (reading 'length')" occurred in the Vue Element UI checkbox component

When using the el-checkbox component from Element UI, i encountered the error message "Cannot read properties of undefined (reading 'length')", and the checkbox is not being displayed. These are my codes:

... return{ ... ruleForm: { name: '', code: '', phone: '', sex: '', ethinc: '', date1: '', date2: '', desc: '', course: [], }, ... }

I tried to move the course array outside of ruleForm, but the validator don't work




Onclick for checkbox in typescript generates error

I am generating checkboxes in a table (typescript) as follows:

  generateTable(): void {
    var table = document.getElementById("table1") as HTMLTableElement;
    if (table.childElementCount == 2) {
      for (var x = 0; x < 2; x++) {
        var newRow = table.insertRow(x+1);
        var newCell = newRow.insertCell(0);
        newCell.innerHTML = "<input type='checkbox' onclick='toggleSelection()'>";
      }
    }
  }
toggleSelection() { 
    console.log("Test");
  }

Now, as soon as I click on either of the checkboxes, I receive the following console error:

Uncaught ReferenceError: toggleSelection is not defined at HTMLInputElement.onclick ((index):142:2)

I am not sure how to handle this error. It seems like the function "toggleSelection" is not properly defined. Help is very much appreciated!




dimanche 10 septembre 2023

Apply Intermediate check to parent if all child nodes are not checked in Tree view WPF C#

I have a 3 level node Tree View Model: --Parent --SubParent --Child and all the nodes have a check box so I want to achieve the functionality of intermidiate check, if one child is unchecked then subparent and parent would have a intermidiate check and same for all.

I want to achieve this using triggers.




My checkbox is not saving when closing and opening the application

I'm trying to get the box to be saved when I open the application again, but when I close and open it it always comes back empty. I've faced many pointer errors trying to resolve this, I've tried creating directly in the onCreate method, but nothing works.

MainActivity

package br.mateus.appTarefas;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

import br.mateus.appTarefas.model.ListaTarefaAdapter;
import br.mateus.appTarefas.model.Tarefa;
import br.mateus.appTarefas.persistance.TarefaBD;
import br.mateus.appTarefas.persistance.TarefaDAO;

public class MainActivity extends AppCompatActivity{
    private EditText titulo;
    private EditText descricao;
    private ImageButton botaoSalvar;
    private ListView listar;
    private List<Tarefa>item;
    private ListaTarefaAdapter arrayTarefa;
    private TarefaDAO dao;
    private Tarefa t;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Theme_App);
        setContentView(R.layout.activity_main);
        mapearXML();
        verificar();
        click();
        check();
        arrayTarefa = new ListaTarefaAdapter(getApplicationContext(),item);
        listar.setAdapter(arrayTarefa);
    }

    private void mapearXML(){
        titulo = findViewById(R.id.idTitulo);
        descricao = findViewById(R.id.idDescricao);
        botaoSalvar = findViewById(R.id.idSalvar);
        listar = findViewById(R.id.idLista);
    }

    private void verificar(){
        if(dao==null){
            dao = new TarefaBD(this);
        }
        item=dao.listar();
    }

    private void check(){
        View checkLayout = getLayoutInflater().inflate(R.layout.linha,null);
        CheckBox check = checkLayout.findViewById(R.id.idCheckBox);

        SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
        boolean isChecked = sharedPreferences.getBoolean("checkBoxState", false);
        check.setChecked(isChecked);
        check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
                editor.putBoolean("checkBoxState", isChecked);
                editor.apply();
            }
        });
    }

    private void click(){
        botaoSalvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("MainActivitya","Item clicado");

                String tituloTarefa = titulo.getText().toString().trim();
                String descricaoTarefa = descricao.getText().toString().trim();
                if (tituloTarefa.isEmpty() ) {
                    titulo.setError("Este campo não pode estar vazio.");
                }else if(descricaoTarefa.isEmpty()){
                    descricao.setError("Este campo não pode estar vazio.");
                }else{
                    if (t == null) {
                        t = new Tarefa();
                    }
                    t.setTitulo(tituloTarefa);
                    t.setDescricao(descricaoTarefa);
                    if (t.getId() == null) {
                        dao.salvar(t);
                    } else {
                        dao.editar(t);
                    }
                    limparCampos();
                    atualizarItens();
                }
            }
            });

        listar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                final Tarefa tarefaSelecionada = item.get(position);

                LinearLayout itemLayout = view.findViewById(R.id.idItem); // Substitua "R.id.itemLayout" pelo ID correto do seu LinearLayout no arquivo linha.xml

                itemLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mostrarDialogoEditarExcluir(tarefaSelecionada);
                    }
                });
            }
        });



    };

    private void mostrarDialogoEditarExcluir(final Tarefa tarefa) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
        dialogBuilder.setTitle("Opções");
        dialogBuilder.setMessage("Escolha uma opção para a tarefa:");

        dialogBuilder.setPositiveButton("Editar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                abrirDialogoEditar(tarefa);
            }
        });

        dialogBuilder.setNegativeButton("Excluir", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mostrarDialogoConfirmacaoExcluir(tarefa);
            }
        });

        dialogBuilder.setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Ação a ser realizada quando o botão "Cancelar" for clicado
            }
        });

        dialogBuilder.create().show();
    }
    private void abrirDialogoEditar(final Tarefa tarefa) {
        AlertDialog.Builder editarDialogBuilder = new AlertDialog.Builder(MainActivity.this);
        editarDialogBuilder.setTitle("Editar Tarefa");

        // Inflar o layout do diálogo de edição
        View editarView = getLayoutInflater().inflate(R.layout.dialog_editar, null);
        editarDialogBuilder.setView(editarView);

        final EditText editarTitulo = editarView.findViewById(R.id.idTitulo);
        final EditText editarDescricao = editarView.findViewById(R.id.idDescricao);

        editarTitulo.setText(tarefa.getTitulo());
        editarDescricao.setText(tarefa.getDescricao());

        editarDialogBuilder.setPositiveButton("Salvar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String novoTitulo = editarTitulo.getText().toString();
                String novaDescricao = editarDescricao.getText().toString();

                // Atualize a tarefa com os novos valores aqui
                tarefa.setTitulo(novoTitulo);
                tarefa.setDescricao(novaDescricao);

                // Atualize a tarefa no banco de dados
                dao.editar(tarefa);

                // Atualize a lista de tarefas na interface do usuário
                atualizarItens();
            }
        });

        editarDialogBuilder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Ação a ser realizada quando o botão "Cancelar" for clicado
            }
        });

        editarDialogBuilder.create().show();
    }
    private void mostrarDialogoConfirmacaoExcluir(final Tarefa tarefa) {
        AlertDialog.Builder confirmarExclusaoDialogBuilder = new AlertDialog.Builder(MainActivity.this);
        confirmarExclusaoDialogBuilder.setTitle("Confirmar Exclusão");
        confirmarExclusaoDialogBuilder.setMessage("Tem certeza de que deseja excluir esta tarefa?");

        confirmarExclusaoDialogBuilder.setPositiveButton("Excluir", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Execute a exclusão da tarefa aqui
                dao.remove(tarefa);

                // Atualize a lista de tarefas na interface do usuário
                atualizarItens();
            }
        });

        confirmarExclusaoDialogBuilder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Ação a ser realizada quando o botão "Cancelar" for clicado
            }
        });

        confirmarExclusaoDialogBuilder.create().show();
    }

    private void atualizarItens(){
        item.clear();
        item.addAll(dao.listar());
        arrayTarefa.notifyDataSetChanged();
    }

    private void limparCampos(){
        titulo.setText(" ");
        descricao.setText(" ");
        t=null;
    }

    public void cancelar(View view){
        AlertDialog.Builder cancela = new AlertDialog.Builder(this);
        cancela.setTitle("Deseja mesmo sair?");
        cancela.setPositiveButton("Sair", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        cancela.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        cancela.create().show();
    }
}

activity_main xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/idPrincipal"
    android:layout_height="match_parent"
    android:background="@color/azulescuro"
    >

    <ListView

        android:id="@+id/idLista"
        android:layout_width="401dp"
        android:layout_height="331dp"
        android:layout_marginTop="392dp"
        android:textFilterEnabled="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />


    <ImageButton
        android:id="@+id/idCancelar"

        android:layout_width="77dp"
        android:layout_height="120dp"
        android:layout_marginStart="4dp"
        android:layout_marginBottom="8dp"
        android:backgroundTint="#00FFFFFF"
        android:contentDescription="Sair"
        android:onClick="cancelar"
        android:src="@drawable/sair"
        app:layout_constraintBottom_toTopOf="@+id/idTitulo"
        app:layout_constraintStart_toEndOf="@+id/idSalvar" />

    <ImageButton
        android:id="@+id/idSalvar"
        android:layout_width="67dp"
        android:layout_height="86dp"
        android:layout_gravity="center"
        android:layout_marginStart="272dp"
        android:layout_marginBottom="24dp"
        android:backgroundTint="#00FFFFFF"
        android:contentDescription="Adicionar"
        android:scaleType="fitCenter"
        android:src="@drawable/adicionar"
        app:layout_constraintBottom_toTopOf="@+id/idTitulo"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/idTitulo"
        android:layout_width="396dp"
        android:layout_height="73dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="116dp"
        android:ems="10"
        android:hint="Título"
        android:inputType="text"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/idDescricao"
        android:layout_width="394dp"
        android:layout_height="142dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="36dp"
        android:ems="10"
        android:hint="Descrição"
        android:inputType="text"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/idTitulo" />
</androidx.constraintlayout.widget.ConstraintLayout>

linha.xml (where is the checkbox)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/idItem"
    android:layout_width="400dp"
    android:layout_height="50dp"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/idCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/textTitulo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Texto da Linha 1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textDescricao"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="30dp"
            android:text="Texto da Linha 2" />
    </LinearLayout>

</LinearLayout>



vendredi 8 septembre 2023

asp.net check/uncheck all checkboxes inside gridview

I have this gridview:

<asp:GridView DataKeyNames="IdUtente" runat="server" ID="grdUtenti" AllowPaging="True" CssClass="tablestyle" AutoGenerateColumns="false" OnPageIndexChanging="grdUtenti_PageIndexChanging" EnableViewState="false" ViewStateMode="Enabled">

and the last column contains one checkbox in the header and for each row:

<asp:TemplateField>
 <HeaderTemplate>
  <asp:CheckBox runat="server" ID="checkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" />
 </HeaderTemplate>
 <ItemTemplate>
  <asp:CheckBox ID="chkSelect" runat="server" onclick="Check_Click(this)" />
 </ItemTemplate>
 <ItemStyle Width="3%" />
 <EditItemTemplate>
 </EditItemTemplate>
</asp:TemplateField>

I finally have this javascript functions:

<script type="text/javascript">
    function Check_Click(objRef) {
        //Get the Row based on checkbox

        var row = objRef.parentNode.parentNode;
        var x = document.getElementById("divEliminaTutto")
        if (objRef.checked) {
            //If checked change color to Aqua
            row.style.backgroundColor = "#f3ef98";
        }
        else {
            //If not checked change back to original color
            if (row.rowIndex % 2 == 0) {
                //Alternating Row Color
                row.style.backgroundColor = "WhiteSmoke";
            }
            else {
                row.style.backgroundColor = "white";
            }
        }

        //Get the reference of GridView
        var GridView = row.parentNode;

        //Get all input elements in Gridview
        var inputList = GridView.getElementsByTagName("input"); //checkAll

        for (var i = 0; i < inputList.length; i++) {
            //The First element is the Header Checkbox
            var headerCheckBox = document.getElementById("grdUtenti_checkAll"); //inputList[0];

            //Based on all or none checkboxes
            //are checked check/uncheck Header Checkbox
            var checked = true;
            if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
                if (!inputList[i].checked) {
                    checked = false;
                    break;
                }
            }
        }
        headerCheckBox.checked = checked;

        //INIZIO CONTEGGIO CHECKBOX SELEZIONATI PER MOSTRARE\NASCONDERE IL PULSANTE ELIMINA
        var numChecked = 0;
        for (var i = 0; i < inputList.length; i++) {
            if (inputList[i].type == "checkbox" && inputList[i].checked) {
                numChecked = numChecked + 1;
            }
        }
        if (numChecked > 0) {
            x.style.display = "block";
        }
        else {
            x.style.display = "none";
        }
        //FINE
    }

    function GridSelectAllColumn(spanChk) {
        var x = document.getElementById("divEliminaTutto")
        var oItem = spanChk.children;
        var theBox = (spanChk.type == "checkbox") ? spanChk : spanChk.children.item[0]; xState = theBox.checked;
        elm = theBox.form.elements;



        for (i = 0; i < elm.length; i++) {
            if (elm[i].type === 'checkbox' && elm[i].checked != xState)
                elm[i].click();
        }

    }
</script>

It does what it should and beyond, meaning when I click the CheckAll checkbox it selects all checkboxes in the page even if they are outside the gridview. How can I just select the checkbox inside the gridview (and better, only those with "chkSelect" ID?) Thanks

EDIT: I included all the javascript functions to give a complete view of the code, but the focus for my need is on GridSelectAllColumn function.




How do I change the styles of checkboxes within a listview in winforms to be flatstyle = flat

My new winforms application is taking windows 11 styling. I want to set checkboxes back to how they looked on windows 10. But currently all i am able to do is add new checkboxes to the listview which sit ontop of the old ones. How do i update the existing checkbox style?

`

 foreach (ListViewItem item in listView.Items)
 {

     CheckBox checkBox = new CheckBox { };
     if (item.Checked)
     {
         // Create and add a new checkbox if it doesn't exist
         checkBox = new CheckBox
         {
             Name = item.Name,
             FlatStyle = FlatStyle.Flat,
             Checked = item.Checked,
             Bounds = new Rectangle(
                     listView.Items[item.Index].SubItems[0].Bounds.Left + 4,
                     item.Bounds.Top + 2, 18, 18)
         };


     }
     else
     {

         checkBox = new CheckBox
         {
             Name = item.Name,
             FlatStyle = FlatStyle.Flat,
             Checked = false,
             Bounds = new Rectangle(
                 listView.Items[item.Index].SubItems[0].Bounds.Left + 4,
                 item.Bounds.Top + 2, 18, 18)
         };


     }

     listView.Controls.Add(checkBox);

 }

`

I have tried creating new checkboxes and adding those controls to the listview.




jeudi 7 septembre 2023

VBA and Graphic - Serie visible or not

in my Chart 1, I'd like - through a CheckBox - to show/hide a series in a graph. However, the below code gives an error application-defined or method-defined. Could somebody help me on fixing it? THanks

If CheckBox1.Value = True Then
Worksheets("Graph").ChartObjects("Chart 1").Chart.FullSeriesCollection.Item(1).IsFiltered = False 



mercredi 6 septembre 2023

How to get Checked Values from Facets-CheckBox Group?

I'm using ORACLE APEX "Sample Maps" example on the "120 - Airports Faceted Search" page. I need to get the checked options from Facet "P120_STATE" (it's a checkbox group) and put this checked values in a Text Item called "CHECKED_STATES". I don't know how to get the checked values in this facet checkbox group. I need to get these checked values to use in another SQL command, for example:

select CITIES.ID as ID, CITIES.NAME as NAME, CITIES.STATE_CODE as STATE_CODE from CITIES CITIES where STATE_CODE IN ( :CHECKED_STATES )




mardi 5 septembre 2023

Excel VBA to auto-fill website checkboxes

My coding knowledge is quite limited, but I need some help from you guys.

The data in an excel table with 3 columns and 3 rows should be automatically marked into the 3x3 checkboxes on a web page. Chrome will be used.

I try to explain in the attached picture.Example Image

Can you help me with the vba code? Just filling in the boxes will suffice. There will be no click to save.

Thank you very much, best regards.

I tried to do it with Selenium but failed, I need working codes.




dimanche 3 septembre 2023

VBA Code to ensure that at least one checkbox is checked

I have a form (titled ReplacedParts) that is opened from original form (frmForm) and it uses checkboxes to track what parts were replaced on a rebuild. A total of 26 checkboxes. After you select the parts replaced, you press "Accept Changes" button. If no boxes are checked then i want there to be a msgbox pop up and i don't want the user to be able to continue until at least one box is checked. If at least one is checked, then i want ReplacedParts to hide (thus revealing the original form) and yes, i did include a last box for no parts replaced. Just need a little bit of code that would accomplish this.

I tried a few different ideas i found online but nothing has worked so far.




samedi 2 septembre 2023

Disable "Ship to a different address?" enabled by default in WooCommerce checkout

I'm using a template for my website, and the default value of "shipping to another address" is set to one. It causes opening a long form.

I have read there's no way to change it by CSS codes, but the information may not be up-to-date. So please check the picture and code, and if there's any way to address the issue, please let me know.

Content Management System: WordPress

screenshot of error

<input id="ship-to-different-address-checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" checked="checked" type="checkbox" name="ship_to_different_address" value="1">

I read online there's no way to change it by CSS codes, but the information may not be up-to-date. So please check the picture and code, and if there's any way to address the issue, please let me know.




vendredi 1 septembre 2023

jQuery Checkbox checked Limitation

I have 6 checkboxes in a group of food sides. Any or all of the six can be checked.

I have another group of 6 checkboxes of sauces that only one can be checked. On a specific condition, the Egg Rolls checkbox is checked, I would like to permit 2 of the checkboxes to be checked.

I have a JSFiddle HERE that shows my current code, although it does not permit 2 checkboxes to be selected if the Egg Roll checkbox is checked. I have alerts that clearly show the value of the declared variable "num" to be 2 when the Egg Roll checkbox is checked, but the function to limit the number of allowed checkboxes does not change from 1 to 2.

The HTML:

<!-- // **** Sides Table **** -->
<div>
  <table>
    <caption>Choose Your Sides</caption>
    <tr>
      <td><input type="checkbox" value="Mac \'n Cheese" name="side1" id="side1" data-price="2.50" class="item"><label for="side1">Mac 'n Cheese</label></td>
      <td><input type="checkbox" value="Egg Roll" name="side2" id="side2" data-price="3.00" class="item"><label for="side2">Egg Roll</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Green Beans" name="side3" id="side3" data-price="2.50" class="item"><label for="side3">Green Beans</label></td>
      <td><input type="checkbox" value="Potato Salad" name="side4" id="side4" data-price="2.50" class="item"><label for="side4">Potato Salad</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Seven Bean Chili" name="side5" id="side5" data-price="2.50" class="item"><label for="side5">Seven Bean Chili</label></td>
      <td><input type="checkbox" value="Cole Slaw" name="side6" id="side6" data-price="1.50" class="item"><label for="side6">Cole Slaw</label></td>
    </tr>
  </table>
</div>
<!-- // **** Sauce Table **** -->
<div>
  <table>
    <caption>Choose Your Sauce</caption>
    <tr>
      <td><input type="checkbox" value="Cheerwine" name="sauce" id="checkbox1" class="sauce"><label for="checkbox1">Cheerwine</label></td>
      <td><input type="checkbox" value="Hummer" name="sauce" id="checkbox2" class="sauce"><label for="checkbox2">Hummer</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Moovelous" name="sauce" id="checkbox3" class="sauce"><label for="checkbox3">Moovelous</label></td>
      <td><input type="checkbox" value="Mercy Me" name="sauce" id="checkbox4" class="sauce"><label for="checkbox4">Mercy Me</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Pepper Jacked" name="sauce" id="checkbox5" class="sauce"><label for="checkbox5">Pepper Jacked</label></td>
      <td><input type="checkbox" value="9mm" name="sauce" id="checkbox6" class="sauce"><label for="checkbox6">9mm</label></td>
    </tr>
  </table>
</div>

And the javascript code:

var last;
var num="";
num=1;
$('input:checkbox[id="side2"]').change(function () {
if($('#side2').prop('checked')) {
      num=2;
      alert (num);
} else {
      num=1;
      alert (num);
}
})

$('input:checkbox[class="sauce"]').change(function () {
if (this.checked) {
        if ($('input[type="checkbox"]:checked').length > num) {
            $(last).prop('checked', false);
        }
        last = this;
    }
});



Checkbox / Submit Logic issues

I have created a GUI using tkinter for an application deployer for my job. Im having an issue with 2 of my check boxes. I believe for some reason the Logic for my "Submit" button is getting confused

Ill elaborate...

When only selecting "Kaseya(AzureAD)" check box, then my submit button, In my logs I get

2023-09-01 12:51:09,465 - INFO - Currently selected options: []
INFO:main:Currently selected options: []
2023-09-01 12:51:09,466 - INFO - No options were selected.
INFO:main:No options were selected.

When only selecting "Trend(AzureAD)" check box, then my submit button, In my logs I get

2023-09-01 12:53:04,686 - INFO - Currently selected options: ['AzureAD']
INFO:main:Currently selected options: ['AzureAD']
2023-09-01 12:53:04,687 - INFO - Kaseya checkbox value for AzureAD: 0
INFO:main:Kaseya checkbox value for AzureAD: 0
2023-09-01 12:53:04,687 - INFO - Trend checkbox value for AzureAD: 1
INFO:main:Trend checkbox value for AzureAD: 1
2023-09-01 12:53:04,687 - INFO - Attempting to install TrendMicro
INFO:main:Attempting to install TrendMicro
ERROR:trend:Not connected to a domain. Current domain AzureAD FROM INSTALL_TREND()

The "Trend(AzureAD)" checkbox is working as expected, I have code to log the value of both active checkboxes when "Submit" button is pressed. Sense "Kaseya(AzureAD)" check box is not pressed it = 0.

When selecting both check boxes, then my submit button, In my logs I get

2023-09-01 12:54:32,387 - INFO - Currently selected options: ['AzureAD']
INFO:main:Currently selected options: ['AzureAD']
2023-09-01 12:54:32,388 - INFO - Kaseya checkbox value for AzureAD: 1
INFO:main:Kaseya checkbox value for AzureAD: 1
2023-09-01 12:54:32,389 - INFO - Trend checkbox value for AzureAD: 1
INFO:main:Trend checkbox value for AzureAD: 1
2023-09-01 12:54:32,389 - INFO - Attempting to install TrendMicro
INFO:main:Attempting to install TrendMicro
ERROR:trend:Not connected to a domain. Current domain AzureAD FROM INSTALL_TREND()
2023-09-01 12:54:32,390 - INFO - Attempting to install Kaseya
INFO:main:Attempting to install Kaseya
ERROR:kaseya:Not connected to a domain. Current domain AzureAD FROM INSTALL_KASEYA()

This is functioning as expected as well,

What doesn't make sense is why when I only select "Kaseya(AzureAD)" it comes back with no value in the check box and doesn't work but if "trend(AzureAD)" check box is selected as well, it works as expected.

Also don't be concerned with the ERROR, (AzureAD) is not a compatible domain for my install function. Its for Testing purposes and is working properly.

Below is my "Submit" button logic

def submit():
    global browser_checkboxes, kaseya_checkboxes, trend_checkboxes
    all_checkboxes = {**browser_checkboxes, **kaseya_checkboxes, **trend_checkboxes}
    selected_options = [option for option, var in all_checkboxes.items() if var.get() == 1]  

      # This line will log or print the selected options for debugging.
    logger.info(f"Currently selected options: {selected_options}")

    # checks if any Browser or Program has been selected to intall  
    if not selected_options:
        logger.info("No options were selected.")
        label.config(text="You have not selected any browsers or programs to install. Please select at least 1.")
        return
        
    # Check which Browsers to install and invoke the respective functions
    if "Chrome" in selected_options:
        logger.info("Attempting to install Chrome")
        install_chrome()
    if "Firefox" in selected_options:
        logger.info("Attempting to install Firefox")
        install_firefox()
        
    # Debugging logs to understand the values
    kaseya_selected = kaseya_checkboxes.get(domain_name).get()
    trend_selected = trend_checkboxes.get(domain_name).get()

    logger.info(f"Kaseya checkbox value for {domain_name}: {kaseya_selected}")
    logger.info(f"Trend checkbox value for {domain_name}: {trend_selected}")
    
    # Checks if Trend has been selected then calls the install_trend() from trend.py
    if trend_selected == 1:
        logger.info("Attempting to install TrendMicro")
        install_trend()

    # Checks if Kaseya has been selected then calls the install_kaseya from kaseya.py 
    if kaseya_selected == 1:
        logger.info("Attempting to install Kaseya")
        install_kaseya()



jQuery checkbox function not working with show/hide

I have 2 divs with group of checkboxes that conditionally permit 1 or 2 boxes to be selected. The functions work well when both div groups are not hidden by default. I created a Jsfiddle HERE to demonstrate the issue.

If a client chooses an Egg Roll, they are permitted an additional sauce. My intent is to allow 2 selections only if an eggroll is selected. Currently, if I show or hide a div before selecting a sauce, the function that permits 2 selections breaks.

Any help to make the code work on one div only, or on both divs when they are shown or hidden, would be appreciated.

var last1;
var last2;

$('input:checkbox[id="side2"]').change(function() {
  if ($('#side2').prop('checked')) {
    $("#sauce1Container").hide();
    $("#sauce2Container").show();
    //      $('.sauce1').prop("checked", false);
  } // else {
  //    $("#sauce1Container").show();
  //    $("#sauce2Container").hide();
  //  $('.sauce2').prop("checked", false);
  //}
})


$('input:checkbox[class="sauce1"]').change(function() {
  if (this.checked) {
    $('.sauce2').prop("checked", false);
    if ($('input[type="checkbox"]:checked').length > 1) {
      $(last1).prop('checked', false);
    }
    last1 = this;
  }
});

$('input:checkbox[class="sauce2"]').change(function() {
  if (this.checked) {
    $('.sauce1').prop("checked", false);
    if ($('input:checkbox[type="checkbox"]:checked').length > 2) {
      $(last2).prop('checked', false);
    }
    last2 = this;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidesContainer form-group mb-4 w-100" id="sidesContainer">
  <table class="sides">
    <caption>Add Your Sides</caption>
    <tr>
      <td><input type="checkbox" value="Mac \'n Cheese" name="side1" id="side1" data-price="2.50" class="item"><label for="side1">Mac \'n Cheese</label></td>
      <td><input type="checkbox" value="Egg Roll" name="side2" id="side2" data-price="3.00" class="item"><label for="side2">Egg Roll</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Green Beans" name="side3" id="side3" data-price="2.50" class="item"><label for="side3">Green Beans</label></td>
      <td><input type="checkbox" value="Potato Salad" name="side4" id="side4" data-price="2.50" class="item"><label for="side4">Potato Salad</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Seven Bean Chili" name="side5" id="side5" data-price="2.50" class="item"><label for="side5">Seven Bean Chili</label></td>
      <td><input type="checkbox" value="Cole Slaw" name="side6" id="side6" data-price="1.50" class="item"><label for="side6">Cole Slaw</label></td>
    </tr>
  </table>
</div>
// **** Sauce 1 Table ****
<div class="sauce1Container form-group mb-4 w-100" id="sauce1Container">
  <table class="sauces">
    <caption>Choose 1 Sauce</caption>
    <tr>
      <td><input type="checkbox" value="Cheerwine" name="sauce" id="checkbox1" class="sauce1"><label for="checkbox1">Cheerwine</label></td>
      <td><input type="checkbox" value="Hummer" name="sauce" id="checkbox2" class="sauce1"><label for="checkbox2">Hummer</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Moovelous" name="sauce" id="checkbox3" class="sauce1"><label for="checkbox3">Moovelous</label></td>
      <td><input type="checkbox" value="Mercy Me" name="sauce" id="checkbox4" class="sauce1"><label for="checkbox4">Mercy Me</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Pepper Jacked" name="sauce" id="checkbox5" class="sauce1"><label for="checkbox5">Pepper Jacked</label></td>
      <td><input type="checkbox" value="9mm" name="sauce" id="checkbox6" class="sauce1"><label for="checkbox6">9mm</label></td>
    </tr>
  </table>
</div>
// **** Sauce 2 Table ****
<div class="sauce2Container form-group mb-4 w-100" id="sauce2Container">
  <table class="sauces">
    <caption>Choose 2 Sauces</caption>
    <tr>
      <td><input type="checkbox" value="Cheerwine" name="sauce" id="checkbox7" class="sauce2"><label for="checkbox1">Cheerwine</label></td>
      <td><input type="checkbox" value="Hummer" name="sauce" id="checkbox8" class="sauce2"><label for="checkbox2">Hummer</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Moovelous" name="sauce" id="checkbox9" class="sauce2"><label for="checkbox3">Moovelous</label></td>
      <td><input type="checkbox" value="Mercy Me" name="sauce" id="checkbox10" class="sauce2"><label for="checkbox4">Mercy Me</label></td>
    </tr>
    <tr>
      <td><input type="checkbox" value="Pepper Jacked" name="sauce" id="checkbox11" class="sauce2"><label for="checkbox5">Pepper Jacked</label></td>
      <td><input type="checkbox" value="9mm" name="sauce" id="checkbox12" class="sauce2"><label for="checkbox6">9mm</label></td>
    </tr>
  </table>
</div>