dimanche 31 octobre 2021

check uncheck conditionally - React

I am a beginner to react. I am using the following code in jsplayground. I need to check "None" by default and uncheck it as soon as other items are clicked. Also, as soon as all other items are checked, it should be checked automatically.

function SystemChecklist({ categories }) {
const availableCategories = [
 "eBPT",
"ELVIS",
"LIMS1",
"OTRS",
"ComLIMS",
"Concur",
"Relationwise",
"Mitrefinch",
"concord",
"ADP",
"zoho",
"fastfinder",
"TCP",
"MYOB Advanced",
"Trello",
"Freshdesk",
"Time Clock Plus",
"OSO",
"Concurs",
"iLeader",
// "Other",
"None"
];

const handleChange = category => {
const isSelected = categories.includes(category);
let payload = categories;

if (isSelected) {
  payload = categories.filter(c => c !== category);
} else {
  payload = [...categories, category];
}
  console.log(payload);
/*
dispatch({
  type: "CATEGORIES_CHANGE",
  payload
 });*/
};


return (
 <form>
    {availableCategories.map(category => (
      <div key={category} style=>
         <div>
        <input
          type="checkbox"
          name={category}
          id={category}
          value={category}
          style=
          onChange={() => handleChange(category)}
          checked={category == "None" ? true : categories.includes(category)}
        />
        </div> 
          <div>
       <label variant="h6" htmlFor={category}>{category}</label>
       </div>
      </div>
    ))}
  </form> 
);
}

ReactDOM.render(
<SystemChecklist categories={[]}/>,
mountNode
);



Trying to insert multiple checkbox values in separate rows in MySQL table in PHP not working [duplicate]

I have a simple form in PHP like below:

  <div class="col-md-4 ip"><label>Select Class</label><br>
            <?php
$ret=mysqli_query($con,"select * from class");
$cnt=1;
while ($row=mysqli_fetch_array($ret)) {

?>

<div class="form-check">
  <input name="classname[]" class="form-check-input" type="checkbox" value="<?php echo $row['class_name'];?>" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">
    <?php echo $row['class_name'];?>
  </label>
</div>

    <?php }?>
        </div>

Now I want the user selected checkboxes to get inserted in database in separate rows, so I did the following PHP code:

$classname=$_POST['classname'];

foreach ($classname as $pop ){
$ins_query="insert into study_material (`classname`) values ('$pop')";
}

Now here the issue is only the last selected checkbox value is getting inserted and others are not.




samedi 30 octobre 2021

input check not working with react and I'm not sure how to get it working

I have a component CreateTodo

import React, { useState } from 'react';

const CreateTodo = () => {
  const [todoIsChecked, setTodoIsChecked] = useState(false);
  const [todo, setTodo] = useState('');

  const changeTodoStatus = (e) => {
    console.log(e.target.checked);
  };

  const writeTodo = (e) => {
    setTodo(e.target.value);
  };

  const saveTodo = () => {
    setTodoIsChecked(false);
    const newTodo = { body: todo, isChecked: todoIsChecked };
    todos.push(newTodo);
    localStorage.setItem('todos', JSON.stringify(todos));
  };

  return (
    <form onSubmit={saveTodo}>
      <input
        type='checkbox'
        checked={todoIsChecked}
        onChange={changeTodoStatus}
      />

      <input
        type='text'
        placeholder='Add todo here'
        name='todo'
        value={todo}
        onChange={writeTodo}
      />
      <button onClick={saveTodo}>Add</button>
    </form>
  );
};

export default CreateTodo;

When I render this component I get the following error...

Warning: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.

I tried doing defaultChecked instead of checked and I just get errors as well. What is going on I am drawing a blank because I see others using it the same way I have it.




How to show my entities depending on multiple "CheckBox Inputs "in ASP.NET Core?

I have two entities named Course.cs and CourseGroup.cs and each Course.cs has one CourseGroup.cs inside itself. I've fetched all my CourseGroups inside the ViewPage using a foreach loop and placed them with their values inside input tags as following:

@foreach (var item in courseGroups.Where(c => c.ParentId == null))
{
        <li>
        <input value="@item.CourseGroupId" type="checkbox" name="groupIds" id="cat-1">
        <label for="cat-1"> @item.CourseTitle </label>

        @if (courseGroups.Any(c => c.ParentId == item.CourseGroupId))
        {
                <ul>
                @foreach (var sub in courseGroups.Where(c => c.ParentId == 
                        item.CourseGroupId))
                        {
                                 <li>
                                         <input value="@sub.CourseGroupId" type="checkbox" name="groupIds" id="cat-1">
                                 <label for="cat-1"> @sub.CourseTitle </label>
                                 </li>
                        }
                </ul>
                        }

         </li>

         }

Now, I want to show my Course.css depending on the checked inputs, for example: assume that I have one Course in my DataBase with "Learning Advanced React Native" title, and it has relarions with CourseGroup JavaScript and SubCourseGroup React. So when my application is running, I click on the CheckBox inputs JavaScript and 'React', but it shows me nothing while when I just click on one of them, it will show me the courses!

Bellow is my method function and how to fetch my Courses.cs:


public List<ShowListCoursesViewModel> GetListCoursesByFilters(int pageId = 1, string? filter = null, string buyType = "all",
            string sortType = "NewestDate", decimal startPrice = 0,
            decimal endPrice = 0, List<int>? groupIds = null, int take = 0, bool IsMainPage = true)
{
IQueryable<Course> result = _context.Courses;
.
.
.
if (groupIds != null && groupIds.Any())
{
        foreach (var item in groupIds)
        {
                result = result.Where(c => c.CourseGroupId == item || c.CourseSubGroupId == item);
        }
}
.
.
.
}

and my ActionMethod is as following:

#nullable enable
        public IActionResult Index(int pageId = 1, string? filter = null, string buyType = "all",
            string sortType = "newestDate", decimal startPrice = 0,
            decimal endPrice = 0, List<int>? groupIds = null, int take = 0, bool IsMainPage = true)
        {
            ViewData["byType"] = buyType;
            ViewData["CourseGroups"]=_courseServices.GetGroupsAndSubGroups();
            return View(_courseServices.GetListCoursesByFilters(pageId,filter,buyType,
                sortType,startPrice,endPrice,groupIds,take=9,IsMainPage=false));
        }
    }

Would anybody help?




vendredi 29 octobre 2021

Unbind checkbox selection while clicking on mat table row

I am unable to unbind the selection of checkbox. Please someone who has worked on this before can help me with this code, it would be great.

Reference is Material Table this. I tried removing the toggle but that didnt help as my datas in table did not populate

                                <ng-container matColumnDef="select">
                                  <th mat-header-cell *matHeaderCellDef >
                                    <mat-checkbox (change)="$event ? masterToggle() : null"
                                                  [checked]="selection.hasValue() && isAllSelected()"
                                                  [indeterminate]="selection.hasValue() && !isAllSelected()" (click)="selectAllCheck(isAllSelected(), $event)">
                                    </mat-checkbox>
                                  </th>
                                  <td class="checkbox-area" style="width: 1% !important; padding: 20px !important;  background-color: transparent; border: none;" mat-cell *matCellDef="let row; let i=index" >
                                   
                                        <mat-checkbox (click)="$event.stopPropagation()" 
                                                  (change)="$event ? selection.toggle(row) : null" 
                                                  [checked]="selection.isSelected(row)" (click)="specificSelect(row , selection.isSelected(row))"> 
                                                  
                                    </mat-checkbox>



jeudi 28 octobre 2021

Display image one by one

I have a checkbox in my form that will display images when an item is checked .

Is it possible that the images will be displayed one by one every time an item is clicked because at the moment , every time I checked an item on the checkbox , it is displayed on the div that I assigned .

What I want to achieve is , when an item is checked , it will be displayed and when I clicked another item , the previous image will be overridden by the new item that was checked .

I assigned an ID and class in the image and here is my JS :

jQuery(document).ready(function( $ ){
  
$(function() {
  $('.decalcheckbox input[type=checkbox]').on("change",function() { 
    var checkbox = $(this).val().toLowerCase();
    var checkboxremovespace = checkbox.replace(/ /g, "_")
$('#decal_'+ checkboxremovespace).toggle(this.checked); 
  }).change(
  ); // trigger the change
});

}); 

Sorry for my English but I hope I explained what I want to say .

Thanks .




Wordpress - How to create a checkbox which checks once a user has visited a link

Looking for a way to create a condition for when a user has visited a link on a WordPress site, a checkbox gets checked. I am currently using Gamipress to manage the data, currently, the user needs to check the box of themselves in order to change the state however I'm needing to add an additional condition where when the user has clicked something specific the checkbox gets a checkmark added.

I'm new to Javascript but would like to implement it with JS if possible to have the most control. For context, it is for a to-do list for a user to complete tasks off of. This would be so when a user visits a resource, the checkmark gets added. If anyone has any pieces of advice on how to make this happen it would be greatly appreciated!




How to add a checkbox in pandas dataframe

I have created a dataframe as:

import pandas as pd
 
data = [['Ankit'], ['Akshat' ]]
 
df = pd.DataFrame(data, columns = ['Name'])

Now, I want to insert a column PPA which has checkbox button as values. So, I have written the code as:

import ipywidgets
checkbox_button=widgets.Checkbox(description="", value=False,indent=False)
df.insert(loc = 0,column = 'PPA',value = checkbox_button)

But after running the code in jupyter notebook, I am getting the column values of column PPA as:
Checkbox(value=False, indent=False) but when I run widgets.Checkbox(description="", value=False,indent=False) in the jupyter notebook, I get the proper checkbox button.

So, Can anyone please tell me how to get the checkbox button in a column of a dataframe ?
Any help would be appreciated.




Need help creating a function that checks to see if a checkboxTree is true, indeterminate, or false based on its checkbox options & checkbox children

Having trouble creating a function that checks if the parent checkboxTree is true, indeterminate, or false based on its options which are determined either true, indeterminate or false based on the children of the checkboxTree.

Note: There can be multiple nested checkboxTrees within themselves.

Below are images of the current code as well as the intended result of the function needed. I'm puzzled so apologies if the request is slightly confusing.

Image of current code

Image of intended outcome w working function




How to prevent a check_box_tag from passing it's state along with the values?

I'm working on a form with lots of checkboxes where I implemented some Javascript to have the classic "select all checkboxes" feature.

For this, I have a "master" checkbox that checks it's children check_box_tag's, and also individual check_box_tag's (the children checkboxes) for each element in the iteration block.

html:

  <div data-controller="checkbox-select-all">
    <span class="text-center">
      <%= check_box_tag "coupon[constraint_values][]", nil, false, {
        "data-action": "change->checkbox-select-all#toggleAllCheckboxes",
        "data-checkbox-select-all-target": "selectAll"
          } %> # master checkbox
    </span>

    <% current_account.plans.each do |plan| %>
      <div>
        <span class="text-center">
          <%= check_box_tag "coupon[constraint_values][]", plan.id, false, {
                            "data-checkbox-select-all-target": "checkbox",
                            "data-action": "change->checkbox-select-all#updateSelectAllCheckboxState"} %> # child checkbox
        </span>
        <%= plan.name %>
      </div>
    <% end %>
  </div>

The results of checking only children checkboxes is:

Parameters:

{ 
  "coupon"=> {
    "constraint_values"=>["25", "49", "50"],
  }
}

However, when I check a master checkbox (which makes all it's children checkboxes checked), the master checkbox state "on" is passed along it's children values:

Parameters:

{ 
  "coupon"=> {
    "constraint_values"=>["on", "25", "49", "50"],
  }
}

Is there any way to prevent this? Why is it passing it's state when the children checkboxes do not? They are built the same.




angular : Limit number of checkbox selections

I'm trying to limit base input checkbox

In the code, the limit is informed in ( this.bases.length === 2 ) is work but after the function work I can't update the checkbox

enter image description here

I tried the code but did not works.

HTML :

<div class="form-group row line">
        <div class="p-field-checkbox col-lg-6" *ngFor="let base of listBases">
            <p-checkbox name="group1" value="base" [value]="base" [(ngModel)]="bases (change)="functionBase($event)" [disabled]="checked"  inputId="sv" ></p-checkbox>
            <label for="sv"></label>
        </div>
</div>  

TS :

public checked: boolean = false
public numberOfBase: number = 0
public totalOfBase: number = 0
public bases: string[] = []
public listBases = ['Salade verte','Pate', 'Riz', 'Sans base']

functionBase(e:any){
if (e.target.checked === true){
      this.numberOfBase ++
      if (this.bases.length === 2){
        this.checked = true
      } else { 
              this.checked = false 
             }
    } else {
      this.numberOfBase --
    } 
}

The




Cypress test is not working for focus state for mat-checkbox in Angular

I am trying to test the opacity and color of mat-checkbox when it get focus but it is not working.

My code is as follow:

  it('focused opacity', () => {  
    cy.get('.mat-checkbox[data-cy=selected] .mat-checkbox-input').first()
      .focus()
      .find('.mat-checkbox-focus-overlay')
      .then((btn) => {
        cy.wrap(btn).should('have.css', 'opacity', '0.20');
        cy.wrap(btn).should('have.css', 'background-color')
        cy.wrap(btn).and('be.colored', '#00777');
      });
  });

The error is:

             Timed out retrying after 4000ms: Expected to find element: .mat-checkbox-focus-overlay, but never found it. Queried from element: <input#mat-checkbox-2-input.mat-checkbox-input.cdk-visually-hidden>



mercredi 27 octobre 2021

Display image when checkbox is checked

I was able to do it via dropdown and also hiding the not chosen items with the following ( I am using Elementor/Wordpress )

$('#input_17_19').on('change', function() {
              var item = this.value;
              if(item == "Straw") {
                 $("#decal_preview").hide();
                 $("#decal_straw").show();
                 $("#decal_fork").hide();
                 $("#decal_knife").hide();
                 $("#decal_chopsticks").hide();
                 $("#decal_lids").hide();
                 $("#decal_tips_sign_blue").hide();
                 $("#decal_tips_sign_red").hide();
                 $("#decal_large_takeout_blue").hide();
                 $("#decal_large_takeout_red").hide();
                 $("#decal_small_takeout_blue").hide();
                 $("#decal_small_takeout_red").hide();
                 $("decal_napkin_blue").hide();         
                 $("#decal_napkin_red").hide();
                 $("#decal_regular_soy").hide();   
                 $("#decal_low_soy").hide();
                 $("#decal_pepper_soy").hide();
                 $("#decal_salt_soy").hide();
                 $("#decal_server_station").hide();
              }

But I can't figure out how to do it for checkbox . I assign classes for each images like shown above .

Any help is appreciated .




How can I change multiple Checkboxes in React Hook Form Via state

Oky, so wasted like 12 hours already on this. And I really need help.

I created a filter using an array via Map that returns some checkbox components

Component:

import { useEffect, useState } from "react"

interface Checkbox {
    id: string | undefined,
    name: string,
    reg: any,
    value: any,
    label: string,
    required?: boolean,
    allChecked: boolean
}



const Checkbox = ({ id, name, reg, value, label, allChecked }: Checkbox) => {

    const [checked, setChecked] = useState(false);

    useEffect(() => {
        setChecked(allChecked);
    }, [allChecked])


    return (
        <>
            <label key={id}>

                <input type="checkbox"
                    {...reg}
                    id={id}
                    value={value}
                    name={name}
                    checked={checked}
                    onClick={() => {
                        setChecked(!checked)
                    }}
                    onChange={
                        () => { }
                    }
                />

                {label}

            </label>
        </>
    )
}

export default Checkbox;

Map:


                                    dataValues.sort()
                                        ?
                                        dataValues.map((e: any, i: number) => {

                                            let slug = e.replace(' ', '-').toLowerCase();
                                            return (
                                                <div key={JSON.stringify(e)} id={JSON.stringify(e)}
                                                >
                                                    <Checkbox id={slug}

                                                        name={title as string}
                                                        label={e as string}
                                                        value={e}
                                                        reg=
                                                        allChecked={allChecked}

                                                    />
                                                </div>
                                            )
                                        })
                                        :
                                        null
                                }

State that is just above the Map:

const [allChecked, setAllChecked] = useState<boolean>(false);

When I try to change the state on the parent and check or uncheck all of the checkboxes, nothing happens.

(the form works without a problem if I manually click on the checkboxes, but I cannot do this as I have some sections with over 40 values)

Sample of array:

dataValues = [
    "Blugi",
    "Bluza",
    "Body",
    "Bratara",
    "Camasa",
    "Cardigan",
    "Ceas",
    "Cercel",
    "Colier",
    "Fusta",
    "Geanta Cross-body",
    "Hanorac",
    "Jacheta",
    "Palton",
    "Pantaloni",
    "Pulover",
    "Rochie",
    "Rucsac",
    "Sacou",
    "Salopeta",
    "Set-Accesorii",
    "Top",
    "Trench",
    "Tricou",
    "Vesta"
]



Is there a simple way to use SVGs as a checkbox in JSX?

I have a fairly complicated form that I am working on and I have two SVG's that are styled as checkboxes for the checked and unchecked states. I am trying to find a way to use these instead of the default html checkbox, but still want to be able to disable it. Here is an example of the JSX code for the checkbox, any help is greatly appreciated!

<input type="radio" name='weekly' value="weekly1" id="weekly1" 
checked={this.props.RecurForm.weeklyRadio === 'weekly1'} 
onChange={(e) => { this.onFormChange(e, 'weeklyRadio') }} disabled={(this.props.RecurForm && (this.props.RecurForm.dailyRadio !== 'daily2') ? false : true)} />



I am using a simple checkbox in VUE JS but validation rule is not working

I am using a simple checkbox in VUE JS but validation rule is not working Checkbox Code

<div v-for="option in question.options" :key="reg.id+m+question.id+option.id">
    <input type="checkbox" v-model="attendees[reg.id]['registration'][m].questions[question.id]" :rules="[ (value) => { return ( questionsRequiredRuleCheckBoxes( value, question.required, attendees[reg.id] ['registration'][m].questions[question.id] ) ) } ]" :value="option.id" />
    <label style="padding:10px;"></label> 
</div>

validation rule

questionsRequiredRuleCheckBoxes: ( value, required, v_model ) => {
if( required != 1 ) return true;
    
   if( required == 1 && v_model.length >= 1 ) return true;
    
   if( required == 1 && v_model.length == 0 ) {
       return "At least one item is required.";
    }
}



How to activate textbox depending on checkbox checked and get values from textbox using v-model in Vue js and javascript?

I am new to Vue js. I am trying to do an action form for the rest of API, but I am stuck at this point.

My action form:

<div class="form-group">
   <label class="required"> Social Media </label>
   <b-form-checkbox value="Facebook" v-model="selected"> FaceBook </b-form-checkbox>
   <b-form-checkbox value="Instagram" v-model="selected"> Instagram </b-form-checkbox>
   <b-form-checkbox value="Twitter" v-model="selected"> Twitter </b-form-checkbox>
   <b-form-checkbox v-on:click="onclick()" v-model="selected" > Other:</b-form-checkbox>
      <input type="text" class="form-control" :disabled='isDisabled'>
   <span class="mt-3">Selected: <strong></strong></span>
</div>

My Vue instance

export default {
    data() {
        return {     
            selected: []     
        };
    }

My Output:

Output

Expected output when the checkbox of 'Other' is checked with an input value of 'Friends':

Selected: [ "Facebook", "Instagram", "Twitter", "Friends" ]



mardi 26 octobre 2021

Reactjs: How to handle multiple question checkbox options?

I am working on a survey using react I have multiple questions and choice's in list form and some are type:checkbox where you can select multiple options and some are radio type and I wrote a handle function but the problem is that when I select multiple options for first questions its keep selected options on next question , so I want help that how it will not keep previous question selected options. here is the survey questions list with choices in API form. Here is the code sandbox link I tried please check it and try to help me I am struggling with this few days

https://codesandbox.io/s/fragrant-breeze-gc8us?file=/src/App.js




JQuery is:checked returning two values every click

I have a simple bit of code to show a div of information if a checkbox has been checked, and to hide that div if it is not checked. While building, I ran into an issue that I cannot find any information to resolve. To simplify the problem, I have an if statement, and if the input is checked, it will log "checked". if it isn't checked, it will log "not checked".

$("#my-id") is a div containing a label with a checkbox input inside it

<div id='my-id'>
  <span>
    <label>
      <input type="checkbox">
      test
    </label>
  </span>
</div>

so clicking on it selects and deselects the checkbox input.

$("#my-id").unbind('click').click(function(){
    if($(this).find('input').is(':checked')){
        console.log('checked');
    }
    else {
      console.log('not checked');
    }
});

What I'm seeing in the log with one click is:

not checked
checked

Then when I click the same one again, is shows

checked
not checked

This is messing with the slideUp() and slideDown() functions because they end up getting called twice, and I have parts of my page sliding up and down and up and down. Any insight would be greatly appreciated. I'm sure there is something about JQuery, or it's functions that I do not understand yet.




changing row color depending on identic GroupId with checkbox

i want to add a check box when activated will filter data by the groupId and change identic rows with same color

i want to add a check box when activated will filter data by the groupId and change identic rows with same color




Why last checked checkbox keep it when i go to next questions? ReactJs

i am working on survey questioner and where i have multiple questions and when i check it one question checkbox it keep checked also next questions and so on , so how to now keep check when i go to next question on survey ?

here is json list of questions. Please help me i am struggling fro last few days

Here is what i did not far ?. This is checked function

const processInput = (e) => {
    const checked = e.target.checked;
    let detachedAnswers = answers;
    if (checked) {
      let index = detachedAnswers.findIndex((i) => i.question === show.id);
      // detachedAnswers[index] = e.target.checked;
      detachedAnswers[index].body.push(e.target.value);

      console.log(detachedAnswers);
      setAnswers(detachedAnswers);
    } else {
      const filtered = detachedAnswers[number].body.filter(
        (string) => string !== e.target.value
      );
      detachedAnswers[number].body = filtered;
      setAnswers(detachedAnswers);
    }
  };

here is the survey display using checkbox.

<div className="survey_option">
                {show?.choices?.split(",").map((c, index) => (
                  <div className="fix_lable" key={index + 1}>
                    <input
                      type="checkbox"
                      name="body"
                      id={c}
                      value={c}
                      // checked
                      // checked={c}
                      onChange={(e) => processInput(e, show.id)}
                    />
                    <label id={c} htmlFor={c}>
                      {c.split("-")[0]}
                    </label>
                  </div>
                ))}
              </div>
            </div>



How to dynamically assign ID to a checkbox in a for-each cycle

I have the following code in a ascx : i run a SQL query and I put it in a Datatable. Then I show the values in the page like this

<% For each row As DataRow In myDataTable.Rows %>

    <%=row("something") %>
    <%=row("somethingelse") %>
    <asp:CheckBox ID="CheckBox1" runat="server" />

<% next %>

Now... how can I set the ID of the checkbox dymanically? something like

<asp:CheckBox ID="<%=row("MyId")%>" runat="server" />

that obviously do not work.

I need to set the id as the value I get from the DB so if it is checked I can pass the checked id to another page.




final radio button - detection in multiple groups

I am new in javascript and here but I need help. Is there a way to detect the selection of the last radio button by tracking multiple groups? For example... I have several groups of buttons (5 in example). There are several buttons in each group. (in original project 18 in total, of which 9 are ordinary and 9 are double). Each button in the group has its "characteristics", ie. a specific button can “disable” the next entire group. I want if I check the "double" button that it disables the whole group but that other group is considered as if something of it was selected. Or to clarify ... Below in the specification there is a list of selected buttons. I need to get a display of the final "div" after selecting all the fields in the specification, I named it "box" ih html. In the given example I showed how it would go for groups 1 and 2 (although it doesn’t work well) but to figure out what I need.

The tricky part is that the user can (must) go back to change their selection. Then there is a “refutation” of previous selections, especially if “double” buttons have been selected.

I'm interested in how to solve this whole situation and as for the display of the button name in the specification, also how to select the final "box" after selecting all the buttons.

From here you can download html code and javascript: https://www.dropbox.com/s/awj3t389xmrvmit/checkRadioGroup.rar?dl=0

// GROUP 1 

function GROUP_1_select_1(){
    var check_poz_1 = document.getElementById("check_poz_1");
    var check_poz_2 = document.getElementById("check_poz_2");
    var check_poz_3 = document.getElementById("check_poz_3");

    var choice_1 = document.getElementById("choice_1");
    var choice_2 = document.getElementById("choice_2");
    var choice_3 = document.getElementById("choice_3");

    choice_1.value = 'GROUP 1 - ONE';
    document.getElementById("check_poz_1").checked = true;
    document.getElementById("row_1").innerHTML = "1";
    document.getElementById("row_2").innerHTML = "2";
    document.getElementById("group_2_button_1").disabled = false;
    document.getElementById("group_2_button_2").disabled = false;
    document.getElementById("group_2").style.backgroundColor = "white";
    call_final_box();
    if (check_poz_2.checked == true && choice_2.value == '') {
        document.getElementById("check_poz_2").checked = false;
    } 
    if (check_poz_2.checked == false){
        document.getElementById("check_poz_2").checked = false;
        choice_2.value = '';
    }
    if (choice_3.value == '' && choice_2.value == ''){
        choice_2.value = '';
    }
    if (choice_2.value != '' && choice_3.value == ''){
        document.getElementById("row_2").innerHTML = "2 and 3";
    }
}

function GROUP_1_select_2(){
    var check_poz_1 = document.getElementById("check_poz_1");
    var check_poz_2 = document.getElementById("check_poz_2");

    var choice_1 = document.getElementById("choice_1");
    var choice_2 = document.getElementById("choice_2");
    var choice_3 = document.getElementById("choice_3");
    var check_poz_3 = document.getElementById("check_poz_3");

    document.getElementById("check_poz_1").checked = true;
    document.getElementById("check_poz_2").checked = true;
    document.getElementById("row_1").innerHTML = "1 and 2";
    document.getElementById("row_2").innerHTML = "row 2 will be hidden but must be considered as filled"; // just info
    choice_1.value = 'GROUP 1 - DOUBLE';
    choice_2.value = '';
    document.getElementById("group_2_button_1").disabled = true;
    document.getElementById("group_2_button_2").disabled = true;
    document.getElementById("group_2_button_1").checked = false; 
    document.getElementById("group_2_button_2").checked = false;  
    document.getElementById("group_2").style.backgroundColor = "lightgrey";
    call_final_box();
    if (check_poz_2.checked == true){
        document.getElementById("group_3_button_1").disabled = true;
        document.getElementById("group_3_button_2").disabled = true;
        document.getElementById("group_3_button_1").checked = false; 
        document.getElementById("group_3_button_2").checked = false;
        document.getElementById("group_3").style.backgroundColor = "white"; 
    }
    if (check_poz_3.checked == true){
        document.getElementById("group_3").style.backgroundColor = "white"; 
        document.getElementById("check_poz_3").checked = false;
        document.getElementById("row_3").innerHTML = "3";
    }
}


// GROUP 2


function GROUP_2_select_1(){
    var check_poz_2 = document.getElementById("check_poz_2");
    var check_poz_3 = document.getElementById("check_poz_3");
    var check_poz_4 = document.getElementById("check_poz_4");

    var choice_2 = document.getElementById("choice_2");
    var choice_3 = document.getElementById("choice_3");

    choice_2.value = 'GROUP 2 - ONE';
    document.getElementById("check_poz_2").checked = true;
    document.getElementById("row_2").innerHTML = "2";
    document.getElementById("row_3").innerHTML = "3";
    document.getElementById("group_3_button_1").disabled = false;
    document.getElementById("group_3_button_2").disabled = false;
    document.getElementById("group_3").style.backgroundColor = "white";
    call_final_box();
    if (check_poz_3.checked == true && choice_3.value == '') {
        document.getElementById("check_poz_3").checked = false;
    } 
    if (check_poz_3.checked == false){
        document.getElementById("check_poz_3").checked = false;
        choice_3.value = '';
    }
    if (check_poz_3.checked == true && choice_4.value == ''){
        document.getElementById("check_poz_3").checked = true;
        document.getElementById("row_3").innerHTML = "3 and 4";
        choice_3.value = 'GROUP 2 - DOUBLE';
        document.getElementById("check_poz_4").checked = true;
    document.getElementById("row_4").innerHTML = "row 4 will be hidden but must be considered as filled"; // just info
}

}

function GROUP_2_select_2(){
    var check_poz_2 = document.getElementById("check_poz_2");
    var check_poz_3 = document.getElementById("check_poz_3");
    var check_poz_4 = document.getElementById("check_poz_4");

    var choice_2 = document.getElementById("choice_2");
    var choice_3 = document.getElementById("choice_3");

    document.getElementById("check_poz_2").checked = true;
    document.getElementById("check_poz_3").checked = true;
    document.getElementById("row_2").innerHTML = "2 and 3";
    document.getElementById("row_3").innerHTML = "row 3 will be hidden but must be considered as filled"; // just info
    choice_2.value = 'GROUP 2 - DOUBLE';
    choice_3.value = '';
    document.getElementById("group_3_button_1").disabled = true;
    document.getElementById("group_3_button_2").disabled = true;
    document.getElementById("group_3_button_1").checked = false; 
    document.getElementById("group_3_button_2").checked = false;  
    document.getElementById("group_3").style.backgroundColor = "lightgrey";
    call_final_box();
    if (check_poz_3.checked == true){
        document.getElementById("group_4_button_1").disabled = true;
        document.getElementById("group_4_button_2").disabled = true;
        document.getElementById("group_4_button_1").checked = false; 
        document.getElementById("group_4_button_2").checked = false;
        document.getElementById("group_4").style.backgroundColor = "white"; 
    }
    if (check_poz_4.checked == true){
        document.getElementById("group_4").style.backgroundColor = "white"; 
        document.getElementById("check_poz_4").checked = false;
        document.getElementById("row_4").innerHTML = "4";
    }
}


// call final box after all checbox are checked by button from groups

function call_final_box(){

    var $checks = $('input[name=check_name_specif]:checkbox');
    var numChecked = $checks.filter(':checked').length;

    if (numChecked == 5) {
        document.getElementById("box").style.display = 'flex';
    } else {
        document.getElementById("box").style.display = 'none';
    }
}
<!DOCTYPE html>
<head>
    <meta charset="utf-8" />
    <script src="myScript.js" type="text/javascript">></script>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <style type="text/css"></style>
  <style>
    body {
    width: auto;
    font: sans-serif;
    font-size: 13px;
    font-weight: bold;
  }

  .box{
    width: 500px;
    height: 250px;
    background-color: red;
    display: flex;
  }

  .specification{
    display: flex;
    flex-direction: column;
  }

  .list{
    display: flex;
    justify-content: space-around;
  }

  .group{
    text-align: center;
  }

  </style>
 </head>
<body>
<div class="list">

  <div id="group_1" class="group">GROUP 1<br>
    <label>
    <input type="radio" name="group_1" onclick="GROUP_1_select_1()" id="group_1_button_1" value="GROUP 1 - selected 1">GROUP 1 - ONE</label>
    <br>
    <label>
    <input type="radio" name="group_1" onclick="GROUP_1_select_2()" id="group_1_button_2" value="GROUP 1 - selected 1-2">GROUP 1 - DOUBLE</label>
    <br>
  </div>

  <div id="group_2" class="group">GROUP 2<br>  
    <label>
    <input type="radio" name="group_2" onclick="GROUP_2_select_1()" id="group_2_button_1" value="GROUP 2 - selected 1">GROUP 2 - ONE</label>
    <br>
    <label>
    <input type="radio" name="group_2" onclick="GROUP_2_select_2()" id="group_2_button_2" value="GROUP 2 - selected 2-3">GROUP 2 - DOUBLE</label>
    <br>
  </div>

  <div id="group_3" class="group">GROUP 3<br>  
    <label>
    <input type="radio" name="group_3" onclick="GROUP_3_select_1()" id="group_3_button_1" value="GROUP 3 - selected 1">GROUP 3 - ONE</label>
    <br>
    <label>
    <input type="radio" name="group_3" onclick="GROUP_3_select_2()" id="group_3_button_2" value="GROUP 3 - selected 3-4">GROUP 3 - DOUBLE</label>
    <br>
  </div>

  <div id="group_4" class="group">GROUP 4<br>  
    <label>
    <input type="radio" name="group_4" onclick="GROUP_4_select_1()" id="group_4_button_1" value="GROUP 4 - selected 1">GROUP 4 - ONE</label>
    <br>
    <label>
    <input type="radio" name="group_4" onclick="GROUP_4_select_2()" id="group_4_button_2" value="GROUP 4 - selected 4-5">GROUP 4 - DOUBLE</label>
    <br>
  </div>

  <div id="group_5" class="group">GROUP 5<br> 
    <label>
    <input type="radio" name="group_5" onclick="GROUP_5_select_1()" id="group_5_button_1" value="GROUP 5 - selected 1">GROUP 5 - ONE</label>
    <br>
  </div>

</div>
<br>
<br>

<form name="specification">
  <div class="specification">
    <div >
    <input type="checkbox" class="check_specif" name="check_name_specif" id="check_poz_1" disabled="disabled">
    <label id="row_1">1</label>
    <input type="text" class="checkbox" name="choice" id="choice_1" placeholder="not selected" disabled="disabled">
    </div>

    <div >
    <input type="checkbox" class="check_specif" name="check_name_specif" id="check_poz_2" disabled="disabled">  
    <label id="row_2">2</label>
    <input type="text" class="checkbox" name="choice" id="choice_2" placeholder="not selected" disabled="disabled">
    </div>

    <div >
    <input type="checkbox" class="check_specif" name="check_name_specif" id="check_poz_3" disabled="disabled">
    <label id="row_3">3</label>
    <input type="text" class="checkbox" name="choice" id="choice_3" placeholder="not selected" disabled="disabled">
    </div>

    <div >
    <input type="checkbox" class="check_specif" name="check_name_specif" id="check_poz_4" disabled="disabled">
    <label id="row_4">4</label>
    <input type="text" class="checkbox" name="choice" id="choice_4" placeholder="not selected" disabled="disabled">
    </div>

    <div >
    <input type="checkbox" class="check_specif" name="check_name_specif" id="check_poz_5" disabled="disabled">
    <label id="row_5">5</label>
    <input type="text" class="checkbox" name="choice" id="choice_5" placeholder="not selected" disabled="disabled">
    </div>
  </div>
</form>

<br><br>
  <p>INSTRUCTIONS</p>
  <p>If you check "button_2" this is considered a selection for two groups.</p>
  <p>Once all the rows have been selected it is necessary to display the final "box".</p>
  <p>The program must always know when the LAST field is filled in to display the "box".</p> 
  <p>The user can choose the order of filling and make changes. These changes dictate which fields will be filled.</p>
  <p>If any row have "not selected" the "box" will not be visible</p>
  <div class="box" id="box" style="display: none"></div>
</div>

</body>



lundi 25 octobre 2021

Selenium Python Checkbox Click

I am trying to access the following HTML checkbox for a button click:

<input type="checkbox" data-ng-value="sf.name" data-ng-model="sf.checked" ng-click="ec.onStateFilterChanged(sf)" title="Select a state" class="ng-untouched ng-valid ng-dirty ng-valid-parse" value="Arizona">

using:

state = driver.find_element_by_xpath("input[@type='checkbox']").click()

but keep getting error:

selenium.common.exceptions.NoSuchElementException: Message: 

what might be the element path I am looking for in order to select the checkbox?




React checkbox doesn't keep toggled (think is in infinite loop)

Basically i have this:

const [searchUser, setSearchUser] = useState<string[]>([])

Which i pass as a filter on an array:

reportsData
  .filter((value: any) =>
  searchUser.length > 0
  ? searchUser.includes(value.user.name)
  : true
  )

And i created checkboxes that passes values to this searchUser state so i can filter my array with one (or multiple checkboxes) Like this:

const EmittersComponent: React.FC<PropsButton> = ({ label, onSelect }) => {
    const [checked, setChecked] = useState(false)

    function handleSelect() {
      onSelect(label)
      setChecked(!checked)
    }

    return (
      <div className="grid grid-cols-3 gap-3 lg:grid-cols-2">
        <li className="mt-4 flex items-start">
          <div className="flex items-center h-5">
            <input
              type="checkbox"
              onChange={() => {
                setChecked(checked)
                handleSelect()
              }}
              checked={checked}
              className="h-4 w-4 focus:bg-indigo border-2 border-gray-300 rounded"
            />
          </div>
          <div className="ml-3 text-sm">
            <span className="font-medium text-gray-700">
              {label || 'Sem nome'}
            </span>
          </div>
        </li>
      </div>
    )
  }

  function handleToggle(label: string) {
    setSearchUser((prev) =>
      prev.some((item) => item === label)
        ? prev.filter((item) => item !== label)
        : [...prev, label]
    )
  }

  const emittersComponent = () => (
    <div>
      {emittersData.map((value: any, index: any) => (
        <EmittersComponent
          key={index}
          label={value.Attributes[2]?.Value}
          onSelect={handleToggle}
        />
      ))}
    </div>
  )

Then i render it on my react component <ul>{emittersComponent()}</ul>

But the thing is, it is working everything correctly (if i select one or multiple checkboxes, it filters my array), but the checkbox won't keep toggled. It will render as if it was untoggled (the blank, unchecked box) no matter what i do.

I think is in an infinite loop and i can't fix it.




Filtering with checkboxes with useState

I have an array of things

const reportsData = [
    {
      name: 'Walter',
      Laudos: 1,
    },
    {
      name: 'John',
      Laudos: 20,
    },
  ]

Then on my react component, i need that when i click a checkbox, it sets a state that maked my list filter only that name. Like:

const [searchUser, setSearchUser] = useState('')

{reportsData
                .filter((value: any) => {
                  if (searchUser == '') {
                    return value
                  } else if (
                    value.name
                      .toLowerCase()
                      .includes(searchUser.toLowerCase())
                  ) {
                    return value
                  }
                })

then on the checkbox

<input
  type="checkbox"
  checked={john} // just for example
  onChange={john} // just for example
  className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
/>

I need that when i press this one, it changes the searchUser value to 'John'.

Looked many responses in here but every one of them was messy asf or used this.setState instead of the useState.

How could i achieve this?




Sharepoint - Javascript, How can i add data to multiple choice field set as checkbox

I have five fields in the list. The four fields in the list are of chooice type You can see in the picture

Two of the choice fields are of dropdown type and two of them are of checkbox type. I gave the options that these fields should take while creating For the Checkbox type, I first print the values I have given as default to the screen. Then I assign the value of the selected ones to the array. But I cannot save the data in these arrays to the checkbox type choice fields. I try to save a string instead of array but it still doesn't save. How can we save data to choice fields of type checkbox?

In the code below, selectedPositive and selectedPotential variables take arrays. PotaDurumuOlumlu and PotaDurumuPotansiyel are the names of the choice field fields in the checkbox type, which are in the comment line in cItem. And I can't save there. Can you help me?

function saveForPotaSureci() {
var dealerId = $.urlParam('dealerId');
var potaAction;
if ($("#txtMarketKodu").val() != "") {
    potaAction = "Tamamlandı";
}
else { potaAction = $("#statusAction").text(); }

var potaStatu = $("#ddlPotaStatu").val();

var selectedPositive = selectedPositiveCheckboxValues;
var selectedPotential = selectedPotentialCheckboxValues;
var teststring = "Teminatı alabiliyor mu?";
var magazaKodu = $("#txtMarketKodu").val();
var potaAction2 = $("#statusAction").text();
var portfoyAciklama = $("#txtPotaAciklama").val();
var itemType = "SP.Data.BayiTalepTestListItem";
var cItem = {
    __metadata: {
        type: itemType,
    }
};
cItem = $.extend({}, cItem, {
    PotaStatuDurumu: potaStatu == "" ? null : potaStatu,
    //test: selectedPositive == "" ? null : selectedPositive,
    //PotaDurumuOlumlu: teststring == "" ? null : teststring,
    //PotaDurumuPotansiyel: selectedPotential == "" ? null : selectedPotential,
    MagazaKodu: magazaKodu == "" ? null : magazaKodu,
    PotaAksiyon: potaAction2 == "" ? null : potaAction2,
    PortfoyAciklama: portfoyAciklama == "" ? null : portfoyAciklama
});
if (dealerId != null && dealerId != 0) {
    updateDealerListItemNew2(dealerId, 'BayiTalepTest', cItem, function () {
        console.log('Record updated successfully..');
    });

}
console.log("Pota Statu:" + potaStatu + "Pota Action:" + potaAction + "Olumlu Checkbox:" + selectedPositive + "potansiyel:" + selectedPotential + "magaza kodu:" + magazaKodu);

}




angular Form array for checkboxes - control.registerOnChange error

I have scenario that I need to update dynamically generated checkboxes all the checkboxes are generate from the db

form initializing with the

const filtered = advertisementDetails.workingDistricts.filter(el => {
    return el != null;
});
filtered.map(subAttData => {
    console.log(subAttData, 'DistUpdate');

    const newitem = this.fb.group({
        index: subAttData.index,
        value: subAttData.value,
    });
    this.getworkingDistricts.push(newitem);
});

getter for form array

get getworkingDistricts(): FormArray {
 return this.suppliersForm.get('workingDistricts') as FormArray;
}

html for displaying data

 <div class="check-box-main" *ngFor="let districts of getworkingDistricts.value  ; let i = index">
   <ng-container [formArrayName]="workingDistricts" >
      <input   [formControl] ="districts"  id="districts" (click)="servicedest($event)" value=    type="checkbox"><span></span>
   </ng-container>
</div>

Html for file




Updating the checkbox value based on the backend reponse using react

I'm trying to do an edit function, Where I'll get the data from the backend. So if the value of dependents is '1,2' then box the checkbox should be selected. I should be able to unselect the checkbox and send the value again if needed. In the below one, When we click on the add for the second row I'm checking if value of check box as 2 (line:79) and it's showing as checked. The problem is when I'm unable to unselect it and send it again.

https://codesandbox.io/s/naughty-rhodes-i2sn9?file=/src/App.js




CheckboxTree keeps closing and not staying open

I set up the CheckboxTree plugin. One of the errors I can't find is that CheckboxTree keeps closing and not staying open. CheckboxTree should only close when I press the minus icon. I think it is due to this part of the jQuery code:

$('input[type="checkbox"]').change(function(e) {
  var checked = $(this).prop("checked"),
    container = $(this).parent(),
    siblings = container.siblings();

  container.find('input[type="checkbox"]').prop({
    indeterminate: false,
    checked: checked
  });

  function checkSiblings(el) {
    var parent = el.parent().parent(),
      all = true;

    el.siblings().each(function() {
      return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
    });

    if (all && checked) {
      parent.children('input[type="checkbox"]').prop({
        indeterminate: false,
        checked: checked
      });

      checkSiblings(parent);
    } else if (all && !checked) {
      parent.children('input[type="checkbox"]').prop("checked", checked);
      parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').lenght > 0));
      checkSiblings(parent);
    } else {
      el.parents("li").children('input[type="checkbox"]').prop({
        indeterminate: true,
        checked: false
      });
    }
  }

  checkSiblings(container);
});

$(document).ready(function() {
  $("#tree .open").click(function(e) {
    e.stopPropagation();
    $(this).toggleClass("open closed");
  });
});



Not able to bind checked checkboxes for update

Component .ts file

HTML File

Console Image




dimanche 24 octobre 2021

React Checkbox not being checked or unchecked in popup instantly when it is clicked, instead it is being changed only when the popup is opened again

Here are some screenshots showing the current behavior of the checkbox in popup Current Checkbox behavior

Expected Checkbox behavior in popup: Expected Checkbox behavior

Code:

        let out = "";

        //"choices" is an array, where each row constists 'label_choice' and 'isChecked' fields

        //menus and setMenus is intialized with choices using React useState
        const [menus, setMenus] = React.useState(choices);

        //handleChange function handles the input checkbox change by setting the isChecked field 'true' or 'false' when checked or unchecked
        
        const handleChange = (e) => {
          //setMenus sets the Menus with the updated input change
          setMenus(
            menus.map((o) =>
              o.label_choice === e.target.value ? { ...o, isChecked: !o.isChecked } : { ...o, isChecked: false },
            ),
            out= e.target.value,
          );
        };

body: <div>
           <div style=>
                        {/* menus.map function is used to display all the label_choice along with the input checkbox element */}
                        {menus.map((item) => (
                          <label key={item.label_choice}>
                            {/* checked should be true when the isChecked field is true */}
                            <input type="checkbox" checked={item.isChecked} 
                             value={item.label_choice} onChange={handleChange} />
                            {item.label_choice}
                          </label>
                        ))}
              </div>
         </div>



Check box not copying

I'm using a module to copy one sheet to many, but it doesn't copy the check box I have in the sheet, although if I manually select all and copy it does. Can someone explain why its not working in the VBA script, and if possible, how to get it to work?

Here is the script I am running:

Sub Button4_Click()

Const ExclusionsList As String = "Main,Source," _ & "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday"

Dim Wbk As Workbook
Dim WshSrc As Worksheet
Dim WshTrg As Worksheet
Dim Exclusions() As String
Dim n As Long

Set Wbk = ThisWorkbook
Set WshSrc = Wbk.Worksheets("Source")
Exclusions = Split(ExclusionsList, ",")

Application.ScreenUpdating = False

For Each WshTrg In Wbk.Worksheets
    If IsError(Application.Match(WshTrg.Name, Exclusions, 0)) Then
        WshSrc.Cells.Copy
        With WshTrg
            .Cells.PasteSpecial Paste:=xlPasteAll
            Application.Goto .Cells(1), 1
        End With
    End If
Next

Application.Goto Worksheets("Main").Cells(1), 1

Application.ScreenUpdating = True

End Sub




Change data true or false using checkbox

Hi!

I have a Node.js CMS application using MongoDB, Mongoose and Express.

There is a page that is collecting user info and pass it to the admin. I got that part done. But I also like to be able to change the status to each applies as admin. Like "in progress", "Denied", and "Approved" and save it to the database using only checkboxes.

My approach is the give each applies three checkboxes and in the model one of them is true the others are false. "In progress" is true default, but if I change it to "approved" the database changes the data and "In progress" is false, and "Approved" becomes true.

I tried many thing but nothing works out.

Can you help me? Thanks!

This is the model:

const {Schema, model} = require('mongoose');

const ApplySchema = new Schema({
    firstname: {
        type: String,
        require: true
    },
    lastname: {
        type: String,
        require: true
    },
    applyStatus : {
        "in progress": {
            type: Boolean,
            default: true
        },
        "denied": {
            type: Boolean,
            default: false
        },
        "approved": {
            type: Boolean,
            default: false
        }
    }
});

try {
    module.exports = model('applications', ApplySchema);
} catch (e) {
    module.exports = model('applications');
}

This is the admin route:

router.get('/', (req, res) => {
    Apply.find({})
        .then(applications => {
            res.render('admin/apply/apply', {applications: applications});
        });
});

This is the Handlebars:

 </thead>
  <tbody>
  
    <tr>
      <td></td>
      <td></td>
      <td>
        <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked>
            <label class="form-check-label" for="flexCheckDefault">
                In progress
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
            <label class="form-check-label" for="flexCheckDefault">
                Denied
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
            <label class="form-check-label" for="flexCheckDefault">
                Approved
            </label>
        </div>
      </td>
    </tr>
  
  </tbody>
</table>
</div>
</div>
</div>



Why ticking all checkbox at once doesn't update or fire the (change) event?

If I select a checkbox then it calls the method on (change) event and updates the collection but now I have puyt checkall button that checks all the checkboxes but I cannot figure out how to update the collection in this case?

<input type="checkbox" #chkSelectedSubjectTest (change)="checkAll(chkSelectedSubjectTest.checked)">
<tr *ngFor="let item of mf.data">
            <td>
              <input #chkSelectedSubject type="checkbox" (change)="updateSelection(item.Id, chkSelectedSubject.checked)" 
              class="form-check-input" name="chkSelectedSubject" id="chkSelectedSubject">
            </td>
            <td>  </td>
            <td>  </td>
            <td> </td>
        </tbody>

methods:

  updateSelection(subjectId: number, isChecked: any) {     
    if(isChecked) {
      this.selectedSubjects.push(subjectId);
    }
    else {
      this.selectedSubjects= this.selectedSubjects.filter(item=> item != subjectId);
    }

    if(this.selectedSubjects.length > 0)
      this.isDeleteDisabled= false;
    else
      this.isDeleteDisabled= true;
  }

  checkAll(ele) {

    var checkboxes = document.getElementsByTagName('input');
    if (ele) {
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].type == 'checkbox') {
                checkboxes[i].checked = true;
            }
        }
    } else {
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].type == 'checkbox') {
                checkboxes[i].checked = false;
            }
        }
    }
    console.log(ele)
}



Not able to set checkboxes based on saved results from DB

.ts File: editUser(userData: user): void {

 let selectedProjectIdsList = userData.projectIds.split(',');

    for (let i = 0; i < selectedProjectIdsList.length; i++) {
      this.projects
        .filter((x) => x._id == selectedProjectIdsList[i])
        .map((x) => x.selected = true);

      console.log(
        this.projects
          .filter((x) => x._id == selectedProjectIdsList[i])
          .map((x) => x.selected = true)
      );
    }

}

.html File:

  <ul class="list-group list-row">
              <li class="list-group-item" *ngFor="let item of projects">
                <input
                  class="form-check-input me-1"
                  type="checkbox"
                  value="item._id"
                  (change)="onChangeProject()"
                  [(ngModel)]="item.selected"
                  name="selected"
                />
                 |  |`enter code here`
                
              </li>
            </ul>

Note : After getting API response from backend It checked all the checkboxes




samedi 23 octobre 2021

recyclerview item mishap(undesirable behaviour) in android studio

I have a recycler view with a list of items and each of those items have checkboxes attached to them. When a checkbox is checked, it behaves properly and there is no problem with unwanted items getting checked. But when a checked item is deleted, then the unwanted item gets checked.

My Adapter Class :

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskHolder> {
private static List<Task> tasks = new ArrayList<>();
private static OnItemClickListener listener;
private static TaskAdapter adapter = new TaskAdapter();


@NonNull

@Override
public TaskHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.task_item, parent, false);
    return new TaskHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull TaskHolder holder, int position) {
    Task currentTask = tasks.get(position);
    holder.a_tname.setText(currentTask.getTname());
    holder.a_tdate.setText(currentTask.getTDate());
    holder.a_ttime.setText(currentTask.getTTime());
    holder.a_tprior.setText(currentTask.getTprior());
    holder.bind(tasks.get(position));
   holder.bind2(tasks.get(position));

}
@Override
public int getItemCount() {
    return tasks.size();
}
public void setTasks(List<Task> tasks) {
    this.tasks = tasks;
    Collections.sort( tasks, Task.comparepriority);
    notifyDataSetChanged();
}
public Task getTaskAt(int position){
    return tasks.get(position);
}

 class TaskHolder extends RecyclerView.ViewHolder  {
    private final TextView a_tname;
    private final TextView a_tdate;
    private  final TextView a_ttime;
    private final TextView a_tprior;
    ImageView priorityIndicator;
    CheckBox checkbox;


    public TaskHolder(View itemView) {
        super(itemView);
        a_tname = itemView.findViewById(R.id.a_tname);
        a_tdate=itemView.findViewById(R.id.a_tdate);
        a_ttime = itemView.findViewById(R.id.a_ttime);
        a_tprior = itemView.findViewById(R.id.a_tprior);
        priorityIndicator = itemView.findViewById(R.id.priorityIndicator);
        checkbox = itemView.findViewById(R.id.checkbox);




        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if(listener!=null&&position!=RecyclerView.NO_POSITION){
                    listener.onItemClick(tasks.get(position));
                }
            }
        });

    }

    private void bind(Task task){
        int drawableId;int red = R.color.red;int yellow = R.color.yellow;int green = R.color.green;
        int color1 = ContextCompat.getColor(a_tprior.getContext(), red);
        int color2 = ContextCompat.getColor(a_tprior.getContext(),yellow);
        int color3 = ContextCompat.getColor(a_tprior.getContext(),green);
        switch(task.t_prior){
            case "1": drawableId = R.drawable.ic_baseline_priority_high_24;
            a_tprior.setTextColor(color1);
            break;
            case "2": drawableId = R.drawable.ic_baseline_priority_middle_24;
            a_tprior.setTextColor(color2);
            break;
            case "3" : drawableId = R.drawable.ic_baseline_low_priority_24;
            a_tprior.setTextColor(color3);
            break;
            default: drawableId = R.drawable.ic_baseline_crop_square_24;
        }
        priorityIndicator.setImageDrawable(ContextCompat.getDrawable(priorityIndicator.getContext(),drawableId));
    }

    public void bind2(Task task){
        final boolean[] checked = {true};
        checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkbox.isChecked()) {
                    String pos = Integer.valueOf(getAdapterPosition()).toString();
                    PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).edit().
                            putBoolean("checkbox" + pos , checked[0]).apply();
                    Toast.makeText(checkbox.getContext(), "Way to go! Now swipe to delete", Toast.LENGTH_LONG).show();
                }
                else  {
                    checked[0] =false;
                    String pos = Integer.valueOf(getAdapterPosition()).toString();
                    PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).edit().
                            putBoolean("checkbox" + pos, checked[0]).apply();
                }
            }
        }); String pos = Integer.valueOf(getAdapterPosition()).toString();
        boolean cb = PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).getBoolean
                ("checkbox" + pos, false);
        checkbox.setChecked(cb);
    }

 }
public interface  OnItemClickListener {
    void onItemClick(Task ta);
}
public void setOnItemClickListener(OnItemClickListener listener){
    this.listener = listener;
}

}

Picture 1 Picture 2

My code to delete in HomeFragment.java -

  new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull
                RecyclerView.ViewHolder viewHolder, @NonNull  RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull  RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            new AlertDialog.Builder(getActivity())
                    .setMessage("Do you want to delete this task?")
                    .setPositiveButton("Delete", ((dialog, which) ->
                            taskViewmodel.delete(adapter.getTaskAt(viewHolder.getAdapterPosition()))))
                    .setNegativeButton("Cancel", ((dialog, which) -> adapter.notifyItemChanged(position)))
                    .setOnCancelListener(dialog -> adapter.notifyItemChanged(position))
                    .create().show();


        }
    }).attachToRecyclerView(recyclerView);

May i know what changes should i make to rectify this problem? Thankyou




RecyclerView and notifyDataSetChanged LongClick mismatch

I'm having a weird problem with notifyDataSetChanged() in my Recycler Adapter. If I keep 5 items in an array the code works fine and I can check the checkbox at the item I LongClick, but when I add 5 items or more to the array other checkboxes get checked in my list.

I am using a boolean to toggle between VISIBLE and GONE on the checkboxes when the user LongClicks as well.

Here is my code:

class RecyclerAdapter(private val listActivity: ListActivity) : RecyclerView.Adapter<RecyclerAdapter.Holder>() {

    lateinit var binding: ActivityListItemRowBinding
    var checkboxesVisibility = false
    val dummyArrayWorks = arrayOf("000", "111", "222", "333", "444")
    val dummyArrayFails = arrayOf("000", "111", "222", "333", "444", "555")

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

    override fun getItemCount(): Int = dummyArrayFails.size

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: Holder, position: Int) {

        val item = dummyArrayFails[position]
        
        holder.binding.checkbox.visibility = if (checkboxesVisibility) VISIBLE else GONE
        holder.bindItem(item)

        holder.itemView.setOnLongClickListener {
            if (!checkboxesVisibility) {
                checkboxesVisibility = true
                holder.binding.checkbox.isChecked = true
                notifyDataSetChanged()
                true
            } else {
                false
            }
        }
        holder.itemView.setOnClickListener {
            if (!checkboxesVisibility) {
                //Some other unrelated code
            } else {
                holder.binding.checkbox.isChecked = !holder.binding.checkbox.isChecked
                notifyDataSetChanged()
            }
        }
    }

    class Holder(internal val binding: ActivityListItemRowBinding) : RecyclerView.ViewHolder(binding.root) {

        var item = String()

        fun bindItem(item: String) {
            this.item = item
            binding.itemPlaceHolder.text = item
        }
    }
}

I should add that when I remove the toggle for the checkboxes, and just show the checkboxes on first load, the clicks match the checkmarks without a problem.

Does anybody have any idea of what is going on? All help will be much appreciated!




How To remove checkbox in datatable?

I am using data table but i do not require the checkbox column. How can i remove that checkbox field. Here's my code

 responsiveHelper = undefined;
            var activity = $("#view-activity");
            var Activity = activity.DataTable( {
                fixedColumns: true,
                stateSave: true,
                info: true,
                data : JSON.parse('{!! $activity ?? '' !!}'),
                dom : "<'row'"+
                    "<'col-lg-6 col-md-6 mb-2'l>"+
                    "<'col-lg-6 col-md-6 mb-2'f>>"+
                    "<'card-body py-0'"+
                    "<'table-responsive'tr>>"+
                    "<'card-footer text-center'ip>",
                columns : [
                    {
                        data : "date",
                        orderable : false,
                    },{
                        data : 'description',
                        orderable : false,
                    }
                ],
                order: []
            });



vendredi 22 octobre 2021

Checkbox automatically being selecting when button clicked, how can I stop this?

I am making a calculator and want a specific value to be assigned depending on if the checkbox is checked or not, the code I have might work however everytime I click the "Calculate" button it automatically checks the checkbox even if it wasn't checked in the first place. How would I fix this?

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
    <form>
        <label for="side1">Side 1</label>
        <input type="checkbox" id="side1" name="side1"></input>

        <input type="button" value="Calculate" onclick="run()"></input>

        <span>Total: $</span>
        <span id="totalvalue"></span>
        <script type="text/javascript" src="tek.js"></script>
    </form>
</body>
</html>

JS

function run()
{
  var checkbox = document.getElementById('side1');
  
  if (checkbox.checked = true)
  {
    var output = 5;
  }
  else
  {
    var output = 3;
  }
  
    document.getElementById("totalvalue").innerHTML = output;

}



Array storing data in a sorted way in js [closed]

There are multiple checkboxes and I want to transfer data of checked boxes to an array. I know how to do that but the problem is that it stores data in an array in a sorted way. I am using javascript.

Example: See the attached screenshot of checkboxes

If I click in an order: 1 > 2 >5 >4 then array results in 1 2 4 5. I do not want that. I want the data to be stored in the order it was selected and not in increasing order of index. Please help me with this. Thanks in advance.




Links shown after hitting submit should be opened in a new tab

So I have a homework where we have to create a form with several elements in it. One of them is a checkbox and after it is checked the links shown in the resulting page should be opened in a new tab. NO Javascript, ONLY html and css!

fieldset{
    display: table;
}

p{
    display: table-row;
}

label{
    font-family: Arial;
    padding: 10px;
    display: table-cell;
    
}

input{
    margin-left: 30px;
    display: table-cell;
}
<form action="https://www.google.com/search">
        
            <fieldset> 
                
                <!--Google search/field-->
                <legend>Google search</legend>

                <p>
                <label for="search">Search</label>
                <input id="search" name="q" type="text">
                </p>
                

                <!--Google search/slider-->
                <p>
                <label for="hits">Number of hits</label>
                <input id="hits" type="range"
                        min="1" max="10" value="5"
                        oninput="rangeValue.innerText = this.value"
                        name="num">
                </p>
                

                <!--Google search/Checkbox-->
                <p>
                <label for="newTab">New Tab</label>
                <input id="newTab" type="checkbox" 
                        name="target" value="_blank">
                </p>

                <!--Start search-->
                <input type="submit" value="Start search">
                
            </fieldset>
</form>

At is the code that I tried but I just couldn't get it to work. And sorry if the code is a bit messy, we are now just about a month into html and I'm only at the beginning of learning :)




Check box not working on form before allowed to submit

Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??

<form>
  <p>
    <input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
  </p>

  <p>

    <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>

  <p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>



jeudi 21 octobre 2021

Angular - How to do inline batch update of checkbox columns in a modal / dialog window

I have a modal / dialog of an Angular material table with a couple of checkbox columns and other data from an api. How do I go about making inline updates on the checkbox columns and saving all the changes when I close the dialog and post to the api? I've looked at inline edit examples where you have to click edit on individual rows then edit and save each rows at a time. Requirement is to be able to just click on any checkbox in the table and save all changes.




how to enable checkbox with tapping on text in flutter?

I have a checkbox with a text next to the checkbox I want when user tap on text the checkbox be enable/disable, how can i do that?

  Widget buildRememberCb() {
    return Container(
      height: 200,
      child: Row(
        textDirection: TextDirection.rtl,
        children: [
          Theme(
            data: ThemeData(unselectedWidgetColor: Colors.white),
            child: Checkbox(
              value: isRememberMe,
              checkColor: Color(0xfff44336),
              activeColor: Colors.white,
              onChanged: (value) {
                setState(() {
                  isRememberMe = value!;
                });
              },
            ),
          ),
          Text(
            "Remember Me",
            style: TextStyle(
                fontWeight: FontWeight.w900, fontSize: 18, color: Colors.white),
          ),
        ],
      ),
    );
  }



Trying to create an expandable menu with only html and css

I'm pretty new to coding in general and have been learning CSS. I'm trying to create a drop-down menu page for a website and I'm having difficulty; I understand that JavaScript could probably help with this, but I don't have the time to learn a whole new language.

I've written this code to expand a ul to be visible when a checkbox is checked:

#nav-bar ul {
  position: fixed;
  top: 0;
  right: 0;
  visibility: hidden
}

#menu:checked~#nav-bar ul {
  visibility: visible;
  height: 100vh;
  width: 25vw;
}
<div class="site-nav-container" id="nav-bar" style="display: block">
  <div class="snc-header">
    <input type="checkbox" id="menu">
  </div>
  <nav class="site-nav">
    <ul id="menu-primary-nav" class="sn-level-1">
      <li>item1</li>
      <li>item2</li>
      <li>item3</li>
      <li>item4</li>
    </ul>
  </nav>
</div>



Tkinter multiple checkboxes after the selection from a listbox

I'm trying to generate a list of checkboxes depending on the selection in another list box. For example: in the main list box I have 3 entries: Europe, Asia, Africa. Each entry is a list of Nation within the continent I would like to see all the objects inside the list as checkboxes when I select one. For example, if I select Europe I would have as checkboxes: Italy, Spain etc etc... if I select Africa the checkboxes that appear will be Congo, Nigeria etc...

The main problem I have is the formatting of the boxes when they appear and how to get the information on the status (variable) of the box. I'm having problems because the variable indicating each box is not saved in the main script. So I do not know how to recover the value to continue with my script, Any suggestion?




Dynamically Enable/Disable a DropDownList based on CheckBox

I've got the following in a partial view, representing a row that is added dynamically:

<td>
    <input asp-for="Id" class="form-control" />   
</td>
<td>
    <input asp-for="EnableDropDown1" id="EnableDropDown1Id" type="checkbox" class="form-control" />
</td>
<td>
    <select asp-for="MyDropDown1" id="MyDropDownId1" asp-items="Html.GetEnumSelectList<MyEnum1Type>()" disable="disabled" class="form-control"></select>
</td>
<td>
    <input asp-for="EnableDropDown2" id="EnableDropDown2Id" type="checkbox" class="form-control" />
</td>
<td>
    <select asp-for="MyDropDown2" id="MyDropDownId2" asp-items="Html.GetEnumSelectList<MyEnum2Type>()" disable="disabled" class="form-control"></select>
</td>

I thought that maybe an onclick="EnableDropDown()" call attached to the CheckBox (that took a checkbox and a dropdown parameter) might do the trick, but it doesn't keep the state nor does the checkbox find the appropriate dropdown. I could loop through all the rows on a click and enable/disable dropdowns appropriately but this seems like a poor solution.

I've seen a fair few solutions out there but none of the simple ones work... either because they're not dynamic, or maybe it's down to the multiple checkboxes, or the fact it's an EnumSelectList and not a simple DropDown (Is there a difference?)..

I'm not too well-versed on javascript so I'm a bit lost with this one.




Checkboxes not getting value when inside another function

I am new to python and stackoverflow so sorry if I did some mistakes. So I have a problem when making a mock Covid 19 app for my uni assignment. I'm using tkinter to make the GUI and the problem starts when ranking people if they are high risk or low risk based on the questions prepared. When I code in another file, it works fine, but when I put it in my full GUI, it wont get the value. This is the part where they work ;

def risk() :

    Q1 = x01.get() 
    Q2 = x02.get() 
    Q3 = x03.get() 
    Q4 = x04.get() 
    Q5 = x05.get()  
    Q6 = x06.get()  
    Q7 = x07.get() 
    Q8 = x08.get() 
    Q9 = x09.get()
    Q10 = x10.get()
    Q11 = x11.get()

    eg = [Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9 ,Q10, Q11]
    print(eg)


def update() :

    updatescreen = Tk()
    updatescreen.geometry('690x690')
    updatescreen.title('Update Covid-19 Status')
    updatescreen.config(background = '#735DA2')
    global x01
    global x02
    global x03
    global x04
    global x05
    global x06
    global x07
    global x08
    global x09
    global x10
    global x11

    x01 = IntVar()
    x02 = IntVar()
    x03 = IntVar()
    x04 = IntVar()
    x05 = IntVar()
    x06 = IntVar()
    x07 = IntVar()
    x08 = IntVar()
    x09 = IntVar()
    x10 = IntVar()
    x11 = IntVar()

    Label(updatescreen, text = 'Update Covid-19 Status', bg = '#965DA2', fg = 'white', width = 420, height = 2).pack()

    Label(updatescreen, text="", bg = '#735DA2').pack()

    Label(updatescreen, text="Have you returned from an overseas trip in the past 14 days?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x01, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Did you attend any gatherings identified as clusters by MOH in the past 14 days?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x02, onvalue = 1, offvalue = 0, bg = '#735DA2').pack() 

    Label(updatescreen, text="Are you a close contact of a confirmed COVID-19 person?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x03, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Any of your family household members being confirmed positive for COVID-19?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x04, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Have you been working / face-to-face in the same confined space with less than 1-meter distance for more than 15 minutes?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x05, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Have you been in the same vehicle (more than 2 hours) within 2 meters from an individual who is positive of COVID-19?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x06, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="", bg = '#735DA2').pack()

    Label(updatescreen, text = 'Symptoms', bg = '#965DA2', fg = 'white', width = 420, height = 2).pack()
    Label(updatescreen, text="", bg = '#735DA2').pack()

    Label(updatescreen, text="Fever?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x07, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()


    Label(updatescreen, text="Cough?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x08, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Sore Throat?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x09, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="Runny Nose?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x10, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()


    Label(updatescreen, text="Shortness of Breath?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x11, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Button(updatescreen, text = 'submit', width=10, height=2, bg='#5D69A2', fg='black', command = risk).pack()


    updatescreen.mainloop()

update()

The problem is when I put the in another function like so ;

def userprofile():
    global profilescreen
    profilescreen = Tk()
    profilescreen.geometry('420x420')
    profilescreen.title('User Profile')
    profilescreen.config(background = '#735DA2')

    Label(profilescreen, text = 'User Profile', bg = '#965DA2', fg = 'white', width = 420, height = 2).pack()

    Label(profilescreen, text="", bg = '#735DA2').pack()
    Label(profilescreen, text="", bg = '#735DA2').pack()
    Label(profilescreen, text="", bg = '#735DA2').pack()

    Button(profilescreen, text = 'Update Covid-19 Status', command = update, width=35, height=2, bg='#5D69A2', fg='black').pack()

    Label(profilescreen, text="", bg = '#735DA2').pack()

    Button(profilescreen, text = 'Check Appointment Date,Location, and Time', width=35, height=2, bg='#5D69A2', fg='black').pack()

    Label(profilescreen, text="", bg = '#735DA2').pack()

    Button(profilescreen, text = 'Respond to the Assigned Appointment', width=35, height=2, bg='#5D69A2', fg='black').pack()

    Label(profilescreen, text="", bg = '#735DA2').pack()

    profilescreen.mainloop()

    



def risk() :

    Q1 = x01.get() 
    Q2 = x02.get() 
    Q3 = x03.get() 
    Q4 = x04.get() 
    Q5 = x05.get()  
    Q6 = x06.get()  
    Q7 = x07.get() 
    Q8 = x08.get() 
    Q9 = x09.get()
    Q10 = x10.get()
    Q11 = x11.get()

    eg = [Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9 ,Q10, Q11]
    print(eg)


def update() :

    profilescreen.withdraw()
    global updatescreen
    updatescreen = Tk()
    updatescreen.geometry('690x690')
    updatescreen.title('Update Covid-19 Status')
    updatescreen.config(background = '#735DA2')

    global x01
    global x02
    global x03
    global x04
    global x05
    global x06
    global x07
    global x08
    global x09
    global x10
    global x11

    
    Label(updatescreen, text = 'Update Covid-19 Status', bg = '#965DA2', fg = 'white', width = 420, height = 2).pack()

    Label(updatescreen, text="", bg = '#735DA2').pack()

    x01 = IntVar()
    Label(updatescreen, text="Have you returned from an overseas trip in the past 14 days?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x01, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x02 = IntVar()
    Label(updatescreen, text="Did you attend any gatherings identified as clusters by MOH in the past 14 days?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x02, onvalue = 1, offvalue = 0, bg = '#735DA2').pack() 

    x03 = IntVar()
    Label(updatescreen, text="Are you a close contact of a confirmed COVID-19 person?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x03, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x04 = IntVar()
    Label(updatescreen, text="Any of your family household members being confirmed positive for COVID-19?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x04, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x05 = IntVar()
    Label(updatescreen, text="Have you been working / face-to-face in the same confined space with less than 1-meter distance for more than 15 minutes?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x05, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x06 = IntVar()
    Label(updatescreen, text="Have you been in the same vehicle (more than 2 hours) within 2 meters from an individual who is positive of COVID-19?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x06, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    Label(updatescreen, text="", bg = '#735DA2').pack()

    Label(updatescreen, text = 'Symptoms', bg = '#965DA2', fg = 'white', width = 420, height = 2).pack()
    Label(updatescreen, text="", bg = '#735DA2').pack()

    x07 = IntVar()
    Label(updatescreen, text="Fever?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x07, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x08 = IntVar()
    Label(updatescreen, text="Cough?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x08, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x09 = IntVar()
    Label(updatescreen, text="Sore Throat?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x09, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x10 = IntVar()
    Label(updatescreen, text="Runny Nose?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x10, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()

    x11 = IntVar()
    Label(updatescreen, text="Shortness of Breath?", bg = '#735DA2', fg = 'black').pack()
    Checkbutton(updatescreen, text = 'click if yes', variable = x11, onvalue = 1, offvalue = 0, bg = '#735DA2').pack()


    Button(updatescreen, text = 'submit', width=10, height=2, bg='#5D69A2', fg='black', command = risk).pack()


    updatescreen.mainloop()

userprofile()

Any kind of help would be very appreciated. This had me working on this part for hours. Thank you :)




mercredi 20 octobre 2021

gspread Python How to set the value of a checkbox

I'm using python to manipulate a gsheet and I can't seem to find a straight forward answer to this question. From what I can tell, it requires the use of DataValidationRule and set_data_validation_rule, but I'm in over my head in this and was wondering if some of you nice people wouldn't mind setting me straight.




How to translate checked boxes into plots

I hope the title is not too confusing. I have a large Data file with many columns, they all have titles and the data is loaded into pandas, the x-axis should be the date.

Now I want to create an interactive plot with the data, so you can see all the checkboxes and can select, which data should be shown in the plot.

I have found that maybe bokeh is the best way to do it, but I am a bit stuck. I habe already created the checkboxes (checkbox_group), but I dont know how to translate that into a plot.

Obvously I dont want to create around 300 boxes and plots manually, so I am looking for a solution, that takes all the heades and then plots the data from that column if the box is checked.




mardi 19 octobre 2021

holoviz panel checkboxgroup updated value not being passed to the function

The code below renders the widget and the corresponding line chart. But when you check/uncheck additional checkboxes, the function doesn't seem to receive the updated values of checkboxgroup. The chart does not get updated with additional lines. Thanks in advance for your help. '''

    hsType = pn.widgets.CheckBoxGroup(name='Housing Types', value=['High'], options=['High','Medium','Low'])

    @pn.depends(hsType.param.value)

    def hsLinePlot(hsType):
         fig, uTLine = plt.subplots(figsize=(10,6))
         for col in hsType:
              uTLine.plot(df['Date'], df[col], label=col)
              #print(col)
         uTLine.legend()
         return uTLine
    pn.Column(hsType,hsLinePlot)

'''

line chart




How show checkbox checked data-img on list

I have this field

<input class="red-heart-checkbox " name="photo[]" type="checkbox" value="<?php echo $id; ?>" id="<?php echo $id; ?>" data-img="<?php echo $imageURL; ?>"/>

And I would like to make a list of image with url image from the data-img checked but I only have values with this code :

<script>
            $(function() {
        var masterCheck = $("#masterCheck");
        var listCheckItems = $("#devel-generate-content-form :checkbox");

        masterCheck.on("click", function() {
          var isMasterChecked = $(this).is(":checked");
          listCheckItems.prop("checked", isMasterChecked);
          getSelectedItems();
        });

        listCheckItems.on("change", function() {
          var totalItems = listCheckItems.length;
          var checkedItems = listCheckItems.filter(":checked").length;

          if (totalItems == checkedItems) {
            masterCheck.prop("indeterminate", false);
            masterCheck.prop("checked", true);
          }
          else if (checkedItems > 0 && checkedItems < totalItems) {
            masterCheck.prop("indeterminate", true);
          }
          else {
            masterCheck.prop("indeterminate", false);
            masterCheck.prop("checked", false);
          }
          getSelectedItems();
        });

        function getSelectedItems() {
          var getCheckedValues = [];
          getCheckedValues = [];
            
          listCheckItems.filter(":checked").each(function() {
            getCheckedValues.push($(this).val());
          });
            
          $("#selected-values").html(JSON.stringify(getCheckedValues));
        }
      });
        </script>
        

My result is on :

<li class="list-group-item" id="selected-values"></li>

And looks like this :

result of script

Is it possible to have url image instead of the value , or use the result with de database to have url image ?

Thanks a lot !




Como enviar un valor +1 a un campo numerico de sql por medio de la activacion de un checkbox en un documento aspx

Estoy llevando a cabo una aplicacion(aspx document) de encuestas de satisfaccion, y estoy trabajando con controladores de tipo checkbox (esto para permitir cambiar el icono antes y dsp de presionarlo)

Me gustaria conocer una manera de incrementar (+1) el campo correspondiente en la tabla de sql, al checkbox presionado.




how to return blank values with checked checkbox

How to return blank values from datagridview columns using checkbox, who is checked. So how it is in both pictures, I want to filter blank rows without date and it should work as filter as blank.

That checkbox gets data from database.

I tried some if statements in my sql procedure.

if @INNOT_CLOSED_CARDS is not null
        set @WHERE = @WHERE + 'AND EXISTS (select hosp_ID from D3_HOSPITALIZATION
            where isnull(CLOSE_DATE,'''') = '''')'

Or something like this.

if @INNOT_CLOSED_CARDS = 1
    BEGIN
        set @WHERE = @WHERE + ' AND (CLOSE_DATE is null)'
    END ELSE if @INNOT_CLOSED_CARDS = 0
    BEGIN
        set @WHERE = @WHERE + ' AND (CLOSE_DATE is not null)'
    END

Well, it does nothing.

enter image description here

enter image description here




CheckBox Data to ListBox (VBNet)

the problem with my code is that when i initially select a particular checkbox it works well and displays selected item in listbox, but when selected again it creates another entry within the listbox and when i remove it i have to uncheck the same checkbox the times it has been displayed in the listbox when i click the btnSubmit.

Can someone tell me what's wrong with the code, thank you so much

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    If CheckBox1.Checked Then
        ListBox1.Items.Add(CheckBox1.Text)
    Else
        ListBox1.Items.Remove(CheckBox1.Text)
    End If
    If CheckBox2.Checked Then
        ListBox1.Items.Add(CheckBox2.Text)
    Else
        ListBox1.Items.Remove(CheckBox2.Text)
    End If
    If CheckBox3.Checked Then
        ListBox1.Items.Add(CheckBox3.Text)
    Else
        ListBox1.Items.Remove(CheckBox3.Text)
    End If
    If CheckBox4.Checked Then
        ListBox1.Items.Add(CheckBox4.Text)
    Else
        ListBox1.Items.Remove(CheckBox4.Text)
    End If
    If CheckBox5.Checked Then
        ListBox1.Items.Add(CheckBox5.Text)
    Else
        ListBox1.Items.Remove(CheckBox5.Text)
    End If
    If CheckBox6.Checked Then
        ListBox1.Items.Add(CheckBox6.Text)
    Else
        ListBox1.Items.Remove(CheckBox6.Text)
    End If
End Sub



lundi 18 octobre 2021

Change data in MongoDB from admin page

Hi, there!

I have a school managing system CMS with Node.js, MongoDB and Mongoose. This site has no registration so everyone can apply to courses. The person applying give personal data push submit and the data given goes to the admin page.

My goal is the find a way to keep track where is the student process at. The data is being rendered in a table and that table has a column where you can change the status: 'approved', 'denied', and 'in progress'. The model schema for it is set to 'default: 'in progress'.

What I want to do is to put three checkboxes in the admin table and if I check for example 'denied' the data is changed and save in the database as well from the default 'in progress' to 'denied'.

I tried to find a solution in Mongoose documentation but nothing came up and I am very new to Node.

Can any of suggest a method how to approach this problem?

Thank you!