mardi 19 décembre 2023

Oracle Apex checkbox on the interactive report

i am trying to add checkbox column on a interactive report. https://hardlikesoftware.com/weblog/2015/07/24/apex-interactive-report-checkbox-row-selection/ this is the reference that i used. it works when i click the header and choose all the rows but when i click on a row spesifically it throws an error says : "Cannot read properties of undefined (reading 'checked')"

here is my dynamic actions:

var cb$, checked, allRows$,
    sel$ = $("#P1_SELECTED"),
    event = this.browserEvent,
    target$ = $(event.target),
    th$ = target$.closest("th"),
    tr$ = target$.closest("tr");

if (th$.length) {
    // the click was on the "select all"
    // checkbox or checkbox cell
    cb$ = th$.find("input");
    if (cb$.length && cb$.val() === "all") {
        checked = cb$[0].checked;
        if (target$[0].nodeName !== 'INPUT') {
            // only do this if the click was not on the checkbox
            // because the checkbox will check itself
            checked = cb$[0].checked = !checked;
        }
        if (sel$.val() === "") {
            sel$.val("|");
        }
        $("#seq_id").find("td input").each(function() {
            this.checked = checked;
            // give a visual style to the [un]selected row
            $(this).closest("tr").toggleClass("selected", checked);
            // update the hidden selected item
            sel$.val(sel$.val().replace("|" + this.value + "|", "|"));
            if (checked) {
                sel$.val(sel$.val() + this.value + "|");
            }
        });
    }
} else if (tr$.length) {
    // the click was on some other data row
    cb$ = tr$.find("td").first().find("input");
    checked = cb$[0].checked;
    if (target$[0].nodeName !== 'INPUT') {
        // only do this if the click was not on the checkbox
        // because the checkbox will check itself
        checked = cb$[0].checked = !checked;
    }
    // give a visual style to the [un]selected row
    tr$.toggleClass("selected", checked);
    // update the hidden selected item
    if (checked) {
        if (sel$.val() === "") {
            sel$.val("|");
        }
        sel$.val(sel$.val() + cb$.val() + "|");
    } else {
        sel$.val(sel$.val().replace("|" + cb$.val() + "|", "|"));        
    }
    // update the select all checkbox state
    allRows$ = $("#seq_id").find("td input");
    checked = (allRows$.length === allRows$.filter(":checked").length);
    $("#seq_id").find("th input")[0].checked = checked;
}

this is the after refresh script

var checked,
    allRows$ = $("#seq_id").find("td input");
allRows$.filter(":checked").closest("tr").addClass("selected");
checked = (allRows$.length === allRows$.filter(":checked").length);
$("#seq_id").find("th input")[0].checked = checked;

here is the error ss error




vendredi 8 décembre 2023

Formik library's checkbox is not working in Microsoft Edge but working in Chrome

I am using one checkbox using the formik library's Field component this check box is working fine in chrome but not in microsoft edge,

I have cleared the cache along with browser history and also the Microsoft edge is up to date. what do I do?

const useStyles = makeStyles(theme => ({
  checkBoxSize: {
    transform: 'scale(1.4)',
  },
  checkBoxDiv: {
    display: 'flex',
    alignItems: 'flex-end',
    marginBottom: theme.spacing(0.85),
  }
}))
const classes = useStyles()
   <Grid xs={1} className={classes.checkBoxDiv}>
                <Field
                  title="Update in Development Timeline"
                  type="checkbox"
                  name={`trainingGroups[${groupIndex}].trainings[${trainingIndex}].Is_centralize_duration`}
                  className={classes.checkBoxSize}
                />
              </Grid>



mercredi 6 décembre 2023

How to change the white tick color when using Material UI Checkbox (React, JS)

I'm trying to change the default white tick (not the checkbox background!) to some other color of my choice. I've found some solutions for when using an older version of MUI and React. I'm looking for a solution for MUI v5.14 and React v18

MUI checkbox for reference: https://mui.com/material-ui/react-checkbox/

Found this post, but it seems not relevant for the current versions: Change the tick color in MuiCheckbox material UI




dynamic checkbox is not showing selected value in ASP.Net core Razor Pages

I have a checkbox list where the values are loaded from a database table. When the user selects particular customer, it is updating the database value to '1', but in the razor pages view the values are showing unchecked. I am not sure where i am going wrong.

Please find my code below,

AccessRights.Cs(Model Class)

public class AccessRights
{
    [Key]
    public int Id { get; set; }
    public int EmployeeId { get; set; }

    [Display(Name = "Users")]
    public string Username { get; set; }
    public string ADUsername { get; set; }        
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public bool isSelected { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? CreatedTimeStamp { get; set; }
    public string LastModifiedBy { get; set; }
    public DateTime? LastModifiedTimeStamp { get; set; }
}

Edit.Cshtml

<div class="form-group">
                <label  class="control-label"> Access To Customers</label>
                <div class="checkbox checkboxlist">
                @{
                    foreach (var customers in Model.CustomersChecked)
                    {
                    
                        <input type="checkbox" id="@customers.Value" value="@customers.Value" name="CustomersChecked" checked="@customers.Selected" />
                        <label class="text-black">@customers.Text</label><br/>
                    //<input type="hidden" asp-for="@Model.CustomersChecked" value="@customers.Id">
                    }
                }
                </div>
                <span  class="text-danger"></span>
            </div>

Edit.Cshtml.Cs

[BindProperty]
        public List<SelectListItem> CustomersChecked { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null || _context.AccessRights == null)
            {
                return NotFound();
            }

            var accessrights = await _context.AccessRights.FirstOrDefaultAsync(m => m.EmployeeId == id);
            AccessRights = accessrights;
            CustomersChecked = (from p in _context.AccessRights.Where(m => m.EmployeeId == id)
                                                select new SelectListItem
                                                {
                                                    Text = p.CustomerName,
                                                    Value = p.CustomerId.ToString()
                                                }).ToList();
            //CustomersChecked = CustomersChecked.Where()
            return Page();
        }

        
     
        public async Task<IActionResult> OnPostAsync(string[] CustomersChecked)
        {
            List<SelectListItem> items = (from p in _context.AccessRights.Where(m => m.EmployeeId == AccessRights.EmployeeId)
                                          select new SelectListItem
                                          {
                                              Text = p.CustomerName,
                                              Value = p.CustomerId.ToString()
                                          }).ToList();
            foreach (SelectListItem item in items)
            {
                if (CustomersChecked.Contains(item.Value))
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }
                AccessRights.LastModifiedBy = HttpContext.Session.GetString("DisplayName").Trim();
                AccessRights.LastModifiedTimeStamp = DateTime.Now;
                await _context.Database.ExecuteSqlInterpolatedAsync($"UPDATE [AccessRights] SET [isSelected] = {item.Selected}, [LastModifiedBy] = {AccessRights.LastModifiedBy}, [LastModifiedTimeStamp] = {AccessRights.LastModifiedTimeStamp} WHERE [EmployeeId] = {AccessRights.EmployeeId} AND [CustomerName] = {item.Text}");

            }
            return RedirectToPage("./Index");
        }

Appreciate your help! Thanks!




get value with if condition in codeigniter form checkbox [closed]

i want to get the checkbox that value 1 if checked and 0 if unchecked

heres my form.php code

<?= form_open('What/yougot') ?>
<table>
<tr><td>
<input name="id" type="text">
</td></tr>
<tr><td>
<input name="method1" type="checkbox" value="valuee">
<input name="method2" type="checkbox" value="valuee">
<input name="method3" type="checkbox" value="valuee">
</td></tr>
<tr><td>
<input name="show" type="submit">
</td></tr>
</table>
<?= form_close() ?>

i DO NOT know how to put it in controller but i want something like this

public function yougot (){

if (isset($_POST['show'])) {
$data = [
'id'=>$this->model_yougot->showYougot(id)->result_array(), //to select name and id based on id

if ('method1' = 'valuee'){
'metode1' => 1 } else {
'metode1' => 0 },
if ('method2' = 'valuee'){
'metode2' => 1 } else {
'metode2' => 0 },
if ('method3' = 'valuee'){
'metode3' => 1 } else {
'metode3' => 0 },
];

}

$this->load->view('view_yougot',$data);

}

this is the model

public function showYougot($id){
return $this->db->get_where('data',['id'=>$id]);
}

and then in the view_yougot.php i want these variables

$id = $data['id'];
$name = $data['name'];
$metod1 = $data['metode1'];
$metod2 = $data['metode2'];
$metod3 = $data['metode3'];

and use them to show the value somewhere like

name = <?= $name; ?><br>
id =  <?= $id; ?><br>
mehhod 1 = <?= $metod1; ?><br>
mehhod 2 = <?= $metod2; ?><br>
mehhod 3 = <?= $metod3; ?>

each $metod1 $metod2 $metod3 is showing 1 if checked or 0 if unchecked

i know im doing the select name and id wrong please help me correct it too. i have looked on google and can't find tutorials. alternatives way is okay. this is my first time please kindly teach me thank you




mardi 5 décembre 2023

Blazor FluentValidation and invalid class on checkboxes

I am working with Blazor WASM and FluentValidation project. The validation works, but for checkboxes, the invalid class is not added to invalid checkboxes, when that object isnt valid.

For my radio button groups, the validation invalid class works fine, and the validation updates when you select a radio button making it valid. This is because I am binding to SelectedValues in the InputRadioGroup.

My validator has the following rule.

 RuleFor(r => r.SelectedValues).NotEmpty().NotNull().When(r => r.IsRequired).WithMessage(r => $" XXX is required.");

Then on my razor page, I have this..

<InputCheckbox class="form-check-input" @bind-Value="@x.Selected" CurrentValue="@x.Value" />

When viewing the page, the InputCheckbox has "form-check-input valid" which may not be correct. Again if I dont select anything, and click the submit button, the validation message appears, but it doesnt disappear when I check/select a checkbox making it valid, as well as the invalid css class isn't applied to the checkboxes.

Is it because I am validating SelectedValues, which in this case is a comma separated list, but the checkboxes aren't bound at all to that property? There isnt a grouping component like there is InputRadioGroup.

There may be a simple solution for this, but I havent figured it out yet.




Save multiple checkbox value to database in ASP.NET Core MVC

I am using checkboxes to save data in database. It can save only one value at a time. When multiple values are selected, it only stores the first selected value.

I have Googled my problem. Multiple solutions suggested the use of List<string> Name in Model. I tried to do so but my controller gave me error CS0029.


  • Database Table (CollectionCategories):
Id CategoryName
1 First Category
2 Second Category
... ...

Code-

  • Model:
public class PostModel
{
    // Code before

    public string? CollectionCategory { get; set; }
}
public class CollectionCategoryModel
{
    [Key]
    public int Id { get; set; }
    public string CategoryName { get; set; }
}
  • ViewModel:
public class CreatePostViewModel
{
    // Code before
    
    // Category
    public string? CollectionCategory { get; set; }

    // Category List
    public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}
  • Controller:
public async Task<IActionResult> CreateAsync()
{
    // Category List
    var CreatePostCategoryVM = new CreatePostViewModel
    {
        CollectionCategoryList = await _context.CollectionCategories.ToListAsync()
    };

    return View(CreatePostCategoryVM);
}

[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
    if (ModelState.IsValid)
    {
        var post = new PostModel
        {
            // Code before             

            // Category
            CollectionCategory = postVM.CollectionCategory,
        };

         return RedirectToAction("Index");
    }
    else
    {
        // Error
    }
    return View(postVM);
}

  • View:
<div class="form-check">
    @foreach (var list in Model.CollectionCategoryList)
    {
        <input type="checkbox" asp-for="CollectionCategory" id="@list.CategoryName" value="@list.CategoryName">
        <label asp-for="CollectionCategory" for="@list.CategoryName"> @list.CategoryName </label>
    }
</div>

Edited

Error:

(JsonReaderException: 'S' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 1.)

  • Controller
[HttpGet]
public async Task<IActionResult> Index()
{
    var CardPostVM = new CardsViewModel
    {
        PostCard = await _context.Posts.ToListAsync()
    };

    var cached = _cache.TryGetValue("post", out var post);
    if (cached)
    {
        return View(post);
    }

    return View(CardPostVM);
}
  • ViewModel
public class CardsViewModel
{
    public List<PostModel>? PostCard { get; set; }
    public List<CollectionModel>? CollectionCard { get; set; }
}

Error Image


Thank you




lundi 4 décembre 2023

how to ask multiple selected question radio button/checkbox

There should be three checkboxes/radiobuttons. When I click on one, the others should be grayed out. For example, when I click on someone, I have to make different selections. When I click on the other, different selections. How can I do that. For example, when I click on the first radio button. There should be a file upload button at the bottom. When you click on the second radio button, there should be text for writing. How can I do this with html css?

There should be a file upload button at the bottom. When you click on the second radio button, there should be text for writing. How can I do this with html css?




How do I Write a Google Sheets Custom Conditional Format that Applies to Multiple Two-Column Sets in a Single Formula?

I want to make many columns of checklists that can be moved around without messing up the conditional formatting ranges. I know this can be done with multiple rules but if i want to move things around, I dont want the ranges to start acting up so a single rule would work best.

In Column A, there are checkboxes and the tasks in column B. There will be more checkboxes in column C and more tasks in column D and so on. If A2 is true, I only want to format cells A2 and B2. If C3 is true, I only want to format cells C3 and D3. Can this be done with a single formula? I'm trying to avoid app scripts, but maybe its the only way. I'm not sure. Thanks!

I've tried using separate rules for sets of two columns and that only works if you're not actively copying tasks back and forth which users will be doing a lot of.




dimanche 3 décembre 2023

updating a state inside a map, causes to push new elements to state that I don't want

here I have data state which I'm trying to loop over it with map function, and print out checklist which I called myChecklist.

import React, { useState } from 'react'

const App = () => {

  const [data, setData] = useState([
    {
      id:0,
      isChecked: true
    },
    {
      id:1,
      isChecked: false
    },
    {
      id:2,
      isChecked: false
    },
  ])
  

  const myCheckList = data.map((checkbox, index) => {
    return (
      <div key={index}>
        <input type="checkbox" 
          checked={checkbox.isChecked} 
          onChange={e => {setData(prev => [...prev, prev[index].isChecked = e.target.checked])}} 
          id={index} />
        <label htmlFor={index}>{checkbox.id}</label>
      </div>
    )
  })

  console.log(data)

  return (
    <div>{myCheckList}</div>
  )
}

export default App

every time I click my any of the checkboxes, it updates to isChecked Boolean referring to that checkbox. the problem is pushes new elements to the data state which cause the to map function to create a new checkbox I don't want. when ever I click the my checkboxes the log of **data **state should look like this:

[
    {
        "id": 0,
        "isChecked": true
    },
    {
        "id": 1,
        "isChecked": false
    },
    {
        "id": 2,
        "isChecked": false
    }
]

but after changing the checkbox a couple of times it would look like this:

[
    {
        "id": 0,
        "isChecked": true
    },
    {
        "id": 1,
        "isChecked": false
    },
    {
        "id": 2,
        "isChecked": false
    },
    false,
    true
]

noticed some true false values pushed to the state. I am NOT pushing anyThing so why this happens ????

I'll appreciate your help. thanks

I tried to separate the state that I am mapping throw and the state I want to update like this

import React, { useState } from 'react'

const App = () => {

  const [isChecked, setIsChecked] = useState([
    {isChecked: false},
    {isChecked: false},
    {isChecked: false}
  ])

  const data = [
    {
      id:0,
    },
    {
      id:1,
    },
    {
      id:2,
    },
  ]


  const myCheckList = data.map((checkbox, index) => {
    return (
      <div key={index}>
        <input type="checkbox" 
          checked={isChecked[index].isChecked} 
          onChange={e => {setIsChecked(prev => [...prev, prev[index].isChecked = e.target.checked])}} 
          id={index} />
        <label htmlFor={index}>{checkbox.id}</label>
      </div>
    )
  })

  console.log(isChecked)

  return (
    <div id='my-id'>{myCheckList}</div>
  )
}

export default App```

no new checkboxes would be printed to DOM but the issue of pushing elements I don't to the state, still remains



samedi 2 décembre 2023

Save PDF FormFields using VBA Excel

I've been writing values in the form fields from cell values in excel using VBA The problem is when it comes to checkbox, I have two checkbox, say checkbox 1 and checkbox 2. In order fot the checkbox1 to be marked the values of them must be 1 and 1 respectively For Checkbox2 to be marked, the values of the two checkbox must be 0 and 2 respectively I also have checkbox that is either 0 and 1 for it to be marked or not.

Whenever the program is done, you can check from the preview of the generated PDF file that markings are done correctly, but when you try to open it, values are there for text fields but the checkmarks are back to its default markings.

Is there something wrong with the values i stored for the checkbox.? I check the identification of the form field their type and values to get the right I.D. for the checkbox.

I tried writing it to 0 and 1 for on and off. Didn't solve the problem.

I tried going to PDF's Edit>Preferences>Documents> Checked "Save As Optimizes for Fast Web View"

I tried bringing it to front, automate left click and ctrl S, but it didn't work out

I simulated click on the boxes, and it is working fine.

Is there a way to get it right without simulating click?, because users might be using different dimensions in the screen, so it would be different target point for the click.




vendredi 1 décembre 2023

Assign code to multiple commandbuttons via loop

I am currently working on a vocabulary programm. That includes choosing which chapters (1-35) should be checked. I have a userform with 35 checkboxes. I have assigned the properties for the checkboxes via loop. Now I have to give every checkbox a induvidial code, the code is:

Privat Sub Checkbox1()
Chapters_checked(Chapter_number)=true
End sub

Chapters_checked is an array which stores, wheather a chapter needs to be checked or not. As you can see the code can be written with a loop, but I do not know how to give every checkbox a code with a loop. Anyone has an idea? Conrad

I did not try anything, since I did not found the tag "code"




MudBlazor checkboxes in tables being independent from one another

I want the user to be able to check only one Element at a time. If they check another element then that becomes checked any the others are false. I'm using MudBlazor and I tried to control this via a method but I've failed horribly.

<MudTable T="Element" Items="@Elements" Hover="true">
    <HeaderContent>
        <MudTh>checkbox</MudTh>
        <MudTh>Nr</MudTh>
        <MudTh>Name</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="checkbox">
            <MudCheckBox Value="@context.Checked" T="bool" CheckedChanged="CheckedChanged" Color="Color.Warning" CheckedIcon="@Icons.Material.Filled.PersonPinCircle" UncheckedIcon="@Icons.Material.Outlined.PersonPinCircle"></MudCheckBox>
        </MudTd>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
    </RowTemplate>
    <PagerContent>
        <MudTablePager PageSizeOptions="new int[]{50, 100}" />
    </PagerContent>
</MudTable>



@code {
    private IEnumerable<Element> Elements = new List<Element>()
    {
        new Element("helium", 1),
        new Element("borium", 45),
        new Element("argon", 346),
        new Element("oxygen", 51),
        new Element("radium", 467),
    };

    protected void CheckedChanged(object sender, EventArgs e)
    {
        // Set every other elements checked to false
        foreach (var item in Elements)
        {
            item.Checked = false;
        }   

        // set this elements checked value to what is is not
        CheckBox3 = !CheckBox3;
    }

    public class Element
    {
        public string Name { get; set; }
        public int Number { get; set; }
        public bool Checked { get; set; }

        public Element(string name, int number)
        {
            Name = name;
            Number = number;
            Checked = false;
        }
    }
}



jeudi 30 novembre 2023

Wix website: How to have a section of a profile (user ID) page collapsed, until the user checks a checkbox on their "update profile" page?

When a user signs up, multiple pages are created (because of how I'm working with Wix Dynamic pages and their Content Management System). Among those pages are the public profile page and the private update profile info page.

How do I keep a section of the public profile page collapsed until the user decides to check a checkbox on the "update profile info" page?

I've already managed to set the default value of the section as collapsed. It was an option that didn't require code.

I'm new to coding, btw, but not a complete noob.

I don't know exactly how to get checking the checkbox to expand the collapsed section.

And in this case, section and checkbox are on two different pages, which complicates things even further.

I hope you guys have some ideas and I appreciate any time you take to look into this.




Powershell implementing checkboxes within a table of data

Currently writing a PowerShell script to query DB & convert that info to a DataTable. Then output all to HTML file. I want 3 columns of the table to be outputted as checked checkboxes instead of T/F. Meaning instead of a value in table being true, it will appear as a check box.

I have tried writing a While loop to loop through the elements.




I want to deselect the checkboxes on button click

i want to implement clear all filters feature, for that i need to deselect all the checkboxes on a button click.

I have used primeng checkbox. HTML:

<button (click)="clearAllFilters()">Clear All Filters</button>

<p-checkbox *ngFor="let cb of filterColorCheckboxes" value=""
    label="" (onChange)="checkBoxFilter(cb.category, cb.value, $event)">
</p-checkbox>

In event.checked, i am getting an array of length 1 containing the value of the checkbox (instead of any boolean value that is given in many other solutions). That's why am unable to deselect the checkbox.




mercredi 29 novembre 2023

Sum total and return it when checkboxes checked with laravel livewire

I want to sum data from database where I can get it when checkbox is checked.

this is my component livewire

class YpReconSpv extends Component
{
    public $checkboxes = [];
    public $selected = [];
    public $total = 0;

    public function updatedCheckboxes($value)
    {

        if ($value) {
            $sales = YamahaPointSale::find($value);
            if ($sales) {
                $this->selected[$value] = $sales->total_amount;
            }
            $this->selected[$value] = $sales->total_amount;
        } else {
            if (isset($this->selected[$value])) {
                unset($this->selected[$value]);
            }
        }

        $this->total = array_sum(array_values($this->selected));
    }

    public function render()
    {
        $sales = YamahaPointSale::get();

        return view('livewire.yamaha.yp-recon-spv', compact('sales'));
    }
}

what I try to reach is when I click the checkbox, I get data from database, then I populate it in an associative array then sum it.

and this is my view

<input type="checkbox" wire:model="checkboxes." name="id[]"
id="id" value="" wire:change="updatedCheckboxes()">

but when I try it, it return error




mardi 28 novembre 2023

Stuck at FreeCodeCamp Trest

First, I'd like to apologise in advance for the (probably) dumbest question ever asked here. I started the FreeCodeCamp Responsive Web Design course less than a month ag. When I finally got to the HTML test, I totally got stuck in the "All your checkboxes inside #survey-form should have a value attribute and value." I have a value attribute and a value, I tried fixing it in several different ways, asked ChatGPT, fixed all errors that showed up on validator.w3, but I still get the same error. In my desperate pursuit, I found this site.

Everything else in my code passes the test. I had a few other very silly issues, but I managed to fix, however, no matter how much I change this checkbox fieldset, I still get the same error.

Here's is my current code for checkboxes:

<fieldset>
  <legend>Choose the position you're applying for:</legend>

  <input type="checkbox" name="Freelance Translator" id="job1" value="Freelance Translator">
  <label for="job1">Freelance Translator</label>

  <input type="checkbox" name="Data Analyst" id="job2" value="Data Analyst">
  <label for="job2">Data Analyst</label>

  <input type="checkbox" name="Project Manager" id="job3" value="Project Manager">
  <label for="job3">Project Manager</label>

  <input type="checkbox" name="Project Engineer" id="job4" value="Project Engineer">
  <label for="job4">Project Engineer</label>
</fieldset>

I tried to change the value to a number and it didn't work. I changed the value to "option1, option2," etc, and it didn't work. I also tried changing the name attribute, but this also won't work.

Here's my entire code, in case anyone has time and patience to check it out. https://gist.github.com/403-Lux/775b97c0a531437f921e18ebdf772ce4

I super appreciate any help I can get. Thanks so much in advance.




lundi 27 novembre 2023

PHP/SQL/AJAX Submit checkbox values in form without submit button [duplicate]

I am trying to create a form where a client can check off their tasks that automatically saves (AJAX). When the client checks the form, the value of the task's ID is sent to the PHP page. However, if the client unchecks it, even with the exact same code, the value disappears and I don't understand why. Here is my code:

index.php

<form method="post" action="this.form.submit();" name="form1">
  <div class="client-list">
    <div class="checkbox-list">

       <?php if(empty($clientTask['status'])): ?>
          <input type="checkbox" id="task0" name="task0" onclick="function1();" value="1">
       <?php else: ?>
          <input type="checkbox" id="task0" name="task0" onclick="function1();" value="1" checked>
       <?php endif; ?>
       <label for="task0">Task 0 Name</label>

       <?php if(empty($clientTask['status'])): ?>
          <input type="checkbox" id="task1" name="task1" onclick="function1();" value="2">
       <?php else: ?>
          <input type="checkbox" id="task1" name="task1" onclick="function1();" value="2" checked>
       <?php endif; ?>
       <label for="task1">Task 1 Name</label>

       <?php if(empty($clientTask['status'])): ?>
          <input type="checkbox" id="task2" name="task2" onclick="function1();" value="3">
       <?php else: ?>
          <input type="checkbox" id="task2" name="task2" onclick="function1();" value="3" checked>
       <?php endif; ?>
       <label for="task2">Task 2 Name</label>
    </div>
  </div>
</form>

script.js

<script>
    function function1() {
    var data = $("[name='form1']").serialize()
    $.ajax({
        url: "client-tasks.php",
        type: "POST",
        async: true,
        cache: false,
        data: data, 
        success: function(data){ 
            alert(data) 
        }
    });
}
</script>

I tried 3 different ways to see what works and what doesn't in client-tasks.php:

  1. $_POST['task0'] works both ways when the id is hard-coded.
  2. $_POST['task1'] only works in the if statement, but the value disappears in the else statement. It doesn't matter if the status is set to 1 or 0.
  3. The whole code with $_POST['task2'] will work even though the $task2 is an empty string.

From what I found, the else statement never works unless it is hard-coded. So, I need to find a way to get it working.

<?php
   include("../../path.php");
   include(ROOT_PATH . "/app/database/config.php");
   

    if (isset($_POST['task0'])) {
        $sql1="UPDATE client_tasks SET status = 1 WHERE id = 1";        
    } else {
        $sql1="UPDATE client_tasks SET status = 0 WHERE id = 1";
    }
    $result=$conn->query($sql1);
  
    if (isset($_POST['task1'])) {
        $sql2="UPDATE client_tasks SET status = 1 WHERE id = " . $_POST['task1'] . "";
    } else {
        $sql2="UPDATE client_tasks SET status = 0 WHERE id = " . $_POST['task1'] . "";
    }
    $result=$conn->query($sql2);

    $task2 = $_POST['task2'];
    if (isset(task2)) {
        $sql3="UPDATE client_tasks SET status = 1 WHERE id = " . $task2 . "";
    } else {
        $sql3="UPDATE client_tasks SET status = 0 WHERE id = '$task2'";
    }
    $result=$conn->query($sql3);

When it works When it doesn't work (empty string helps execute code)

I would really appreciate any help or advice, thank you!




dimanche 26 novembre 2023

Toggle button how to return true if it is ON and false if is OFF

Newbie to front-end world i am trying to implement a logic when a toggle button is on i want to return True and when it is turned off i want to return False

Below is my HTML

 <div class="toggle-button">

    <body>
      <label class="showLabel" for="show">Toggle on or off :</label>
      <label class="toggle">
        <input class="toggle-input" type="checkbox" (click)="helper();" />
        <span class="toggle-label" data-off="OFF" data-on="ON"></span>
        <span class="toggle-handle"></span>
      </label>
    </body>
  </div>

</div>

in typescript i have global variable that i want to be filled with either true or false when toggle is turned on or off -

Typescript global variable -

isToggled=false (if toggle is off)

or

isToggled=true (if toggle is on)

I would appreciate any help




When checkbox is marked "TRUE" in the specific data row in sheet - all data of that specific row from A:AA are copied in "Data_base" sheet

The issue that specific row checkbox "TRUE" in different sheets (example "Data1", Data2", "Data3") could be in different row (example row 28, row 40, row 100, but all the time the checkbox will be in the same column E and just 1 in all the sheet in that E column. Its needed to copy data from the active sheet to last empty row of "Data base" sheet, when check box is selected "TRUE" in column E. The data A:AA all the time are in the same row where checkbox was selected.

function onEdit(e) {
  e.source.getActiveSheet().getName() == 'Data1' && e.range.getColumn() == 5 && e.value == "TRUE" ?
    (e.source.getSheetByName('Data_base').appendRow([e.source.getSheetByName('Data1').getRange('A' + e.range.getRow()).getValue()]) ?
    (e.source.getSheetByName('Data1').getRange('B' + e.range.getRow()).copyTo(e.source.getSheetByName('Data_base').getRange('B' + e.source.getSheetByName('Data_base').dest.getLastRow()+1;
}



samedi 25 novembre 2023

Is it possible to dynamically generate linws checkbox tree?

I have been playing around with my react project and I am trying to replicate my checkbox tree design. (I have linked the image).

I have a nice jsfiddle of a working solution, however, I am really struggling to see how I can use this in my project. Because I will need to dynamically generate my tree.

Is it possible to use this code to dynamically generate a tree and replicate my design?

I feel like the Pseudo styling will be tough to deal with if I map my data.

My data will look like this:

[
  {
    value: 1,
    data: "data",
    children: [],
  },
  {
    value: 2,
    data: "data2",
    children: [],
  },
  {
    value: 3,
    data: "data3",
    children: [
      {
        value: 1,
        data: "data",
        children: [],
      },
    ],
  },
];

code:

.what {
  margin-right: 15px;
}
  
  ul.tree,
  ul.tree ul {
    padding-bottom: 5px;
    list-style: none;
    margin: 0;
    padding-left: 0;
  }

  ul.tree ul {
    margin-top: 5px;
    margin-left: 20px;
  }

  ul.tree li {
    padding-bottom: 5px;
    margin-left: 0.60em;
    border-left: thin solid #000;
  }

  ul.tree li:last-child {
    border-left: none;
  }

  ul.tree li:before {
    width: 0.9em;
    height: 0.6em;
    margin-right: 0.1em;
    vertical-align: top;
    border-bottom: thin solid #000;
    content: "";
    display: inline-block;
  }

  ul.tree li:last-child:before {
    border-left: thin solid #000;
  }
<ul class="tree"><input class="what" type="checkbox" />Root</ul>
<ul class="tree">
  <li><input class="what" type="checkbox" /> Animals </li>
  <li><input class="what" type="checkbox" /> Animals
    <ul class="tree">
      <li><input class="what" type="checkbox" /> Animals </li>
    </ul>
  </li>
</ul>
<ul class="tree"><input class="what" type="checkbox" /> Root</ul>
<ul class="tree"><input class="what" type="checkbox" /> Root</ul>

enter image description here




jeudi 23 novembre 2023

C# Allow user to use checkbox column to select one row in each DataGridView on a form

I am new to C# and Visual Studio and am building a application which interacts with data.

I am trying to get my head around the intricacies of DataGridView controls.

I'm basically trying to build a "mapping" interface whereby an user can map a column from one table to a column in another table (in a different database).

I have two DataGridView controls on a form, one for each of the 2 databases being interacted with. Each DataGridView is populated using a SqlDataAdapter and DataTable, which is triggered by selecting a table name from a corresponding combo box.

The corresponding grid displays the column name and datatype of each column in a data table.

So essentially the user will have 2 grids showing the columns of a table from each of the 2 databases.

I have added a checkbox column to each DataGridView, and so the user can only select one row from each data grid I have set the VirtualMode property of each grid to "True".

However, at runtime, the checkbox column in both grids is behaving like a set of Radio buttons, thus only allowing the user to select ONE checkbox across both grids.

Is there any way I can remove this limitation?

The mapping aspect of the work I'm trying to do is going to be difficult, but if I can't get around this, I'm going to have to re-think my approach. I was basically going to try, one at a time, to build a SQL INSERT INTO statement through code so I'd end up with something like

INSERT INTO TargetDB.dbo.TargetTable (TargetFieldA, TargetFieldB, TargetFieldC) 
SELECT SrcFieldA AS TargetFieldA, SrcFieldB AS TargetFieldB, SrcFieldC AS TargetFieldC FROM SourceDB.dbo.SourceTable 
EXCEPT 
SELECT TargetFieldA, TargetFieldB, TargetFieldC FROM TargetDB.dbo.TargetTable;

But that's probably for another question. As I said, I'm very new to C# so am probably approaching this all wrong anyway.

I haven't written any code yet to get around this as I was hoping I was just overlooking a setting or something. The only thing I have tried is placing each DataGridView control inside its own Panel, as I do with Radio buttons to ensure they "group" together and are not affected by the checked property of a radio button outside the panel. But that didn't work.

Many thanks in advance.

Regards

Steve




mercredi 22 novembre 2023

Removing thick border when activex checkbox is not checked

I can not figure out how to remove the border when the activex check box is not checked. I have been messing with the code but either get errors or unwanted results.

Screenshot of checked with code #1

Screenshot of unchecked with code #1

This is for work so I can not upload the sheet but I can answer more questions and upload more screenshots if needed. I am still very new to using VBA and ActiveX controls and trying to learn more; so I would appreciate the help!

This is where i am at on the code right now;

Code#1

Private Sub CheckBox3_Click()
    If CheckBox3.Value = True Then
        Me.CommandButton3.Visible = True
        Me.CommandButton4.Visible = True
        Me.CommandButton5.Visible = True
        Me.CommandButton6.Visible = True
        Me.CommandButton7.Visible = True
        Me.CommandButton8.Visible = True
        Me.CommandButton9.Visible = True
        Range("B4:B14", "C4:C14").BorderAround _
          LineStyle:=xlContinuous, _
          Weight:=xlThick, _
          Color:=RGB(0, 0, 0)
  Else: CheckBox3.Value = False
        Me.CommandButton3.Visible = False
        Me.CommandButton4.Visible = False
        Me.CommandButton5.Visible = False
        Me.CommandButton6.Visible = False
        Me.CommandButton7.Visible = False
        Me.CommandButton8.Visible = False
        Me.CommandButton9.Visible = False
    End If
    Application.EnableEvents = True
End Sub

I have tried a few different codes but they have failed;

Code#2

Private Sub CheckBox3_Click()
    If CheckBox3.Value = True Then
        Me.CommandButton3.Visible = True
        Me.CommandButton4.Visible = True
        Me.CommandButton5.Visible = True
        Me.CommandButton6.Visible = True
        Me.CommandButton7.Visible = True
        Me.CommandButton8.Visible = True
        Me.CommandButton9.Visible = True
        Range("B4:B14", "C4:C14").BorderAround _
          LineStyle:=xlContinuous, _
          Weight:=xlThick, _
          Color:=RGB(0, 0, 0)
  Else: CheckBox3.Value = False
        Me.CommandButton3.Visible = False
        Me.CommandButton4.Visible = False
        Me.CommandButton5.Visible = False
        Me.CommandButton6.Visible = False
        Me.CommandButton7.Visible = False
        Me.CommandButton8.Visible = False
        Me.CommandButton9.Visible = False
        With .Range("H4:I7")
                .Interior.ColorIndex = xlNone
                .Font.Color = vbWhite
                .Borders.LineStyle = xlNone
                .EntireRow.Hidden = False ' ?
    End If
    Application.EnableEvents = True
End Sub

This one works, just changing the color of the border, but it screws up the border on the bottom of row 3.

Code#3

Private Sub CheckBox3_Click()
    If CheckBox3.Value = True Then
        Me.CommandButton3.Visible = True
        Me.CommandButton4.Visible = True
        Me.CommandButton5.Visible = True
        Me.CommandButton6.Visible = True
        Me.CommandButton7.Visible = True
        Me.CommandButton8.Visible = True
        Me.CommandButton9.Visible = True
        Range("B4:B14", "C4:C14").BorderAround _
          LineStyle:=xlContinuous, _
          Weight:=xlThick, _
          Color:=RGB(0, 0, 0)
  Else: CheckBox3.Value = False
        Me.CommandButton3.Visible = False
        Me.CommandButton4.Visible = False
        Me.CommandButton5.Visible = False
        Me.CommandButton6.Visible = False
        Me.CommandButton7.Visible = False
        Me.CommandButton8.Visible = False
        Me.CommandButton9.Visible = False
         Range("B4:B14", "C4:C14").BorderAround _
          LineStyle:=xlContinuous, _
          Weight:=xlThick, _
          Color:=RGB(250, 250, 250)
    End If
    Application.EnableEvents = True
End Sub



mardi 21 novembre 2023

Uncheck one of the checkboxes, and the data from report analysis also will hide one

Please see image, currently the checked checkbox from issue and report analysis data are from table or database.

My question is how if I unchecked one of the checkboxes, the data from report analysis will hide one. Then if I checked one more checkbox it will add one more details for report analysis to be keyed in. I try below code, but unsuccessfully.

enter image description here

document.addEventListener('DOMContentLoaded', function() {
  // Add an event listener for each checkbox
  var issueCheckboxes = document.querySelectorAll('input[name="selectedIssues[]"]');
  issueCheckboxes.forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
      showAnalysisDropdowns();
    });
  });

  // Initialize the display on page load
  showAnalysisDropdowns();
});

function showAnalysisDropdowns() {
  var issueCheckboxes = document.querySelectorAll('input[name="selectedIssues[]"]');
  var analysisContainer = document.getElementById('analysisContainer');
  var doContainer = document.getElementById('doContainer');

  analysisContainer.innerHTML = ''; // Clear existing "Report Analysis" content
  doContainer.innerHTML = ''; // Clear existing "doNo" and "doQuantity" content

  var analysis_data = [
    <?php
                $analysis = mysqli_query($con, "SELECT analysis_desc, analysis_value FROM list_report_analysis where analysis_status='1'");
                $analysisOptions = array();
                while ($row = mysqli_fetch_array($analysis)) {
                    $analysisOptions[] = $row['analysis_desc'] . ',' . $row['analysis_value'];
                }
                echo '"' . implode('", "', $analysisOptions) . '"';
                ?>
  ];

  for (var i = 0; i < issueCheckboxes.length; i++) {
    if (issueCheckboxes[i].checked) {
      // Create "Report Analysis" dropdowns as before
      var select = document.createElement("select");
      select.name = "analysis_data[]";
      select.innerHTML = '<option value="">Select Report Analysis</option>';

      for (var j = 0; j < analysis_data.length; j++) {
        var parts = analysis_data[j].split(',');
        var desc = parts[0];
        var value = parts[1];
        var option = document.createElement("option");
        option.value = value;
        option.text = desc;
        option.setAttribute('data-analysis-desc', desc);
        select.add(option);
      }

      var sampleNoInput = document.createElement("input");
      sampleNoInput.type = "text";
      sampleNoInput.name = "analysis_sampleNo[]";
      sampleNoInput.placeholder = "Sample No";

      var resultInput = document.createElement("input");
      resultInput.type = "text";
      resultInput.name = "analysis_result[]";
      resultInput.placeholder = "Result";

      var analysisTotalInput = document.createElement("input");
      analysisTotalInput.type = "text";
      analysisTotalInput.name = "analysis_total[]";
      analysisTotalInput.placeholder = "Total Exceed";
      analysisTotalInput.readOnly = true;
      analysisTotalInput.value = '';

      analysisContainer.appendChild(select);
      analysisContainer.appendChild(sampleNoInput);
      analysisContainer.appendChild(resultInput);
      analysisContainer.appendChild(analysisTotalInput);
      analysisContainer.appendChild(document.createElement("br"));
    }
  }

  // Add the "Calculate" button
  var calculateButton = document.createElement("button");
  calculateButton.textContent = "Calculate";
  calculateButton.type = "button";
  calculateButton.onclick = calculateAnalysisTotal;
  analysisContainer.appendChild(calculateButton);
  analysisContainer.appendChild(document.createElement("br"));

  // Hide analysisContainer if no checkboxes are checked
  analysisContainer.style.display = (document.querySelector('input[name="selectedIssues[]"]:checked') ? 'block' : 'none');
}
<table>
  <tr>
    <td><b> Issue : </b></td>
    <td>
      <?php
        // Select issue_ids related to the specified complaintId
        $sql = "SELECT issue_id FROM tblccrs_details WHERE complaintId='" . $_GET['cid'] . "'";
        $result = mysqli_query($con, $sql);

        $issueIdsFromDatabase = array(); // Initialize an array to store issue_ids

        while ($row = mysqli_fetch_array($result)) {
            $explodedList = explode(',', $row['issue_id']);

            // Add the issue_ids to the array
            $issueIdsFromDatabase = array_merge($issueIdsFromDatabase, $explodedList);
        }

        // Remove duplicates from the array
        $issueIdsFromDatabase = array_unique($issueIdsFromDatabase);

        $issue = mysqli_query($con, "SELECT * FROM list_issue_ts where issue_ts_status='1'");

        while ($row = mysqli_fetch_array($issue)) {
            $issueId = $row['issue_id'];
            $issueDesc = $row['issue_ts_desc'];

            // Check if the issue_id is in the selected issues array
            $isChecked = in_array($issueId, $issueIdsFromDatabase);

            echo '<input type="checkbox" name="selectedIssues[]" value="' . $issueId . '" ' . ($isChecked ? 'checked' : '') . ' onchange="showAnalysisDropdowns()"> ' . $issueDesc . '<br>';
        }
        ?>
    </td>
  </tr>

  <tr height="50">
    <td colspan="2"> <b>Report Analysis : </b> </td>
  </tr>

  <tr>
    <td colspan="2">
      <?php
        $a = 1;
        $sql = "SELECT analysis_desc, analysis_sampleNo, analysis_result, analysis_total FROM tblccrs_report_analysis WHERE complaintId='" . $_GET['cid'] . "'";
        $result = mysqli_query($con, $sql);
        ?>

        <?php while ($row = mysqli_fetch_array($result)) { ?>
        <div class="analysis-container">
          <label for="analysisData<?php echo $a; ?>">
                    <?php echo $a ?>. <?php //echo $row['analysis_desc']; ?>
                </label>
          <select name="analysisData<?php echo $a; ?>" onchange="calculateAnalysisTotal(this)">
            <!-- Populate options dynamically as before -->
            <?php
                    $analysisDesc = $row['analysis_desc'];
                    $analysisValue = $row['analysis_value'];

                    $allAnalysisQuery = "SELECT DISTINCT analysis_desc, analysis_value FROM list_report_analysis WHERE analysis_status='1'";
                    $allAnalysisResult = mysqli_query($con, $allAnalysisQuery);

                    while ($descRow = mysqli_fetch_assoc($allAnalysisResult)) {
                        $selected = ($descRow['analysis_desc'] == $analysisDesc) ? "selected" : "";
                        echo '<option value="' . $descRow['analysis_desc'] . '" data-analysis-value="' . $descRow['analysis_value'] . '" ' . $selected . '>'
                            . $descRow['analysis_desc'] . '</option>';
                    }
                    ?>
          </select>

          <br> Sample No: <input type="text" name="analysis_sampleNo[]" value="<?php echo $row['analysis_sampleNo']; ?>">
          <br> Result: <input type="text" name="analysis_result[]" value="<?php echo htmlentities(number_format($row['analysis_result'], 2)); ?>">
          <br> Exceed: <input type="text" name="analysis_total[]" value="<?php echo htmlentities(number_format($row['analysis_total'], 2)); ?>" readonly>
          <br>

          <!-- Add the "Calculate" button -->
          <button type="button" onclick="calculateAnalysisTotal(this)">Calculate</button>
          <br />
          <hr />
        </div>
        <?php $a++;} ?>
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <div id="analysisContainer"></div>
    </td>
  </tr>
</table>



lundi 20 novembre 2023

Checkbox value not being returned on checkbox change [duplicate]

I am creating checkboxes from an array of objects. on change, I am not getting back anything.

My code:

let res = [
  { id: "123", fullName: "harry potter", username: "harrypotter" },
  { id: "345", fullName: "hermione granger", username: "hermionegranger" },
  { id: "678", fullName: "ron weasley", username: "ronweasley" },
  { id: "789", fullName: "ginny weasley", username: "ginnyweasley" },
  { id: "987", fullName: "luna lovegood", username: "lunalovegood" },
];

let cbs = document.getElementById("cboxes");
for (const cb of res) {
        cbs.innerHTML += `<div class="form-check form-check-inline">
        <input type="checkbox" class="form-check-input" id="${cb.username}" name="${cb.username}" value="${cb.id}">
        <label class="form-check-label" for="${cb.username}">${cb.username}</label>
        </div>`;
        
let chck = document.getElementById(cb.username);
chck.addEventListener("change", function(event) {
   if (event.currentTarget.checked) {
       alert(`checked ${this.value}`);
   } else {
       alert("not checked");
   }
 });
}
<div id="cboxes"></div>

On checkbox check I want the checkbox value returned. My code is returning nothing.




dimanche 19 novembre 2023

change boolean in ajax in asp.net mvc

I want to write a ajax for my view so that if I change the the check box, The RegisterSituation of rows that were chosen is changed in database. my Model is:

public class OstadCourse
    {
        [Key]
        
        public int OstadCourseId { get; set; }

       
        public int OstadId { get; set; }

        public bool RegisterSituation { get; set; }

        
        public string OstadName { get; set; }

        
        public string OstadFamily { get; set; }

        public string Title { get; set; }
        
        public int CourseId { get; set; }
        
    }

My View is:(I have tried to add ajax to end of following view, but when I change checked to unchecked, it is send null to controller) How can I write ajax so that change RegisterSituation of rows that change

@model IEnumerable<DataLayer.OstadCourse>

@{
   ...
    var courses = Model.Select(x => new { x.CourseId, x.Title }).Distinct();
    var selectedCourseId = Request["selectedCourseId"];
    var filteredCourses = String.IsNullOrEmpty(selectedCourseId) ? Model : Model.Where(x => x.CourseId == int.Parse(selectedCourseId));
    ...
}

<form>
    
    <div class="row">
        
        <div class="col-md-4 mb-3 mb-md-0">
            @Html.DropDownList("selectedCourseId", new SelectList(courses, "CourseId", "Title", selectedCourseId), "-- All --", new { @class = "form-control", style = "padding: 0.375rem .75rem;", onchange = "this.form.submit()" })
        </div>
    </div>

    <table class="gridtable">
        <thead>
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Family</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in filteredCourses)
            {
                <tr>
                    <td>
                        <input type="checkbox" class="rowCheckbox" name="selectedIDs" value="@item.OstadCourseId" @(item.RegisterSituation ? "checked" : "")  />
                    </td>
                    <td>@item.OstadName</td>
                    <td>@item.OstadFamily</td>
                </tr>
            }
        </tbody>
        
    </table>

</form>



vendredi 17 novembre 2023

Click the same cell a second time (toggle)

'EXCEL for Mac

Need 200 checkbox simulated but checkbox slows excel down.

Trying to toggle the same cell between two Custom values repeatedly. As in clicking the same cell as second Time while active.

Application.ontime function does not work for me in the following code: 'I have allowed all Macros to execute.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Address = "$A$1" Or Target.Address = "$A$2" Then
        Exit Sub
    End If
    
    ' Check if the value of the active cell matches cell A1
    If ActiveCell.Value <> Range("A1").Value Then
        ' Assign the active cell to cell A1
        ActiveCell.Value = Range("A1").Value
    Else
       ActiveCell.Value = Range("B1").Value
    End If

    ' Call the CheckActiveCellValue subroutine
    'CheckActiveCellValue
    
        ' To allow triggering the event even when clicking on the same cell,
    ' you can call the event manually using Application.OnTime
    
    
    
   ' WILL NOT WORK
    'Application.OnTime Now + TimeValue("00:00:01"), "TriggerSelectionChangeX"
    'Application.OnTime TimeValue(Now() + TimeSerial(0, 1, 0)), "TriggerSelectionChangeX"

    
End Sub

Sub TriggerSelectionChangex()
    Worksheet_SelectionChange Selection
End Sub

Sub HelloWorld()

MsgBox "Hello World"
Application.OnTime TimeValue(Now() + TimeSerial(0, 1, 0)), "HelloWorld"

End Sub

In the example above after the first execution at 17:00, will repeat after every 1 minute.

This code does work for ticking my custom on and off checkbox graphics. But I cant seem to click the same cell to toggle the value. I've ticked on the Allow all Macros to execute setting.




jeudi 16 novembre 2023

xpath works in browser devtools but selenium cannot find element

steps: after login to techfetch.com, and click select all checkbox and click Multiple Quick Apply button.

Then: trying to check the "Attach Covering Letter" checkbox. I could find element in browser using //*[@id="chkCL"] xpath. But javascript nodejs script is not able to find element.

// url https://www.techfetch.com/js/js_applyemail.aspx?quickapply=true

let attachCoverCheckBox = await driver.findElement(By.xpath('//*[@id="chkCL"]'))
Process exited with code 1
Uncaught NoSuchElementError NoSuchElementError: Unable to locate element: //*[@id="chkCL"]
    at throwDecodedError (file:///C:/work/selenium/apply-jobs/node_modules/selenium-webdriver/lib/error.js:524:15)
    at parseHttpResponse (file:///C:/work/selenium/apply-jobs/node_modules/selenium-webdriver/lib/http.js:601:13)
    at execute (file:///C:/work/selenium/apply-jobs/node_modules/selenium-webdriver/lib/http.js:529:28)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
No debugger available, can not send 'variables'

browser dev tools xpath and ::before pesudo tags

trying to click "Attach Covering letter" checkbox on the quick apply screen of techfetch.com website. I am new to Selenium and This is my second selenium script. So, Please provide as much information you can.




checkbox issue when removing items

Im having this issue when checkbox moves up a row when items are removed. How could I ensure checkbox is not moving up or duplicated? because now I have to check if checkbox is duplicated manually which is not an ideal solution.
Here's the code for removing items for reference.

Dim n, s   As Long
Dim bSelected As Boolean
Dim Cell, c As Range
Dim rng    As Range: Set rng = Range("A27:H42")
Dim ws     As Worksheet
Dim colItem As Long, sItem As String
Set ws = ThisWorkbook.Sheets("Data")
Dim selectedItems As New Collection
Set SelectedItem = New Collection

For n = 0 To Me.ListboxResult.ListCount - 1
    If Me.ListboxResult.Selected(n) Then
        bSelected = True
        Exit For
    End If
Next n

If Not bSelected Then
    MsgBox "Please select an item to remove.", vbOKOnly, "Selection Required"
    Exit Sub
End If

For s = s To Me.ListboxResult.ListCount - 1
    If Me.ListboxResult.Selected(s) Then
        selectedItems.Add s
    End If
Next s

colItem = 1                                   ' 2nd column in listbox
Set rng = ThisWorkbook.Sheets("Data").Range("E:E")
With ListboxResult
    For i = .ListCount To 1 Step -1
        If .Selected(i - 1) Then
            sItem = .List(i - 1, colItem)
            Set c = rng.Find(sItem, LookIn:=xlValues, lookat:=xlWhole)
            If Not c Is Nothing Then
                c.EntireRow.Delete
                Set c = Nothing
            Else
                'MsgBox sItem & " not found on sheet", vbExclamation
                Exit Sub
            End If
            .RemoveItem i - 1
        End If
    Next
End With



How to locate a Checkbox item in Datadog synthetic test with Terraform

I'm building a Datadog's Synthetic Browser test with Terraform, but I'm facing issues to address this HTML element: <input type="checkbox" name="payrollInstructionIds" value="957e1f96-377d-4cec-a815-e6ec0e52402d">

The step I'm trying to do is a click on that checkbox. But, should be considered that the page have 9 checkboxes, and all of them have the same 'type' and 'name' properties. Only 'value' changes.

I have tried with these options, but the test always fails at that step, saying that the element couldn't be located. Option 1:

  browser_step {
    name = "Click checkbox: Reg. Salary Pay"
    type = "click"
    params {
      element_user_locator {
        fail_test_on_cannot_locate = "true"
        value {
          type  = "css"
          value = "input[value='957e1f96-377d-4cec-a815-e6ec0e52402d']"
        }
      }
    }
  }

Option 2:

  browser_step {
    name = "Click checkbox: Reg. Salary Pay"
    type = "click"
    params {
      element_user_locator {
        fail_test_on_cannot_locate = "true"
        value {
          type  = "css"
          value = "input[name='payrollInstructionIds',value='957e1f96-377d-4cec-a815-e6ec0e52402d']"
        }
      }
    }
  }

Option 3:

  browser_step {
    name = "Click checkbox: Reg. Salary Pay"
    type = "click"
    params {
      element_user_locator {
        fail_test_on_cannot_locate = "true"
        value {
          type  = "css"
          value = "input[name='payrollInstructionIds']"
        }
      }
    }
  }

All the three options give me this result on the Datadog's GUI: Error Cannot locate element.

Anyone knows how to do it?

Expectation: The synthetic browser test is able to click the checkbox and continue with the next test's steps.




What is the type of e.values and e.oldValues, when reading boolean values?

Reading differents boolean types of e.values of checkboxes on a sheet, I resumed the (odd) e.values read on a table.)

Table of values & type of values I got this values by clicking on checkboxes and triggering onEdit function. the values read are not boolean. in the table, you can see that the values read are TRUE/FALSE and string type. Reading the cell by his coordinates , it return the correct values as you can see in this other table. Values of direct reading of cells

you can test with this code


    function onEdit(e) {
      var eA1 = e.range.getA1Notation();
      var ui = SpreadsheetApp.getUi();

      // e.value and his typeof
      ui.alert("(" + eA1 + ") e.value=" + e.value);
      ui.alert("(" + eA1 + ") typeof e.value=" + typeof e.value);

      // eValue and his typeof
      var eValue=e.value;
      ui.alert("reading of  eValue......");
      ui.alert("(" + eA1 + ") eValue=" + eValue);
      ui.alert("(" + eA1 + ") typeof eValue=" + typeof eValue);

      // getting de value of (e)cell
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var eTargetCell = sheet.getRange(eA1);
      var eCellValue = eTargetCell.getValue();

      // eCellValue and his typeof
      ui.alert("direct reading of cell.......");
      ui.alert("(" + eA1 + ") eValue=" + eCellValue);
      ui.alert("(" + eA1 + ") typeof eValue=" + typeof eCellValue);
    }

You can easily make a function to get the boolean value of 'e' cell. To get the correct value of e.oldValue... you can recover it in the original cell, if needed, easily by

    e.range.setValue(eOldValue);
...

or in another cell(not tested this point)


I have not found help of this issue on internet, and I expend many hours drilling, I hope this can save time to others, or maybe someone can modify this code to do a better version.



mercredi 15 novembre 2023

Selection of checkbox and send items to email

I have an issue with sending email using VBA. So I have checkboxes and items in the sheet and I want to send items to email when the checkboxes are selected. If not selected, then do nothing. I have this error that says 'Subscript out of range'. Im not sure how to fix. This is the image of the spreadsheet that Im testing on and here's my code:

Private Sub sendEmail(arrType, arrItem, arrQuantity, arrUnit)

    Dim i      As Integer
    Dim objOutlook As Object
    Set objOutlook = CreateObject("outlook.application"
    Dim ws     As Worksheet
    Dim strSubject As String
    Dim strBody As String
    Dim strType As String
    Dim strItem As String
    Dim strQuantity As String
    Dim strUnit As String
    Dim strTable As String
    Dim strHTML As String
    Set ws = ThisWorkbook.Worksheets("Data")
    
    strSubject = "Testing"
    strBody = "<html>"
    strBody = strBody & "Please see the order details below for your reference:<br><br>"
    strTable = "<br><table border = 2><tbody>"
    strTable = strTable & "<tr>"
    strTable = strTable & "<th align = center> Type</th>"
    strTable = strTable & "<th align = center> Item</th>"
    strTable = strTable & "<th align = center> Quantity</th>"
    strTable = strTable & "<th align = center> unit</th>"
    strTable = strTable & "<tr/>"
    
    For i = 4 To UBound(arrType)
        strType = arrType(i)
        strItem = arrItem(i)
        strQuantity = arrQuantity(i)
        strUnit = arrUnit(i)
        
        strTable = strTable & "<tr><td>" & strType & "</td>"
        strTable = strTable & "<td>" & strItem & "</td>"
        strTable = strTable & "<td>" & strQuantity & "</td>"
        strTable = strTable & "<td>" & strUnit & "</td></tr>"
    Next
    strTable = strTable & "</tbody></table><br>"
    strHTML = strBody & strTable & "</html>"
    
    
    
    If MsgBox("Are you sure you want to submit? ", vbYesNo, "Submit Confirmation") = vbYes Then
        Dim objEmail As Object
        Set objEmail = objOutlook.CreateItem(0)
        With objEmail
            .To = ""
            .Subject = "testing"
            .HTMLBody = strHTML
            .Display
            .Send
        End With
        MsgBox "Thanks for the order. Your order details are sent successfully.", vbxOKOnly, "Operation Successful"
    Else
        Exit Sub
    End If
End Sub
Private Sub itemStored(arrType, arrItem, arrQuantity, arrUnit)


    Set ws = ThisWorkbook.Worksheets("Data")
    
    Dim i      As Long
    
    Dim cb     As CheckBox
    
    
    For Each cb In CheckBoxes
        
        If cb.Value = 1 Then
            
            arrType(i) = ws.Cells(i + 4, "I").Value
            
            arrItem(i) = ws.Cells(i + 4, "I").Value
            
            arrQuantity(i) = ws.Cells(i + 4, "I").Value
            
            arrUnit(i) = ws.Cells(i + 4, "I").Value
            
            i = i + 1
            
        End If
        
    Next
    
End Sub
Private Sub cmdbtnShow_Click()
    OrderForm.Show
End Sub
Private Sub CommandButton2_Click()
    Dim arrType() As Variant
    Dim arrItem() As Variant
    Dim arrQuantity As Integer
    Dim arrUnit As String

    Call itemStored(arrType, arrItem, arrQuantity, arrUnit)
    Call sendEmail(arrType, arrItem, arrQuantity, arrUnit)
End Sub

When the checkboxes are selected, items on the left hand side will send to email. If not, noting will happen.I tried making arrType and arrItem correspond to sendEmail but still doesn't work.




Tablesorter Grouping not recognizing checked checkboxes

I have tablesorter runing properly on some table - it works fine. But first column contains checkboxes and I need to sort that column by checked ones. I have add grouping widget and it works fine on every single column except this first one - all rows are sorted under "unchecked" , just like widget does not recognize if it is checked or not. No error is thrown, nothing fancy in other scripts, just one checkbox in head column selecting them all (tried to remove it - no difference). Every script that I have reads checked/unchecked properly - just that widget is not.

Has anyone faced such issue? Can't google out similar situation.

Script is way to big to paste it here, so here is list what I use:

  • tablesorter newest version, jquery 3.6.0
  • widgets: group, zebra, filter, cssstickyheaders, dragtable

All config is cropped version of example in grouping widget page.(I don't have date /time columns)




lundi 13 novembre 2023

After i chose an option from a RadioListTile i want to keep just the text title

enter image description hereI want after i chose an item from a radio list, to keep just the title of radio list and make the ckeckbox, if i can name it like that, dissapear. Do you have any idea on how can i do that? Thanks a lot and have a nice day! This is a sample of my code so far:

  Column(
      children: [
        RadioListTile(
          fillColor: MaterialStateProperty.resolveWith<Color>(
              (Set<MaterialState> states) {
            return CustomColors.primary;
          }),
          title: Text(
            'Option 1',
            style: TextStyle(
                color:
                    selectedRadioGroup1 == 1 ? CustomColors.primary : null),
          ),
          value: 1,
          groupValue: selectedRadioGroup1,
          onChanged: (value) {
            setState(() {
              selectedRadioGroup1 = value;
              nestedSelectedRadioGroup1 = null; // Reset nested selection
            });
          },
        ),
        if (selectedRadioGroup1 == 1)
          Padding(
            padding: const EdgeInsets.only(left: 15.0),
            child: Column(
              children: [
                RadioListTile(
                  title: const Text('Nested Option A'),
                  value: 3,
                  groupValue: nestedSelectedRadioGroup1,
                  onChanged: (value) {
                    setState(() {
                      nestedSelectedRadioGroup1 = value;
                    });
                  },
                ),
                RadioListTile(
                  title: const Text('Nested Option B'),
                  value: 4,
                  groupValue: nestedSelectedRadioGroup1,
                  onChanged: (value) {
                    setState(() {
                      nestedSelectedRadioGroup1 = value;
                    });
                  },
                ),
              ],
            ),
          ),
      ],
    ),



vendredi 10 novembre 2023

why the UI doesn't change in checkbox in flutter?

i tried to make a checkbox for a week in flutter . and because of not writing extra code i made a widget "week" and when i run the code i can see the checkboxes but when i click on them the UI doesn't change ... i expect when i click on a ticked box => the box turns to unticked and vice versa. and this doesn't happen and i don't know what is the problem?? please help me ...please... thank you.

here is my whole code:and this is the UI image

import "package:flutter/services.dart";

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyPage(),
    );
  }
}

class MyPage extends StatefulWidget {
  MyPage({super.key});

  @override
  State<MyPage> createState() => _Example();
}

class _Example extends State<MyPage> {
  bool mon = true;
  bool tue = true;
  bool wed = true;
  bool thu = true;
  bool fri = true;
  bool sat = true;
  bool sun = true;

  Widget week(bool? value, String day) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(day),
            Checkbox(
                value: value,
                onChanged: (bool? new_Value) {
                  setState(() {
                    value = new_Value;
                  });
                }),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('HDBOOKS'),
        ),
        body: Center(
          child: Row(
            children: [
              week(mon, 'Mon'),
              week(tue, 'Tue'),
              week(wed, 'Wed'),
              week(thu, 'Thu'),
              week(fri, 'fri'),
              week(sat, 'sat'),
              week(sun, 'sun'),
            ],
          ),
        ));
  }
}

... i expect when i click on a ticked box => the box turns to unticked and vice versa. and this doesn't happen and i don't know what is the problem?? please help me ...please... thank you.




jeudi 9 novembre 2023

How to make checkboxes non interactive in email

I have an app that users fill forms that have checkboxes, then email those forms as html. The problem is users can interact with the checkboxes in the email. Is there any way to make users can't do that?

I already tried with disable and read-only, but it will make the checkboxes greyed. My client didn't want it like that. BTW my client is using Outlook Web.




Asp.Net Core , Checkbox is returning NULL value

I have a checkbox in my view to get the details about my 'Hall' entity class, and I have a view related to it, but my checkbox always return NULL value to entity class.

I tried others solutions but I can't solve and couldn't figure it out. Here's my codes

Hall.cs (entity class)

 public class Hall : BaseEntity, IAuditableEntity
 {
     [Key]
     public int Id { get; set; }
     public string Name { get; set; }
     public string? Description { get; set; }
     public string UpHall { get; set; }
     public bool IsUpHall { get; set; }
     public int Order { get; set; }
 }`
HallController.cs 

public class HallController : Controller
{
    private readonly IHallService _hallService;
    public HallController( IHallService hallService )
    {
        _hallService = hallService;
    }

    public IActionResult Index()
    {
        var values=_hallService.GetListAll();
        return View(values);
    }
    [HttpGet]
    public IActionResult AddHall()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> AddHall(Hall hall )
    {
        _hallService.Insert( hall );
        return RedirectToAction("Index");
    }
}
AddHall.cshtml (just checkbox part)

<div class="form-group d-flex flex-wrap justify-content-between align-items-center">
    <label class="checkbox m-0 text-muted">
        <input asp-for="IsUpHall" name="IsUpHall" id="IsUpHall" /> Üst Mekan
        <span></span>
    </label>
</div>



mardi 7 novembre 2023

Cannot add chexkboxes to my shiny datatable

I'm trying to add checboxes to my datatable in shiny and retrie later all the checked lines to other manipulation.

I have a function to add checkboxes to my data table (Select column). But when I try to build my datatable, there's text in the checkbox area.

Can anyone help me solve this problem? Thank you.

Result datatable

The function :

input_checkbox_ui_tiers_concours <- function(id, data, session, checked = FALSE) {
  ns <- NS(id)
  tag <- lapply(
    X = data,
    FUN = function(x) {
      # res <- checkboxInput(inputId = ns(paste0("check_", x)), label = NULL, value = FALSE)
      res <- tags$input(id = ns(paste0("check_", x)), type = "checkbox", style = "float: right;")
      if(checked) res$attribs$checked <- "checked"
      doRenderTags(res)
    }
  )
  unlist(tag, use.names = FALSE)
}

Datatable :



data_react_dt = reactive({
  data_p = copy(data_perim_rv$df_perim_filtre)
  test5 <<- data_perim_rv$df_perim_filtre
  col_factor =  data_p %>% lapply(is.factor) %>% .[. == TRUE] %>% names
  col_factor = data_p%>% names %>% str_subset( "^DAT", negate = TRUE)
  col_factor2 = data_p[, col_factor] %>% lapply( function(x){ !is.factor(x)} ) %>% .[. == TRUE] %>% names
  setDT(data_p)
  
  data_p[ , (col_factor2) := lapply(.SD, function(x) { as.factor(x) }), .SDcols = col_factor2]
  
  data_p[ , (col_factor) := lapply(.SD, function(x) { fct_explicit_na(x, "Non renseigné")  }), .SDcols = col_factor]
  
  
  data_p[ , ":=" ( Indic_Projet_Lab = Indic_Projet_Lab %>% fct_recode( "Non renseigné" = "")   ) ]
  
  col_date = data_p %>% names %>% str_subset( "^DAT")
  data_p[ , (col_date) := lapply(.SD, as.character ), .SDcols = col_date ]
  setDF(data_p)
  
  data_p
})


data_react_dt2 = reactive({
  # col_label_reactive()
  
  data = data_react_dt()
  if(length( col_label_reactive())>0)
    data=  data[, col_label_reactive()]
  # toto<<-data
  # print(names(data))
  data
  
})


output[['dt_suivi_dt']] <- DT::renderDataTable(server     = TRUE,
                                               {
                                                 data <- data_react_dt2()
                                                 
                                                 data$Select <- input_checkbox_ui_tiers_concours(ns("select_tiers_concours"),data$ID, session = session)
                                                 data <- data %>% dplyr::select(Select, everything())
                                                 
                                                 datatable(
                                                   data <- data
                                                   )
                                                 data
                                               }



lundi 6 novembre 2023

Vue checkbox binding not working when using a complex dynamic model

I'm working with a dynamic form that is generated from the database with a bunch of questions, basically in the form of an array of questions, all fields work as intended, but my checkbox behave wrong, just selecting an item makes it all selected, but when I just use a brand new object, it works as expected, this is the json that builds the failing question (this is part of an array):

{
            "id": 11,
            "question": "Check all coverages that apply:",
            "options": "{\"values\": [\"Group Medical\", \"Dental\", \"Vision\", \"Voluntary Supplemental Life\", \"Voluntary Supplemental Life for Spouse/Dependents\", \"Short-Term Disability\", \"Long-Term Disability\", \"Health FSA\", \"HRA\", \"Wellness Program\", \"AFLAC\", \"MEC (Minimum Essential Coverage) Plan\", \"Dependent Care FSA\", \"HSA\", \"Tobacco Surcharge\"]}",
            "section_id": 10,
            "form_position": 1,
            "type": 1,
            "liability": 0,
            "weight": 0,
            "title": "For a more accurate assessment, please complete this form:",
            "subtitle": "",
            "is_main": 1,
            "section_type": 0
        }

And this is the code that is failing:

<div class="ms-2 ps-5 mb-3" v-for="(question, questionIndex) in initialQuestions[mainKey]" :key="question.id">
          <h5 class="question-title"></h5>
          <h1></h1>
          <div class="row">
            <div class="col-12">
              <div>
                <p>Papa: </p>
                <div v-if="question.type === 0" v-for="(option, optionIndex) in question.options" class="form-check">
                  <!-- render input -->
                </div>
                <div v-else-if="question.type === 1" v-for="(option, optionIndex) in question.options"  :key="option" class="form-check">
                  <input 
                    class="form-check-input" 
                    type="checkbox" 
                    :id="option" 
                    v-model="initialAnswers[question.id]"
                    :value="option">
                  <label class="form-check-label"
                    :for="option">
                    
                  </label>
                </div>
                <div v-else-if="question.type === 2">
                  <!-- render select -->
                </div>
                
              </div>  
            </div>
          </div>
        </div>

If I inspect the composed object that I use of the checkbox I get this, as you can see, answer 11 is an array as it should, but on raw values, it just shows 'true':

Object debug

Finally, if instead of using the dynamically generated model, I just bind a const checkedNames = ref([]) to the input model it works perfectly, what I'm missing?

enter image description here

In case is any of use, this is how I initialize my model, case 1 is for checkboxes

const initialAnswers = ref([])

for (const [key, value] of Object.entries(initialQuestions.value)) {
      console.log(`${key}: ${value}`);
      value.forEach((obj) => {
        switch(obj.type){
          case 0:
            initialAnswers[obj.id] = ref('')
            break;
          case 1:
            initialAnswers[obj.id] = ref([])
            break;
          case 2:
          case 3:
            initialAnswers[obj.id] = ref()
            break;
        }
        //initialAnswers[obj.id] =  obj,type === 0 ref([]) 
      })
    }



How to set Checkboxes for other tables to enabled if one table is true?

I have a table that is going through a validation with ajax, and the result returned is true, I have also set up a global flag where if the validation of that table is true, then the checkboxes for all the other tables should be enabled as well but for some reason its not working, and I dont know why. The table going through the validation is working 'tabCSite1' and 'tabCEquip1', where the checkboxes for it are enabled but for the other typetables its not working. Here is the code:

    function getDetailsCheckJob(data, typetable, checkboxname,t) {
    
    var tblC = document.getElementById(typetable);
    for (var i = tblC.rows.length - 1; i > 0; i--) {
        tblC.deleteRow(i);
    }

    Row = data.split('[');

    var tab = document.getElementById(typetable);
    var valid_asb = false;
    var valid_FTTH = false;
    var tabCSite1Valid = false;

    for (var p = 0; p < Row.length - 1; p++) {
        var row = tab.insertRow(p + 1);

        row.style.background = "#e8eef4";
        row.style.whiteSpace = "nowrap";

        splitData = Row[p + 1].split('|');
        

        if (splitData[0] == "Y") {
            row.insertCell(0);
            tab.rows[p + 1].cells[0].innerHTML = "<input type=\"checkbox\" id=\"valueZ\" name=\"" + checkboxname + "\" value=\"" + splitData[1] + "\" checked/>"; //checked
        }
        else if (splitData[0] == "N") {
            row.insertCell(0);
            tab.rows[p + 1].cells[0].innerHTML = "<input type=\"checkbox\" id=\"valueZ\" name=\"" + checkboxname + "\" value=\"" + splitData[1] + "\"/>";
        }
      
       if (typetable == "tabCEquip1") {
           checkValidation(splitData[2], splitData[28], splitData[29], t, jobID, function (resp) {

               valid_asb = resp.isASBExist;
               valid_FTTH = resp.isFTTHExist;
           });
        }

        else if (typetable == "tabCSite1") {

        checkValidation(splitData[2], splitData[23], splitData[29], t, jobID,function (resp) {
            valid_asb = resp.isASBExist;
            valid_FTTH = resp.isFTTHExist;
            tabCSite1Valid = valid_FTTH; // Update the global flag here
            console.log('tabCSite1Valid inside: ', tabCSite1Valid);
        });
        }

        var splitDatalen = splitData.length;

        if (typetable == "tabCEquip1" || typetable == "tabCSite1") {
            splitDatalen = splitDatalen - 3;
        }
        else {
            splitDatalen = splitDatalen - 1;
        }

        for (var i = 1; i < splitDatalen; i++) {

            console.log('tabCSite1Valid inside other one: ', tabCSite1Valid);
            //alert(splitData.length);
            row.insertCell(i);
            styleData = splitData[i + 1];
                if (typetable == "tabCEquip1" || typetable == "tabCSite1" || typetable == "tabCSBoundary1" || typetable == "tabLPcomm1" || typetable == "tabAddCardSplit1" || typetable == "tabDelEquip1" || typetable == "tabDelPath1" || typetable == "tabDelSB1" || typetable == "tabCPathConsumer1" || typetable == "tabCreateServiceOLT1") {
                    if (tabCSite1Valid == false) {
                        tab.rows[p + 1].cells[0].innerHTML = "<input type=\"checkbox\" id=\"valueZ\" name=\"" + checkboxname + "\" value=\"" + splitData[1] + "\" disabled/>";
                        styleData = "<span style='color: red'>" + splitData[i + 1] + "</span>";
                        console.log('Activated at FTTH');
                    }
                if (splitData[3] != "ASB" && valid_asb == true) { //else && valid_FTTH == false
                    tab.rows[p + 1].cells[0].innerHTML = "<input type=\"checkbox\" id=\"valueZ\" name=\"" + checkboxname + "\" value=\"" + splitData[1] + "\" disabled/>";
                    styleData = "<span style='color: red'>" + splitData[i + 1] + "</span>";
                    console.log('Activated at ASB');
                }
            }
            tab.rows[p + 1].cells[i].innerHTML = styleData;
        }
    }
}

The issue is the for loop for the last one, the 'tabCSite1Valid' is true for the tables tabCEquip1 and tabCSite1. I even set it to global and yet its still not being true for all the other tables. Where am I going wrong and how to fix it?

As can be seen in the picture, the checkbox is supposed to be enabled because the 'tabCSite1Valid' is true but instead its false

enter image description here




dimanche 5 novembre 2023

How to check all checkboxes on one field? using JS

I have one field that has 5-6 checkboxes (and will increased more in the future), this field name email_notification, here's the code that i find on google to automatic check all the check boxes on event Form - On Load.

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function(checkbox) {
    checkbox.checked = true;
});

When I run the code, it will auto check all my checkboxes on field email_notification, it also check all checkboxes on other field. I just want only one field to automatically check all the checkboxes. Is there any clue to change the syntax? Thank you for helping.

I'm not familiar with Javascript, and I've been googling about this on one week but didn't find any clue.




Cannot uncheck QCheckBoxes in my C++ Qt application

I have tried setChecked and setCheckState but to no avail. I am able to check a QCheckBox but not uncheck. Everything else is working perfectly.

Debug mode was no help; installed a pushbutton to manually clear the checkboxes; tried making the boxes non-exclusive, then unchecked, then exclusive but no success. The only time I have all boxes unchecked is at the beginning when I first load the data. But then, as soon as a box is ticked that same box stays ticked unless I tick another box. But I need all boxes cleared with every fresh data insertion. My data consists of "pages" stored in a QList object. There is nothing in the pages that pretick the boxes.




vendredi 3 novembre 2023

Altering checkbox state in react js

This is my code for check box in react. Its from Material-UI

  const [checkmark, setCheckMark] = useState(false);

  const [selectedRows, setSelectedRows] = useState([]);

  const toggleAllCheck = (event) => {
    console.log("before", checkmark);
    setCheckMark(!checkmark);
    console.log("after", checkmark);
    let newSelectedRows;
    if (checkmark) {
      newSelectedRows = salesRows.map((row) => row.id);
      setSelectedRows(newSelectedRows);
      console.log("selected rows", newSelectedRows);
    }
  };

As checkmark state is initially set to false, there is no check-mark in the checkbox.

After I click the component, it shows a checkmark. The toggle is because of the toggleAllCheck function.

Inside the function, first it console logs the value of checkmark as false, which is understandable. On second line it alters the value to true. Which in turn gives a check-mark in my checkbox.

Then on third line, I again console log the value for checkmark. But it gives the false reading.

So, what I am confused about is why is it still false. I have the idea, that the state update happens in next render (been troubling me in other areas as well), but then how did I get the check on my check-box without any re-render.

Also, the same checkmark values is able to get me a check on the box, although its console log shows false, but is unable to execute the if statement.

I am trying to get a hold to selectedRows, when there is tick on checkbox, but I get that only in second click when the tick is removed.




I am not able to change the color of my checkbox's innerArea

My checkbox is

`import React from "react";

function Checkbox({ onClickProp, isCheckedProp, checkBoxDisableProp }) { return ( ); } export default Checkbox;`

and CSS is

bigger-checkbox
{
  cursor: pointer;
  transform: scale(1.25);
  background-color: #cea325 !important;
  color: #61dafb;
}

input[type="checkbox"]
{
  background-color: #cea325 !important;
}

bigger-checkbox:disabled
{
  cursor: not-allowed;
  transform: scale(1.25);
}
 

and my webpage is

enter image description here

I just want to change the color




When users want to 'check all', how can I implement this in React.js? Can anyone help me with this?

How can I achieve a 'check all' feature in this code? I've attempted several approaches, but I haven't been successful. Could someone please assist me?

This is where the checkbox

         <div style=>
            {Object.keys(permissionList).map((sectionKey, index) => (
              <Collapsible
                title={permissionList[sectionKey][0]?.section}
                isFirst={index === 0}
                key={sectionKey}
              >
                {permissionList[sectionKey]?.map((item, index) => (
                  <Checkbox.Group
                    options={[
                      {
                        label: item.name.toLowerCase(),
                        value: item.name.toLowerCase(),
                      },
                    ]}
                    disabled={isViewItem}
                    className="checkbox-style"
                    key={index}
                    value={formData?.permissions
                      .filter(
                        per =>
                          per.section.toLowerCase() ===
                          item.section.toLowerCase()
                      )
                      .flatMap(per => per.name.toLowerCase())}
                    onChange={checkedValues =>
                      handleCheckboxChange(
                        item.permissionId,
                        item.section.toLowerCase(),
                        checkedValues
                      )
                    }
                  />
                ))}
                <Checkbox.Group
                  options={[
                    {
                      label: "check all",
                      value: permissionList[sectionKey][0]?.section,
                    },
                  ]}
                  disabled={isViewItem}
                  className="checkbox-style"
                  key={index}
                  // value={formData?.permissions
                  //   .filter(
                  //     per =>
                  //       per.section.toLowerCase() === item.section.toLowerCase()
                  //   )
                  //   .flatMap(per => per.name.toLowerCase())}
                  onChange={checkedValues =>
                    handleCheckAll(permissionList[sectionKey], checkedValues)
                  }
                />
              </Collapsible>
            ))}
          </div>

This is checkbox functon

  const handleCheckboxChange = (
    permissionId: number,
    section: string,
    checkedValues: CheckboxValueType[]
  ) => {
    console.log(permissionId, section, checkedValues);
    setFormData(prevFormData => {
      const updatedFormData = { ...prevFormData };

      const permissionIndex = updatedFormData.permissions.findIndex(
        per =>
          per.permissionId === permissionId &&
          per.section.toLowerCase() === section.toLowerCase()
      );

      if (checkedValues.length > 0) {
        if (permissionIndex !== -1) {
          updatedFormData.permissions = updatedFormData.permissions.map(
            (permission, index) => {
              if (index === permissionIndex) {
                return {
                  ...permission,
                  name: String(checkedValues[0]),
                };
              }
              return permission;
            }
          );
        } else {
          updatedFormData.permissions = [
            ...updatedFormData.permissions,
            {
              permissionId,
              section,
              name: String(checkedValues[0]),
            },
          ];
        }
      } else {
        if (permissionIndex !== -1) {
          updatedFormData.permissions = updatedFormData.permissions.filter(
            (___, index) => index !== permissionIndex
          );
        }
      }
      return updatedFormData;
    });
  };

This is handleCheckAll function

  const handleCheckAll = (permissionsData, value) => {
    console.log(permissionsData, value);
  };

This is where I have store the items

  const [formData, setFormData] = useState<RoleFormData>({
    name: "",
    permissions: [],
  });

it's interface

interface Permission {
  name: string;
  section: string;
  permissionId: number;
}
interface RoleFormData {
  name: string;
  permissions: Permission[];
}

This is how I am getting the data from check all box

[{…}, {…}, {…}, {…}] 0: {permissionId: 1, name: 'Add', section: 'Role'}1: {permissionId: 2, name: 'View', section: 'Role'}2: {permissionId: 3, name: 'Edit', section: 'Role'}3: {permissionId: 4, name: 'Delete', section: 'Role'}

section--type ['Role']

permission list look like these enter image description here




jeudi 2 novembre 2023

How to click on Checkbox which is not intractable

I am trying to click on the Checkbox , but the element is not intractable through selenium(automation) as it is not visible in UI "as per SelectorsHub" . And there is no other option to click on Checkbox.

Below is the Code


<div class="expandingListItem" xpath="1"><div class="__react_component_tooltip t87682e2d-d3f9-492a-86e9-ff8647cfea93 place-bottom type-dark" id="21550Tooltip" data-id="tooltip">

   <a class="headerLabel"><div><input class="checkbox" type="checkbox" id="Main"><label for="Main"></label><span>Main </span></div><i class="material-icons"> expand_more</i></a><div class="contentWrapper "><div class="__react_component_tooltip t9d7a7973-4ccd-42c0-ad63-b3dfa99a9f29 place-bottom type-dark" id="nullTooltip" data-id="tooltip">

 </div><a class="contentChoice selected"><input class="checkbox" type="checkbox" id="3:21550:0" title=""><label for="3:21550:0"></label>Cint / Crowdology </a><div class="__react_component_tooltip tfbe137ad-b7b2-41a0-8c46-6fe81aba1c76 place-bottom type-dark" id="nullTooltip" data-id="tooltip">

</div><a class="contentChoice "><input class="checkbox" type="checkbox" id="50:21550:0" title=""><label for="50:21550:0"></label>Lucid </a><div class="__react_component_tooltip taab6a038-addb-4dc6-b569-10cd8bdba6c1 place-bottom type-dark" id="nullTooltip" data-id="tooltip">                                                                                                            

</div><a class="contentChoice "><input class="checkbox" type="checkbox" id="45:21550:0" title=""><label for="45:21550:0"></label>Pure Spectrum </a></div></div>

I am trying to Click in the checkbox




Unable and Disable CheckBox in Swift UI on Toggle

I want if user check the checkbox one then other one should be disable , currently user can select both.

I have seen some example but here I need to have bool values into modal struct but Please note that I do not have bool value into Model . Can I have do it with hardcoded values ?

Here is my CheckboxToggleStyle view code ..

import SwiftUI

struct CheckboxToggleStyle: ToggleStyle {
    @Environment(\.isEnabled) var isEnabled
    let style: Style // custom param

    func makeBody(configuration: Configuration) -> some View {
        Button(action: {
            configuration.isOn.toggle() // toggle the state binding
        }, label: {
            HStack {
                Image(systemName: configuration.isOn ? "checkmark.\(style.sfSymbolName).fill" : style.sfSymbolName)
                    .imageScale(.large)
                configuration.label
            }
        })
        .buttonStyle(PlainButtonStyle()) // remove any implicit styling from the button
        .disabled(!isEnabled)
    }

    enum Style {
        case square, circle

        var sfSymbolName: String {
            switch self {
            case .square:
                return "square"
            case .circle:
                return "circle"
            }
        }
    }
}

Here is the view code ...

struct OrderView: View {
    private var fee: Double = 5.00
    @State private var isOn1 = false
    @State private var isOn2 = false

    var body: some View {
                      VStack(alignment: .leading) {
                        Toggle("Standard : Free ", isOn: $isOn1)
                            .toggleStyle(CheckboxToggleStyle(style: .circle))
                            .foregroundColor(.blue)
                            .onTapGesture {
                                //
                            }

                        Toggle("Express : Charge \(fee.formatted(.currency(code: "GBP")))", isOn: $isOn2)
                            .toggleStyle(CheckboxToggleStyle(style: .circle))
                            .foregroundColor(.blue)
                            .onTapGesture {
                                //

                            }
                    }
                }



Here is the screenshot.. when I select on checkbox other one should be disable but is not..

enter image description here