dimanche 31 mai 2020

How to parse links (or any HTML tags) from external source (e.g. json) in re-useable pug template?

To my understanding, pug templtes are to be re-used. So I set up a collection for building forms and have partials like input.pug, textarea.pug, checkbox.pug, radio-buttons.pug`, etc.

In order to make sense of their reusability, they of course should show different text whenever they are used. Therefore I use - locals.msg = Some custom Text in the pug template that includes any of the form partials.

But as soon as it comes to provide more complex text that consists of links or contains styling elements (like b or a span tag with classes), the text is not parsed properly. This is what I have: a simple checkbox for GDPR acceptance that a user must click in a form. The explanation text is supposed to provide an external link to a page, where the user can read all about the site's data protection:

// parent pug template
div(class="[...]")

  - var form = { id: 'for-gdpr', txt: 'I have read <a href="#" target="_blank">GDPR</a> ...' }
  include ./form/checkbox.pug


// checkbox pug template
label(class="flex items-baseline block w-full")
  input(class="..." type="checkbox")
    div(class="...")= form.txt 

Of course this does not generate a proper link, instead that a-tag is "written out".

I also tried splitting text like this:

- var form = { msg1: 'I have read ', msg2: 'a(class="..." href="..." target="_blank" data protextion ', msg: ' and concur.'}

but to no avail.

How would I have to prepare the text in order to then parse it properly in a pug template?

Thank you!




Indeterminate select all checkbox in datatables is not rendering correctly after updating chrome to latest version(83.0.4103.61)

I am using gyrocode plugin for checkboxes implementation with selection in datatables.

Details are here https://www.gyrocode.com/projects/jquery-datatables-checkboxes/

JSFiddle implementation https://jsfiddle.net/gyrocode/snqw56dw/

when we select any row to get indeterminate state for select all checkbox, it will not render correctly. You can try even on above link.

enter image description here




How to add an dynamically a checkbox element on a Tabcontrol after Tabcontrol.Pages is from GUI Designer?

can i add tabcontroll elements after programm started?

For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        Me.Controls.Add(cBox)
        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

    Next i

Instead of using Me.Controls i wanna add the checkboxes after programm started dynamically.




How to check which checkboxes are checked in PyQt5

I'm trying to create a simple desktop app that gets an IP address and show it's location using a REST API (including country, city, isp, regionName and timezone). I have 5 checkboxes in my form so that the user can decide what data will be shown (city, country, isp etc).

The way i did it was by using 5 If statements for each checkbox which don't seem a good way of doing it. Also in order to set the returned values from API to the lineEdits, again i had to use 5 if statements for each lineEdit.

Is there any other way of checking which checkboxes are checked so that i can call the API with the data related to those checkboxes? My snippet:

def set_params(self,IP):
        try:
            socket.inet_aton("%s" %IP)
        except:
            pass #for now

        else:
            
            
            if self.ui.checkBox_City.isChecked():

                city = "city"
            else:
                city = None
            
            if self.ui.checkBox_Country.isChecked():
                country = "country"
            else:
                country = None

            if self.ui.checkBox_Rname.isChecked():
                Rname = "regionName"
            else:
                Rname = None

            if self.ui.checkBox_ISP.isChecked():
                ISP = "isp"
            else:
                ISP = None

            if self.ui.checkBox_Time.isChecked():  
                time = "timezone"
            else:
                time = None 

            
            param = {"fields": "{},{},{},{},{}".format(country,city,ISP,Rname,time)}             
    

            r = requests.get("http://ip-api.com/json/{}".format(IP), params=param)

            resdict = r.json()
            #print(resdict)
            

            if "country" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["country"])

            if "city" in resdict.keys():
                self.ui.lineEdit_City.setText(resdict["city"])

            if "isp" in resdict.keys():
                self.ui.lineEdit_ISP.setText(resdict["isp"])

            if "timezone" in resdict.keys():
                self.ui.lineEdit_Time.setText(resdict["timezone"])

            if "regionName" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["regionName"])



Deselecting checkboxes

I have 2 check boxes, I save them using sharedPreferences, however, I need one check box to be deselected if the other one is selected.

My code:

public static CheckBox checkHolyPaiges, checkDefault;
public static boolean checkHolyPaiges2, checkDefault2;

checkDefault = (CheckBox) findViewById(R.id.checkDefault);
    checkHolyPaiges = (CheckBox) findViewById(R.id.checkHolyPaiges);

final SharedPreferences prefs = getSharedPreferences("game", MODE_PRIVATE);

    if (checkHolyPaiges.isChecked())
    {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("checkHolyPaiges", true);
        editor.apply();

        checkDefault.setChecked(false);
    }

    if (checkDefault.isChecked())
    {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("checkDefault", true);
        editor.apply();

        checkHolyPaiges.setChecked(false);
    }

    checkHolyPaiges2 = prefs.getBoolean("checkHolyPaiges", false);
    checkDefault2 = prefs.getBoolean("checkDefault", true);



Jquery limit checkbox selection doesn't work

I have big complex form, there can be similar checkboxes with the same class or even name. So I need that some of them would restricted from checking more then once. I found good examples how to do that but none of them worked for me. Can someone take a look and say what I'am doing wrong thanks. When pushing green button script generates similar form so i need that checkbox pagrindines would be allowed to select once through all generated forms if there is selected no more can be in other places ofcourse would be great that deselect and changing in another checkbox work.

$('#skaicius').val(2);
$(document).ready(function(){
        $('#duomenys').submit(function(){
                $('#skaicius').val($('.fieldGroup').length*1+1);
        })
    //papildomu pareigu limitas
    var maxGroup = 10;
    //$('#skaicius').val(2);
    //papildomu pareigu pridejimas
    $(".prideti").click(function(){
        if($('body').find('.fieldGroup').length < maxGroup){
            var fieldHTML = '<div class="row form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
            $('body').find('.fieldGroup:last').after(fieldHTML);
                        
        }else{
            alert('Viršintas didžiausias papildomų pareigų skaičius.');
        }
    });
        
        
        $(document).on("change",".form-check-input",function(){
                var inputklase =$(this).attr("name");
                //console.log(inputklase);
                $(this).closest("div").find("input."+inputklase).val($(this).is(":checked")?1:0);
                        
        })    
        
    //papildomu pareigu salinimas
    $("body").on("click",".salinti",function(){ 
        $(this).parents(".fieldGroup").remove();
                
    });
        
        /* not working limit
        var $ckb = $(":checkbox[name=pagrindines1]").on("change", function(){
        
        var $checked = $ckb.filter(":checked");
        $ckb.not($checked).prop("disabled", $checked.length >= 1);


        });
        */
        
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

                        <div class="container">                   
                                                <div class="row form-group fieldGroup">
                                                <h4>Darbuotojo pareigos</h4>
                                                <div style="position: relative; top: 8px; left: 10px;"><a href="javascript:void(0)" class="tbtn-print btn-sm btn-success prideti" title="[Pridėti pareigas]"><span class="fas fa-plus"></span></a></div>
                            <div class="col-md-12">
                                <label class="text-black" for="kodas">Tabelio nr.</label>
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">
                            </div>
                                                        <div class="col-md-12">
                                <label class="text-black" for="imone">Įmonė</label>
                                <select class="form-control" name="imone[]" >
                                                                                @foreach ($imones as $imone)
                                        <option value=""></option>
                                                                                @endforeach
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="text-black" for="miestas">Miestas</label>
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value=""></option>
                                    @endforeach
                                </select>
                            </div>
                                                        <div class="col-md-2">
                                <label class="text-black" for="test2">Pad. kodas</label>
                                <input type="text" id="test2" name="padkodas[]" class="form-control">
                            </div>
                                                        <div class="col-md-10">
                                <label class="text-black" for="padalinys">Padalinys</label>
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value=""> - </option>
                                                                                @endforeach
                                </select>
                            </div>
                                                        <div class="col-md-2">
                                <label class="text-black" for="test2">Pareigu kodas</label>
                                <input type="text" id="test2" name="parkodas[]" class="form-control">
                            </div>
                                                        <div class="col-md-10">
                                <label class="text-black" for="pareigos">Pareigos</label>
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value=""> - </option>
                                                                                @endforeach
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="dpradzia">Darbo pradžia</label>
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
                            </div>


                            <div class="col-md-6">
                                <label class="text-black" for="bandomasis_laikotarpis">Bandomasis laikotarpis</label>
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
                            </div>


                            <div class="col-md-6">
                                <label class="text-black" for="terminuota_sutartis">Terminuota sutartis</label>
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="atldata">Atleidimo data</label>
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">
                            </div>

                                                        
                                                        <div class="col-md-12">
                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
                                                                <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
                                                                <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="vadovastxt">Vadovas</label>
                            </div>
                                                        <div class="col-md-12">
                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" value="1" name="pagrindines1" >
                                                                <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
                                                                <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="pagrindinestxt">Pagrindinės (Generuoti barkodą pagal šią kortelę.)</label>
                            </div>
                        </div>
                                                <!-- Papildomos pareigos -->
                                                <div class="row form-group fieldGroupCopy" style="display: none;" >
                                                <h4>Papildomos pareigos</h4>
                                                <div style="position: relative; top: 8px; left: 10px;"><a href="javascript:void(0)" class="tbtn-print btn-sm btn-danger salinti" title="[Šalinti]"><span class="fas fa-minus"></span></a></div>
                            <div class="col-md-12">
                                <label class="text-black" for="kodas">Tabelio nr.</label>
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">
                            </div>
                                                        <div class="col-md-12">
                                <label class="text-black" for="imone">Įmonė</label>
                                <select class="form-control" name="imone[]" >
                                                                                @foreach ($imones as $imone)
                                        <option value=""></option>
                                                                                @endforeach
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="text-black" for="miestas">Miestas</label>
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value=""></option>
                                    @endforeach
                                </select>
                            </div>
                                                        <div class="col-md-2">
                                <label class="text-black" for="test2">Pad. kodas</label>
                                <input type="text" id="test2" name="padkodas[]" class="form-control">
                            </div>
                                                        <div class="col-md-10">
                                <label class="text-black" for="padalinys">Padalinys</label>
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value=""> - </option>
                                                                                @endforeach
                                </select>
                            </div>
                                                        <div class="col-md-2">
                                <label class="text-black" for="test2">Pareigu kodas</label>
                                <input type="text" id="test2" name="parkodas[]" class="form-control">
                            </div>
                                                        <div class="col-md-10">
                                <label class="text-black" for="pareigos">Pareigos</label>
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value=""> - </option>
                                                                                @endforeach
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="dpradzia">Darbo pradžia</label>
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
                            </div>


                            <div class="col-md-6">
                                <label class="text-black" for="bandomasis_laikotarpis">Bandomasis laikotarpis</label>
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
                            </div>


                            <div class="col-md-6">
                                <label class="text-black" for="terminuota_sutartis">Terminuota sutartis</label>
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="atldata">Atleidimo data</label>
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">
                            </div>

                                                        
                                                        <div class="col-md-12">
                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
                                                                <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
                                                                <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="vadovastxt">Vadovas</label>
                            </div>
                                                        <div class="col-md-12">
                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" name="pagrindines1" >
                                                                <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
                                                                <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="pagrindinestxt">Pagrindinės (Generuoti barkodą pagal šią kortelę.)</label>
                            </div>
                        </div>
                                                <!-- Papildomos pareigos pabaiga -->
                                                
                        </div>



samedi 30 mai 2020

Using Jquery how do I get dynamically generated checkboxes checked status inside a function called on a button click

Using jquery, coming out of an ajax call I have an 'each' statement that generates checkboxes. Here is the line that actually does the generation and append inside my script.

$('<input />', { type: 'checkbox', id: value.rental_accessories_id, value: value.partnumber, class: 'accessories' }).appendTo($('#form_container');

On a click of a button I am executing a function in the main HTML code.

<button type="button" onclick="calculate()" id="calc">CALCULATE</button>

Inside the function, so back in the script, I need to know if these checkboxes have been selected. I can grab the elements using this code and verify they are there, but cannot get a checked status:

    function calculate() {
$('#form_container input, #form_container select').each(
                function(index){  
                    var input = $(this);
                    console.log('Id:' + input.attr('id'));
                    console.log('Type: ' + input.attr('type'));
                    console.log('Name: ' + input.attr('name'));
                    console.log('Value: ' + input.val());
                    console.log($('#' + input.attr('id')).checked);
                    if(input.attr('type') == 'checkbox')
                    {
                        checked_status = input.parent().find('input[name="'+input.attr('name')+'"]:checked').val();
                        console.log('Checked Status' + checked_status);
                    }
                }
            );
}

The id, type, name, and value are coming through find. But I am getting a 'undefined' on the checked status request. I've tried two different methods that are shown here but both of them return undefined. I'm creating a couple other form field types which is why I am looking for both input and select. I can find everything else I am looking for except whether or not the checkboxes have been checked.

I've already done some digging on this site looking for an answer. You might recognize some of the code above as coming from suggestions from other questions that are similar. I'm not an expert on jquery but a lot of the suggestions mention using .on, but the examples do not seem to apply to what I am doing, or if they do apply I am not sure how to implement them for this specific setup.




How to make JList items editable?

I have a JList consisting of JPanels in which there are checkboxes, labels and buttons. The problem is that I cannot edit this items. I would like to be able to check the boxes or push the buttons of items. How can I do it?enter image description here




Is there a way to disable checkboxes with different names and id, if radio button is checked?

I figured out the solution, but the name attribute must be the same or it won't work. I was thinking of auto-incrementing the id attribute someway, but I had no luck so far. Here's what I have so far(that works):

function ckChange(ckType) {
  var ckName = document.getElementsByName(ckType.name);

  for (var i = 0; i < ckName.length; i++) {
    if (!ckName[i].checked) {
      ckName[i].disabled = true;
    } else {
      if (ckName[i].checked) {
        ckName[i].disabled = false;
      }
    }
  }
}
<form>
 <input type="radio" name="No Past Conditions" id="rb0" onclick="ckChange(this)" />
   <label for="rb0">No Past Conditions </label>
          
 <input type="checkbox" name="No Past Conditions" id="cb1" value="Yes" onclick="ckChange(this)" />
   <label for="cb1">Heart disease </label>

<!-- WORKS GREAT IF NAME IS THE SAME, HOWEVER I WANT TO CHANGE IT IN ORDER FOR READABILITY WHEN I COLLECT THE FORM -->

<!-- this part here doesn't work, bcz the name attrib is different -->
  <input type="checkbox" name="Anemia or other blood disease" id="cb2" value="Yes" />
          <label for="cb2">Anemia or other blood disease</label>
  <input type="checkbox" name="Severe headaches" id="cb3" value="Yes" />
          <label for="cb3">Severe headaches</label>
</form>

Now I tried declaring a checkbox variable to be autoincremented, using the base id name(cb: checkbox) + j(concatenating it I guess?) but that's not the right syntax I think. Code:

var j;
var checkbox = document.getElementById(cb + j);
for (var j = 0; j < 20; j++)

Clearly I know it's wrong but I've searched for hours and I'm really upset. Can you guys help me?

Edit:@shingo.nakanishi answer generates this error @shingo.nakanishi answer generates this error




CheckBox size will decrease in split screen mode , but when I enter into normal mode , the size remains the same

I have a message application, in which the checkbox size will be normal and when I entered into split-screen the size will decrease, but when I re-entered into normal mode, some of the checkboxes are still in the same small sie while some are normally visible




vendredi 29 mai 2020

Google Sheets - Change row color once multiple boxes are checked

In Google Sheets, I would like each row to turn green, once two of the checkboxes (in Columns F and G) are checked for that row.

I have tried using conditional formatting with the following formulas applied to range A2:I145:

=IF($F2=TRUE,1)=AND($G2=TRUE,1)  /* This colors the row when cells are unchecked */

=IF($F2:$G2=TRUE) /* This does not color the row at all */

I know that if it was only based on one checkbox, it could be accomplished with =$F2=TRUE. There is documentation on this here, but they don't give an example with requirement of two checkboxes.

Is there a simple function that can perform this task?




Automatically tick checkbox when clicking on another form input field

I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

<input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.




Tkinter checkbox returns wrong value in Python

So im currently writing a program to Watch a folder and sort out all Files and their extensions to new folders with the extension names. Right now i am trying to implement a settings Part, where a new Window from Tkinter open and you can check if you want to start the programm with windows on startup or not.

but im not able to receive the right checkbox value, is always say FALSE even if i checked the checkbox.

The whole Code is:

from tkinter import filedialog
from tkinter import *
from tkinter import messagebox
from pystray import MenuItem as item
import os
# main_with_ini.py
import configparser
import pystray
from PIL import Image, ImageDraw
import Handler as h
import threading
import getpass

filename = ""
configfile_name = "config.ini"
icon_name = "icon.png"
fenster = Tk()
folder_path = StringVar()
USER_NAME = getpass.getuser()
CHECKBOX_STATE = 0


# print('sys.argv[0] =', sys.argv[0])
# pathname = os.path.dirname(sys.argv[0])
# print('path =', pathname)
# print('full path =', os.path.abspath(pathname))

def add_to_startup(file_path=""):
    if file_path == "":
        file_path = os.path.dirname(os.path.realpath(__file__))
    bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
    with open(bat_path + '\\' + "open.bat", "w+") as bat_file:
        bat_file.write(r'start "" %s' % file_path)

def createConfig(configfile_name, section, key, value):
    global filename
    config = os.path.join(os.path.dirname(sys.argv[0]), configfile_name)

    write_config = configparser.ConfigParser()
    write_config.add_section(section)
    write_config.set(section, key, value)
    cfgfile = open(config, 'w')
    write_config.write(cfgfile)
    cfgfile.close()

# Check if there is already a configurtion file
def checkConfig(configfile_name):
    config = os.path.join(os.path.dirname(sys.argv[0]), configfile_name)
    # Create the configuration file as it doesn't exist yet
    if os.path.isfile(configfile_name):
        read_config = configparser.ConfigParser()
        read_config.read(config)
        watchPath = read_config['Folder_WatchPath']['PATH']
        folder_path.set(watchPath)
        return watchPath


    else:
        print('no config file yet')


# Systemtray
def quit_window(icon, item, window):
    icon.stop()
    window.destroy()


def show_window(icon, item, window):
    icon.stop()
    window.after(0, window.deiconify)


def setup(icon):
    icon.visible = True


def withdraw_window(window):
    window.withdraw()
    image = Image.open(os.path.join(os.path.dirname(sys.argv[0]), icon_name))
    menu = pystray.Menu(item('Show', lambda: show_window(icon, menu, window)),
                        item('Quit', lambda: quit_window(icon, menu, window)))

    icon = pystray.Icon("name", image, "FolderWatcher", menu)
    icon.run(setup)


def settings():
    settings = Tk()
    settings.title("Settings")

    info_text = Label(settings, text="Script Starten bei Windows Startup")
    info_text.grid(row=0, column=0, pady=20)

    boolvar = BooleanVar()
    boolvar.set(False)

    Checkbutton(settings, text="Autostart", variable=boolvar, command=lambda: callBackFunc(boolvar)).grid(row=0,
                                                                                                          sticky=W)
    btn_save_set = Button(settings, text='Save', command=lambda: saveSettings(settings, CHECKBOX_STATE))
    btn_save_set.grid(row=2, column=0)
    settings.mainloop()


def callBackFunc(checkbox):
    print("Oh. I'm clicked")
    var = checkbox.get()
    print(var)


def getBool(boolvar):  # get rid of the event argument
    print(boolvar.get())


def getAutostart(button):
    global CHECKBOX_STATE
    if button.get():
        print("checked = " + str(CHECKBOX_STATE))
        CHECKBOX_STATE = 1

    else:
        print("notchecked = " + str(CHECKBOX_STATE))
        CHECKBOX_STATE = 0


def saveSettings(window, checkbox):
    messagebox.showinfo(message="Einstellungen wurde gespeichert", title="Save")
    if checkbox:
        temp = "TRUE"
        createConfig(configfile_name, "SETTINGS", "AUTOSTART", temp)

    else:
        temp = "FALSE"
        createConfig(configfile_name, "SETTINGS", "AUTOSTART", temp)
    window.destroy()


def background(func, args):
    th = threading.Thread(target=func, args=args)
    th.daemon = True
    th.start()


def changePath():
    # Allow user to select a directory and store it in global var
    # called folder_path
    global filename
    global folder_path
    filename = filedialog.askdirectory()
    folder_path.set(filename)
    if len(filename) > 0:
        h.watchDir(filename)


def savePATH():
    global filename
    if len(filename) > 0:
        createConfig(configfile_name, "Folder_WatchPath", "PATH", filename)
        messagebox.showinfo(message="Der Ordner wurde gespeichert", title="Info")
    else:
        messagebox.showinfo(message="Bitte einen Order zum Beobachten auswählen", title="Info")


def action_get_info_dialog():
    m_text = "\
************************\n\
Autor: Minh Tuan Vuong \n\
Date: 27.05.2020\n\
Version: 1.00\n\
Email: Minhtv@web.de\n\
************************"
    messagebox.showinfo(message=m_text, title="Infos")


def minimize_win(window):
    Wm.iconify(window)


def on_closing(window):
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        window.destroy()


def main():
    fenster.title("Folder Watcher")

    info_text = Label(fenster, text="Suche den Ordner aus, denn du beobachten möchtest!")
    info_text.grid(row=0, column=0, pady=20)

    # Menüleiste erstellen
    menuleiste = Menu(fenster)

    lbl1 = Label(master=fenster, textvariable=folder_path)
    lbl1.grid(row=1, column=0)
    button2 = Button(text='Durchsuche', command=lambda: background(changePath, ()))
    button2.grid(row=2, column=0, pady=20)

    # Menü Datei und Help erstellen
    datei_menu = Menu(menuleiste, tearoff=0)
    help_menu = Menu(menuleiste, tearoff=0)

    # Beim Klick auf Datei oder auf Help sollen nun weitere Einträge erscheinen.
    # Diese werden also zu "datei_menu" und "help_menu" hinzugefügt
    datei_menu.add_command(label="Speichern", command=savePATH)
    datei_menu.add_command(label="Minimiere", command=lambda: withdraw_window(fenster))
    datei_menu.add_separator()  # Fügt eine Trennlinie hinzu
    datei_menu.add_command(label="Einstellungen", command=settings)
    datei_menu.add_separator()  # Fügt eine Trennlinie hinzu
    datei_menu.add_command(label="Exit", command=fenster.quit)

    help_menu.add_command(label="Info!", command=action_get_info_dialog)

    # Nun fügen wir die Menüs (Datei und Help) der Menüleiste als
    # "Drop-Down-Menü" hinzu
    menuleiste.add_cascade(label="Datei", menu=datei_menu)
    menuleiste.add_cascade(label="Help", menu=help_menu)

    # Die Menüleiste mit den Menüeinrägen noch dem Fenster übergeben und fertig.
    fenster.config(menu=menuleiste)

    fenster.protocol('WM_DELETE_WINDOW', lambda: on_closing(fenster))

    fenster.mainloop()


if __name__ == '__main__':
    filename = checkConfig(configfile_name)
    if filename:
        print("Watched Folder is " + filename)
        background(lambda: h.watchDir(filename), ())
    else:
        print("No Watched Folder defined yet")
    main()

The Problems lays in this methods i guess:

    def settings():
        settings = Tk()
        settings.title("Settings")

        info_text = Label(settings, text="Script Starten bei Windows Startup")
        info_text.grid(row=0, column=0, pady=20)

        boolvar = BooleanVar()
        boolvar.set(False)

        Checkbutton(settings, text="Autostart", variable=boolvar, command=lambda: callBackFunc(boolvar)).grid(row=0,
                                                                                                              sticky=W)
        btn_save_set = Button(settings, text='Save', command=lambda: saveSettings(settings, CHECKBOX_STATE))
        btn_save_set.grid(row=2, column=0)
        settings.mainloop()


    def callBackFunc(checkbox):
        print("Oh. I'm clicked")
        var = checkbox.get()
        print(var)

def main():
    fenster.title("Folder Watcher")

    info_text = Label(fenster, text="Suche den Ordner aus, denn du beobachten möchtest!")
    info_text.grid(row=0, column=0, pady=20)

    # Menüleiste erstellen
    menuleiste = Menu(fenster)

    lbl1 = Label(master=fenster, textvariable=folder_path)
    lbl1.grid(row=1, column=0)
    button2 = Button(text='Durchsuche', command=lambda: background(changePath, ()))
    button2.grid(row=2, column=0, pady=20)

    # Menü Datei und Help erstellen
    datei_menu = Menu(menuleiste, tearoff=0)
    help_menu = Menu(menuleiste, tearoff=0)

    # Beim Klick auf Datei oder auf Help sollen nun weitere Einträge erscheinen.
    # Diese werden also zu "datei_menu" und "help_menu" hinzugefügt
    datei_menu.add_command(label="Speichern", command=savePATH)
    datei_menu.add_command(label="Minimiere", command=lambda: withdraw_window(fenster))
    datei_menu.add_separator()  # Fügt eine Trennlinie hinzu
    datei_menu.add_command(label="Einstellungen", command=settings)
    datei_menu.add_separator()  # Fügt eine Trennlinie hinzu
    datei_menu.add_command(label="Exit", command=fenster.quit)

    help_menu.add_command(label="Info!", command=action_get_info_dialog)

    # Nun fügen wir die Menüs (Datei und Help) der Menüleiste als
    # "Drop-Down-Menü" hinzu
    menuleiste.add_cascade(label="Datei", menu=datei_menu)
    menuleiste.add_cascade(label="Help", menu=help_menu)

    # Die Menüleiste mit den Menüeinrägen noch dem Fenster übergeben und fertig.
    fenster.config(menu=menuleiste)

    fenster.protocol('WM_DELETE_WINDOW', lambda: on_closing(fenster))

    fenster.mainloop()


if __name__ == '__main__':
    filename = checkConfig(configfile_name)
    if filename:
        print("Watched Folder is " + filename)
        background(lambda: h.watchDir(filename), ())
    else:
        print("No Watched Folder defined yet")
    main()

If i encapsulate only the code for the checkbox windows without the main windows, the checkbox code is working.

from tkinter import *


def settings():
    settings = Tk()
    settings.title("Settings")

    info_text = Label(settings, text="Script Starten bei Windows Startup")
    info_text.grid(row=0, column=0, pady=20)

    boolvar = BooleanVar()
    boolvar.set(False)
    Checkbutton(settings, text="Autostart", variable=boolvar, command = lambda : callBackFunc(boolvar)).grid(row=0, sticky=W)
    btn_save_set = Button(settings, text='Save', command=lambda: saveSettings(settings, CHECKBOX_STATE))
    btn_save_set.grid(row=2, column=0)
    mainloop()

def callBackFunc(checkbox):
        print("Oh. I'm clicked")
        var = checkbox.get()
        print(var)

if __name__ == '__main__':
    settings()

But in the main program, it will not return the right value, only False




get fatal error of null pointer exception

getting error while doing multiplechecklist dialogue

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:457) at android.widget.ArrayAdapter.getView(ArrayAdapter.java:419) at androidx.appcompat.app.AlertController$AlertParams$1.getView(AlertController.java:998) at android.widget.AbsListView.obtainView(AbsListView.java:2472) at android.widget.ListView.measureHeightOfChildren(ListView.java:1421) at android.widget.ListView.onMeasure(ListView.java:1327) at android.view.View.measure(View.java:24710) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:24710) at androidx.appcompat.widget.AlertDialogLayout.tryOnMeasure(AlertDialogLayout.java:134) at androidx.appcompat.widget.AlertDialogLayout.onMeasure(AlertDialogLayout.java:64) at android.view.View.measure(View.java:24710) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143) at android.view.View.measure(View.java:24710) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:24710) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:24710) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552) at android.widget.LinearLayout.measureVertical(LinearLayout.java:842) at android.widget.LinearLayout.onMeasure(Li

try { mBuilder.setTitle("Select SubCategories"); mBuilder.setMultiChoiceItems(id, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {

                if (isChecked) {
                    if (!mUserItems.contains(id[position])) {
                        mUserItems.add(id[position]);
                    } else {
                        mUserItems.remove(id[position]);
                    }
                }
            }
        });

        mBuilder.setCancelable(false);
        mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                String item = "";
                for (int i = 0; i < mUserItems.size(); i++) {
                    item = item + mUserItems.get(i);
                    if (i != mUserItems.size() - 1) {
                        item = item + ",";
                    }
                    //   displaysub.append(item[i]);
                }
                displaysub.setText(item);

            }
        });

        mBuilder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        mBuilder.setNeutralButton("Clear All", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                for (int i = 0; i < checkedItems.length; i++) {
                   // checkedItems[i] = false;
                    mUserItems.clear();
                    //   mItemSelected.setText("");
                    displaysub.setText("");
                }
            }
        });

        AlertDialog mDialog = mBuilder.create();
        mDialog.show();
    }catch (Exception ex){
        ex.printStackTrace();
    }



How to get old and new value of dynamically generated checkbox column in agGrid

I am using agGrid where the columns are dynamically created. My objective is to get the old value and new value after checking the checkboxes. I try to use "onCellValueChanged" but it didnt work. If I use "onCellClicked" then I am not getting Old Value and New Value.

For your understanding I want to mean by Old Value and New Value that if user checked then Old Value is false and New Value is true.

HTML

<ag-grid-angular class="ag-theme-balham" [gridOptions]="siteJobDeptGridOptions"
            [rowData]="siteJobDeptRowData" [columnDefs]="siteJobDeptColDef" [paginationPageSize]=10 [domLayout]="domLayout"
            (gridReady)="onGridReady($event)">
        </ag-grid-angular>

TS File

export class SiteJobDeptConfigComponent implements OnInit {
ngOnInit() {
    this.domLayout = "autoHeight";                      
    this.getAllSiteJobConfig();      
    this.generateColumns();     
}

onGridReady(params: any) {            
    params.api.sizeColumnsToFit();
    params.api.resetRowHeights();                                        
}

generateColumns()
{
    let deptColDef = []; 

    let colSiteJob =  { 
            field: 'SiteJobName', headerName: 'Site Job Name',resizable: true,
            sortable: true, filter: true, editable: false, 
    }

    this.siteJobDeptCommonService.getEntityData('getpublisheddepts')
        .subscribe((rowData) => {  
            deptColDef.push(colSiteJob);                              
            for(let dept of rowData)
            {                                    
                deptColDef.push({ 
                    field: dept.DeptName, headerName: dept.DeptName, width:100,resizable: true,
                    cellClass: 'no-border',                                        
                    cellRenderer : params => {                        
                        var input = document.createElement('input');
                        input.type="checkbox";                        
                        input.checked=params.data[dept.DeptName];                       
                        return input;
                    },                    
                    onCellValueChanged: this.siteDeptCellValueChanged.bind(this),

                })
            }                            
        this.siteJobDeptColDef = deptColDef;              
    },
    (error) => { alert(error) });         
}

siteDeptCellValueChanged(dataCol: any) {    
    let checkedOldValue = "Old Check Value - " + dataCol.oldValue;   
    let checkedNewValue = "New Check Value - " + dataCol.newValue;                        
}

getAllSiteJobConfig()
{        
    let siteJobRowData = [];
    this.siteJobDeptCommonService.getEntityData('getallsitedeptjob')
        .subscribe((rowData) => {            
            for(let siteJobDetail of rowData)
            {               
                for(let deptAllow of siteJobDetail.DeptAllow)
                {
                    tempArray[deptAllow["DeptName"]] = deptAllow["IsAllow"];
                }

                siteJobRowData.push(tempArray); 
            }
            this.siteJobDeptRowData = siteJobRowData;
        },
        (error) => { alert(error) }); 
    }    
}

The grid looks like below:-

enter image description here

Can you please help me how to get Old Data and New Data value from checkbox that is dynamically generated?




jeudi 28 mai 2020

Keep check box checked after refreshing the page

I have checkboxes as below in my rails app

<% if field["field_type"] == "checklist"%>
 <% templat = @custom_templates.select{|s| s["id"] == m["startup_field_template_id"]}.first%>
 <small>
   <% vals = field["options"].to_s.gsub(/[\[\"\]]/, '').split(',') %>
   <% vals.each do |v| %>
   <% if templat["option_multi"]%>
     <input type="checkbox" />&nbsp;&nbsp;&nbsp; <%= v %><br/>
   <% else %>
     <input type="checkbox" class="check" />&nbsp;&nbsp;&nbsp; <%= v %><br/>
   <% end %>
   <% end %>
 </small>
<% else %>
 n/a
<% end %>

I used below code to keep checked checkbox 'checked' after refreshing the page

<sript>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>

But it keep all check boxes checked after refreshing the page. how can I solve this?




add and get selected checkbox in modal

Hi everyone I'm working with Angular, and Bootstrap 4.

1.- I have the following modal and I would like to add the information dynamically, add some already selected checkboxes and others not, depending on the configuration, for now I am filling it with an array of objects, but I would like to know what I would have to do to fill it with some selected check and others not.

Modal

2.- In the Modal I can select or deselect the checkboxes and when I give Save changes I get the id of the checkboxes that were modified, both selected and deselected.

My ckecbox already have a value to identify them, I just don't know how to get all the modified checks

Value of checkbox

I share the project to support me to guide me how I could solve these problems that I have:

https://codesandbox.io/checkbox

Thank you for your support.




Click on spam with python selenium

I want to click on the checkbox from the Google ReCAPTCHA-test. For that (I think) I have to Click on the Following span:

<span class="recaptcha-checkbox goog-inline-block recaptcha-checkbox-unchecked rc-anchor-checkbox" role="checkbox" aria-checked="false" id="recaptcha-anchor" tabindex="0" dir="ltr" aria-labelledby="recaptcha-anchor-label"><div class="recaptcha-checkbox-border" role="presentation"></div><div class="recaptcha-checkbox-borderAnimation" role="presentation"></div><div class="recaptcha-checkbox-spinner" role="presentation"><div class="recaptcha-checkbox-spinner-overlay"></div></div><div class="recaptcha-checkbox-checkmark" role="presentation"></div></span>

https://patrickhlauke.github.io/recaptcha/ Here the Website is (it's just an empty website with an ReCAPTCHA in it)

I am using the latest version of the Chrome driver and it's defined as driver. I tried:

driver.find_element_by_tag_name("span").click()

driver.find_element_by_xpath('//*[@id="recaptcha-anchor"]').click()

driver.find_element_by_id('recaptcha-anchor').click()

driver.find_element_by_class_name('recaptcha-checkbox goog-inline-block recaptcha-checkbox-unchecked rc-anchor-checkbox').click()

but i'm always getting following error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {*this is every try different*}
  (Session info: chrome=83.0.4103.61)

I hope someone can help me clicking on this span, course I'm very new at Python and Its my first try with Selenium :)




Select Checkbox Selenium Python

I really need help to solve this.

I'm trying create a Checkout script, and for this I need to select "Accept the Exchange and Cancellation Policy"

Here is the image:enter image description here

And my code:

def abrir_termos(driver):
    sleep(4)
    LOGGER.info("Abrindo e acitando termos")
    driver.getElement(By.id("politica-trocas")).click()



Como fazer somente um CheckBoxListTile ser selecionado

Eu estou tendo problema no CheckBoxListTile, ele está sendo construido pelo ListView.builder e eu estou conseguindo selecionar mais de um campo, tive a ideia de tentar mapear meus campos com o valor "false", e se caso algum fosse selecionado o value mudaria para "true", contudo não consigo passar disso. O meu objetivo é q somente um elemento do Mapa pode ser "true", ou seja, só pode ter um CheckBox selecionado por vez, caso um esteja selecionado, e o usuário clicar em outro, o primeiro desmarcará e o último será marcado.

Código:

  Map<String, bool> _currencies = {
    "one": false,
    "two": false,
    "three": false,
    "one2": false,
    "two2": false,
    "three2": false,
    "one3": false,
    "two3": false,
    "three3": false,
    "one4": false,
    "two4": false,
    "three4": false,
    "one5": false,
    "two5": false,
    "three5": false,
  };

  ....
  body: ListView.builder(
          itemCount: _currencies.length,
          itemBuilder: (BuildContext context, int index) {
            return Material(
              child: ListTile(
                leading: _currencies.values.elementAt(index) == false
                    ? Icon(null)
                    : Icon(Icons.check),
                title: Text(_currencies.keys.elementAt(index)),
                onTap: () {
                  setState(
                    () {
                     _currencies[_currencies.keys.elementAt(index)] =
                     !_currencies[_currencies.keys.elementAt(index)];                    
                   },
                  );
                },
              ),
            );
          },
        ),

Exemplo




checkbox hack inside ngfor

i am using angular 9 and i am doing an checkbox hack that is checked as image, and its work, but my checkbox hack is inside an ngFor and te class is based on the id and its fixed on HTML:

 <ul *ngFor="let acquirer of getAcquirersValues()">
    <li>
       <input type="checkbox" id="myCheckbox1" />
       <label for="myCheckbox1">
       <img src="assets/taxes/brands/.png" /></label>
     </li>
 </ul>

and in my css checkbox:

ul {
    list-style-type: none;
  }

  li {
    display: inline-block;
  }

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

  label {
    border: 1px solid #e5e5e5;
    padding: 10px;
    display: block;
    position: relative;
    margin: 10px;
    border-radius: 5px;
    cursor: pointer;
  }

  label:before {
    background-color: white;
    color: white;
    content: " ";
    display: block;
    border-radius: 50%;
    border: 1px solid grey;
    position: absolute;
    top: -10px;
    left: -13px;
    width: 25px;
    height: 25px;
    text-align: center;
    line-height: 28px;
    transition-duration: 0.4s;
    transform: scale(0);
  }

  label img {
      width: 64px;
    height: 28px;
    transition-duration: 0.2s;
    transform-origin: 50% 50%;
  }

  :checked + label {
    border-color: #ddd;
  }

  :checked + label:before {
    content: "✓";
    background-color: grey;
    transform: scale(1);
  }

  :checked + label img {
    transform: scale(0.9);
    /* box-shadow: 0 0 5px #333; */
    z-index: -1;
  }

That ngFor returns me various items that i render on the image, but, i dont want to create various and various classes to relate it to the id... i think i can do a thing like

<input type="checkbox" id="myCheckBox>

but if i do that i have to create various equal classes on css... anyone know how can i turn it dinamic without write equal classes on css? (because of that, only the first item is checked ever(same id))

thanks




Active checkbox changes table background color except for a cell

When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red. That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}
<!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html>

Thanks already for the help.




How to identify large checkmarks that overlap the checkbox using openCV / deep learning?

I am trying to detect checkboxes using OpenCV. I am able to detect the cases where the boxes are empty (not tick-marked) as well as the checkboxes having checkmarks neatly inscribed inside them.

But whenever there is an image of the type aside enter image description here

where the checkmark cross signs are huge and overlap the boxes, I am not able to detect the checkboxes and checkmarks.

Can someone kindly suggest a work around for this using OpenCV or any deep learning model ?




Handle indeterminate checkbox in react

So I've tried to build a simple react toggle which is based on a checkbox. I want the toggle to have three states: neutral, on, and off which are determined by a prop I pass to the component.

So far, I have the component rendering ok, but I can't get it to reflect the changes in whether it's indeterminate, on, or off. It just stays frozen in the 'off' position.

I suspect this is a combination of my CSS and potentially how I'm call the ref in my code.

Here's the code: https://codesandbox.io/s/objective-wozniak-z0tes?file=/src/index.js

Any advice appreciated!




Jtable Header change value

I have a table with checkbox headers in the form of (checkbox + string). The table components is also made of checkboxes. I have an table listener and works fine, but i want when i click on a specific checkbox from a cell, to tick a checkbox from the header in same column. I tried with setvalue but it isnt working. Thanks!




How to make multiple columns of checkboxes with Rails 6, collection_check_boxes and Bootstrap 4?

I'm trying to display a (really) long list of checkboxes in a series of columns instead.

In my form, I'm using

<%= f.collection_check_boxes(:building_ids, Building.all, :id, :option) %>

I tried this solution, but it wasn't responsive and the boxes in the right-hand column were spaced out weird (justified top to bottom).

This Reddit was promising, but unfortunately the OP didn't post his final/working code.

I'm pretty sure I have to add some custom CSS and then wrap the f.collection_check_boxes with it, but I'm not sure how to go about that. Some solutions have done this with a few divs and then styled them with a few custom CSS classes.

Oh, and I'm using the bootstrap_form gem to apply Bootstrap to form elements, but I could probably find a way to apply a more generic Bootstrap solution.




Jquery Checkbox not changing

the issues is that if you check and then uncheck the vacancy_select checkbox, then check the selection checkbox it doesn't change the vacancy_select check status

I have a few checkboxes on screen, the first checkbox $("input[type=checkbox]#selection") will toggle all other checkboxes, on or off depending on the status of the first checkbox.

$('input[type=checkbox]#selection').on('change', function () {
    let rows = $("tr.content_list > td > input[type=checkbox].vacancy_select");
    for(let i=0; i < rows.length; i++){
        $(rows[i]).attr('checked', this.checked);
    }
});

if, I select or change the status of any of the other checkboxes then these checkboxes

$("tr.content_list > td > input[type=checkbox].vacancy_select") don't updated when marking this $("input[type=checkbox]#selection") checkbox as checked.

checkboxes

$('input[type=checkbox]#selection').on('change', function() {
  let rows = $("input[type=checkbox].vacancy_select");
  for (let i = 0; i < rows.length; i++) {
    $(rows[i]).attr('checked', this.checked);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table  id="list_table" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>
                <input type="checkbox" id="selection" name="selection">Selection
            </th>
        </tr>
        <tr>
            <td class="na">
                <a class="btn btn-primary" href="" style="color: #FFF">New Vacancy</a>
            </td>
        </tr>
    </thead>
    <tr class="content_list">
        <td>
            <input type="checkbox" class="vacancy_select" data-vacancy-id="">
       </td>
    </tr>a
    <tr class="content_list">
        <td>
            <input type="checkbox" class="vacancy_select" data-vacancy-id="">
       </td>
    </tr>a
    <tr class="content_list">
        <td>
            <input type="checkbox" class="vacancy_select" data-vacancy-id="">
       </td>
    </tr>
</table>



mercredi 27 mai 2020

Chrome 83: Change colors of new form styling

With the new Chrome update Chrome is displaying improved default form styling. According to the post I would say it should be possible to change this form theme to match the color set of a website.

We were going for beautiful, webby, and neutral. We hope that every design system would see a bit of themselves in the new designs and easily imagine how they might be adapted for their own branding.

I have spend the last few hours searching and trying to get rid of the default blue color that has a very bad contrast with rest of my website. Aside from using '-webkit-appearance: none;' and restyling things like checkboxes myself I'm not sure if it's possible.

Does anyone experience this issue as well or have a solution or documentation I'm missing?




Checkbox doesn't respond to onChange when checked is driven by state

I have a material-ui Table and have been implementing multi-select functionality on it.

My multi select should behave as follows :

  • Select checkboxes only appear at the start of a row on hover (when nothing has been selected)
  • Once one row has been selected, all other checkboxes become permanently visible.
  • The checkbox in the TableHead will select / deselect all rows in the Table when toggled.

Each row has its own individual unique id.

I maintain a Set called idsOfSelectedRows via a useState hook to keep track of all rows currently selected.

Each TableRow has a Checkbox which looks like this

<Checkbox
  className={
     idsOfSelectedRows.size === 0 &&
     styles.rowSelectionCheckboxStyle
  }
  onChange={() => handleRowSelectionCheckboxClick}
  checked={idsOfSelectedRows.has(row.id)}
 />

and handleRowSelectionCheckboxClick looks like this

  const handleRowSelectionCheckboxClick = event => {
    const idOfClickedRow = event.target.attributes.getNamedItem("id").value;
   //If the checkbox has just become checked then add it to the idOfSelectedRows Set, otherwise remove it.
    setIdsOfSelectedRows(
      event.target.checked
        ? new Set(idsOfSelectedRows.add(String(idOfClickedRow)))
        : () => {
            idsOfSelectedRows.delete(String(idOfClickedRow));
            return new Set(idsOfSelectedRows);
          }
    );
  };

My issue is that clicking on the checkboxes on the rows is unresponsive. I can select them all by clicking on the select all Checkbox in the TableHead but clicking on checkboxes in individual rows does not change their state ?

Here's a full CodeSandbox reproducing the exact issue. What do I need to do to make the checkboxes in the rows be toggleable ?

Edit hover-table-row-checkbox




change style of other labels when checkbox is checked

I have an issue with the checkbox checked. I am trying to find a solution that is when my current checkbox is checked to change the opacity others checkbox. is that possible with CSS? I made it with CSS input and label. Here is my code.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  margin-bottom: 10px;
  display: block;
}

.styled-checkbox {
  position: absolute;
  opacity: 0;
}
.styled-checkbox:checked + label {
  opacity: 1;
}
.styled-checkbox:checked + label label {
  opacity: 0.5;
}
.styled-checkbox + label {
  position: relative;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  font-size: 0.875rem;
}
.styled-checkbox + label:before {
  content: '';
  margin-right: 10px;
  display: inline-block;
  width: 14px;
  height: 14px;
  vertical-align: text-top;
  border: 1px solid #000;
}
.styled-checkbox:checked + label:after {
  content: '';
  position: absolute;
  left: 1px;
  top: 7px;
  background: white;
  width: 2px;
  height: 2px;
  box-shadow: 2px 0 0 #000, 4px 0 0 #000, 4px -2px 0 #000, 4px -4px 0 #000, 4px -6px 0 #000, 4px -8px 0 #000;
  transform: rotate(45deg);
  transition: all 0.3s ease-out;
}
<ul>
  <li>
    <input type="checkbox" class="styled-checkbox" id="styled-checkbox-1" />
    <label for="styled-checkbox-1">Test one</label>
  </li>
  <li>
    <input type="checkbox" class="styled-checkbox" id="styled-checkbox-2" />
    <label for="styled-checkbox-2">Test Two</label>
  </li>
  <li>
    <input type="checkbox" class="styled-checkbox" id="styled-checkbox-3" />
    <label for="styled-checkbox-3">Test Three</label>
  </li>
  <li>
    <input type="checkbox" class="styled-checkbox" id="styled-checkbox-4" />
    <label for="styled-checkbox-4">Test Four</label>
  </li>
</ul>

`

desire goal is something like that

enter image description here

I hope you guys understand the problem. Thanks in advance




Run two checkboxes when both are selected in php

I have a form that has two checkboxes.

<form action="test.php" method="post">
    <input type="checkbox" name="check1" value="check1">
    <label for="check1">Checkbox 1</label><br>

    <input type="checkbox" name="check2" value="check2">
    <label for="check2">Checkbox 2</label><br>
</form>

When the checkbox 1 is selected, its value is displayed on the test.php page, and when the second checkbox is selected, another value is displayed.

<?php

if (@$_POST['check1']) {
    echo "oh you clicked on Checkbox 1";

} elseif (@$_POST['check2']) {
    echo "oh you clicked on Checkbox 2";    
}
?>

In this method, which uses if statements, the program works. But when both checkboxes are selected, the value of both is expected to be displayed, which is impossible with if statements.

I want an algorithm or code that shows the values of their pair if both of them are selected.




Best way to insert large form/checkboxes into sql table

Im looking for advice/best practice around inserting large records into a sql database(approx 250 columns). I currently dont have much in the way of code as Im reluctant to get building this when im still unsure of the best approach. Ive searched the web and found database tips but none seem to cover the types of records that i am looking to submit - mainly small records like order details.

Problem- I have an form that managers can use to complete reviews on their staff. Along with a few generic bits of into, the form has a 12 radio buttons where the manager rates a staff member. This is then submitted into a sql database via php. In the database I have 1 record for each review (therefore staff can have multiple reviews for them over a period of time). The company has decided to expand the review form, adding extra radiobutton questions but also a large number of checkboxes to get further insight if a staff member is scored down. In some cases there is up to 20 checkboxes for a question.

The results from the reviews will be pulled into overall table/page which will focus on number of records and results from the radiobuttons. However i'll also need to know checkbox results as well - for example the page would highlight that "Question X" has an average rating of 65% across all staff and the top reason for this being pulled down is "checkbox C". Staff members will also be able to view completed reviews.

My solution - The only real thing i can think to do is create a new sql table which includes a column for every checkbox option. This is ramping up the number of columns in the database to around 250. Everything I read about sql tables tells me that a table this size isn't a great idea but im not sure what my options are. Depending on how a review is completed around 70% of the columns for a given record could have a null value. Another option would be to create a second table that holds the checkbox details separately and then have a 1-1 relationship between the 2, but i not sure why / if that would improve the efficiency, especially as i might need to pulls both lots of data at the same time when producing results.

I feel im being vague so let me know if any other info is required however as explained im very much trying to work out the best way forward before i start coding. It may be that have a table with 250+ columns is the only solution so any tips/resources on making sure this is as efficient as possible would be a great help.




mardi 26 mai 2020

Enable Button If all the checkboxes are ticked - VBA

I have a vba code that has been assigned to a button named as "run report". Have some instructions with check boxes and what I am trying to do is to enable button only if all the checkboxes are ticked. I tried something like below but somehow it's not working. It seems something is wrong with declaration. I am using ms office 2013 version.

Sub buttonenable()
Dim B1 as Button
Dim C1 as Checkbox
Dim C2 as Checkbox
Dim C3 as Checkbox
Set B1 = Thisworkbook.Sheets("Home").Button("Run report")
Set C1 = Thisworkbook.Sheets("Home").Checkbox("Checkbox1")

Set C2 = Thisworkbook.Sheets("Home").Checkbox("Checkbox2")

Set C3 = Thisworkbook.Sheets("Home").Checkbox("Checkbox3")

IF C1 = True and C2 = True and C3 = True Then
B1.Enable = True

Else
B1.enable = False

End If

End Sub()



Change a value on another worksheet based on a checkbox check

After some searching and trying to figure it out my self i'm stumped. I could use some help on this one.

I have an excel workbook that has multiple tabs. The two I need help with is the "KronosEntries" and the "MASTER" tab. The MASTER tab has a list of all the missed days and vacation time for the employee. The KronosEntries tab has a list of all the records from the MASTER tab that need to be entered into Kronos. Once they are entered into Kronos I will check the box next to that line to remove it from the KronosEntries tab. When I add a new line on the MASTER tab it automatically adds a "No" in column R. What I want to happen is when I check the checkbox on the KronosEntries tab I want to change column R on the MASTER tab to "Yes" for the row that has the same data.

Here's the KronosEntries tab example.

KronosEntries

Here's the MASTER tab example.

MasterTab

Here's what I used to add the checkboxes.

Sub Addcheckboxes()

'Declare variables and data types
Dim cell, LRow As Single
Dim ChkBx As CheckBox
Dim CLeft, CTop, CHeight, CWidth As Double

'Don't refresh or update screen while processing macro, this will make the macro quicker.
Application.ScreenUpdating = False

'Find last non empty cell in column A
LRow = Worksheets("KronosEntries").Range("A" & Rows.Count).End(xlUp).Row

'Iterate through 2 to last non empty cell
For cell = 2 To LRow

    'Check if cell in column B is not equal to nothing
    If Cells(cell, "B").value <> "" And Cells(cell, "B").value <> "Employee ID" Then

        'Save cell dimensions and coordinates of corresponding cell in column E to variables
        CLeft = Cells(cell, "A").Left
        CTop = Cells(cell, "A").Top
        CHeight = Cells(cell, "A").Height
        CWidth = Cells(cell, "A").Width

        'Create checkbox based on dimension and coordinates data from variables
        Worksheets("KronosEntries").CheckBoxes.Add(CLeft, CTop, CWidth, CHeight).Select

        With Selection
            .Caption = ""
            .value = xlOff
            .LinkedCell = .TopLeftCell.Offset(0, 8).Address
            .Display3DShading = False
        End With

    End If

    Next cell

    Worksheets("KronosEntries").Range("A6").Select

    'Turn on screen refresh
    Application.ScreenUpdating = True

End Sub

Here's what I used to remove the checkboxes.

Sub RemoveCheckboxes()

    'Declare variables and data types
    Dim ChkBx As CheckBox

    'Iterate through all check boxes on active sheet
    For Each ChkBx In Worksheets("KronosEntries").CheckBoxes

        'Remove checkbox
        ChkBx.Delete

    'Continue with next checkbox
    Next

End Sub

The part I cant seem to sort out is the code to change column R to Yes for the row that has the same data. Can someone help? Thank you

Sub ChangeData
    ?
End Sub



xmlHttpRequest is blocking other functions

I am using Js xmlHttpRequest to display the same menu on different pages of my site. Lately I found out that some functions are not executed when the site is online, like a quiz I made.

I had also tried to use fetch, or put the scripts in different files, but the same thing kept happening.

(The quiz does work when checking locally, where the xml request cannot be satisfied.)

//load the menu
onload = function loadXMLDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementsByTagName('body')[0].innerHTML +=
        this.responseText;
      }
    };
    xhttp.open("GET", "mnu", true);
    xhttp.send();
  }
  
  //check the quiz
  const checkBtn = document.getElementById('checkBtn')
checkBtn.onclick = function quizCheck() {
    //right answers
    var score = 0;
    if (q1a1.checked) {
        score = score + 1;
    }
    if (q2a1.checked) {
        score = score + 1;
    }
    alert("your score: " + score);
}
<li>
    Check the right answer:
        <br>
    <input type="checkbox" id="q1a1">Right
        <br>
    <input type="checkbox">Wrong
</li>

<li>
    Check the right answer:
        <br>
    <input type="checkbox" id="q2a1">Right
        <br>
    <input type="checkbox">Wrong
</li>

<button id="checkBtn">Check</button>

Anybody knows why and/or has some solutions?




Assign a Value when two checkboxes are checked

I am trying to come up with a JS for a memory test. In a series of 6 tries, Once the tester selects two consecutive checkboxes, I want to assign a Value of "1" to a specific field.

To simplify: if checkbox1 && checkbox2 are checked, then assign value of 1 if checkbox2 && checkbox3 are checked, then assign value of 1 just to checkbox2 and checkbox3

Any help will be greatly appreciated.




How can I align the checkboxes and text vertically?

I want the checkboxes to be parallel to each other and the text to be aligned the same. This is what i have (i'm new to this): `

<input type="checkbox"
          name=”liste1”
          value="1">This is Example1<br>
        <input type="checkbox"
          name=”liste1”
          value="2">Example2<br>
        <input type="checkbox"
          name=”liste1”
          value="3">Example123456<br>
        <input type="checkbox"
          name=”liste1”`enter code here`
          value="4">Option4<br>`

This is how it looks like




In Vuetify, how to prevent a checked v-checkbox from being deselected?

I have a checkbox:

<v-checkbox
     v-for="company in allCompanies" :key="`company_${company.id}`"
     :label="company.name"
     :value="company.id"
     v-model="selectedCompanies"
/>

How could I prevent a selected box from being deselected without having to resort to using radio buttons?

Or how to, using Javascript, check whether a specific checkbox has been deselected?




I want to set checkbox to true based on a condition in ag-grid

I have a button which basically imports some data. This imported data needs to be compared with the data inside already loaded ag-grid and if there is a match, set the cehckbox of that particlar row node to true.

This is the button which checks for the condition:

    enableCheck() {
    alert('works');
    if (this.DataService.isNotBlank(this.rowDataImport)) {
        for (let i = 0; i < this.rowDataImport.length; i++) {
            if (this.DataService.isNotBlank(this.rowData)) { 
                for (let j = 0; j < this.rowData.length; j++) { 
                    if (this.DataService.isNotBlank(this.rowData[j].calDate)) {
                        for (const calDates of this.rowData[j].calDate) {
                            if (
                            this.rowDataImport[i].isin === calDates.isin ||
                            this.rowDataImport[i].portfolioName === calDates.portfolioName ||
                            this.rowDataImport[i].valuationDate === calDates.valuationDate
                                ) 
                                {
                                     // alert('true')
                                    this.checkValue = true;
                                } else {
                                    this.checkValue = false;                                        
                                }
                        }
                    }
                }
            }
        }
      }

}

The this.checkValue is a flag which will be true if match is found.

  public gridColumnDefs = [
        {
            headerName: 'Portfolio Name',
            field: 'portfolioName',
            cellRenderer: 'agGroupCellRenderer',
            headerCheckboxSelection: true,
            headerCheckboxSelectionFilteredOnly: true,
            checkboxSelection: true,
            pinned: 'left',
            filter: true,
            cellRendererParams:(params) => {
                console.log(params);
                if (this.checkValue) {
                 params.node.selected = true;
                }
            }
        },
]

here I used cellRendererParams. But this will only for on load I guess. What to do if I want to update the ag-grid row from a value outside i.e. from import check as given above?




lundi 25 mai 2020

I want to lock/protect certain range of cells in a row if a checkbox in that row is ticked

I have a google sheet --> LINK ( https://docs.google.com/spreadsheets/d/10T_bctLC_QjYEbQlSt_M9RsaWigaT0WqM5hDUCr3BHg/edit?usp=sharing ) I have 2 tabs named Sheet1 and Sheet2. In Sheet1 the users enter their details and put tick mark in column F. Once the user ticks, i want that row including that checkbox to be un-editable by the user but me (owner) can still edit it. Similarly in Sheet2 also i need the same functionality when tick is made. I also require a timestamp when tick mark is made. I tried using data validation (custom formula is =$F2=FALSE) to lock cells but the drop down list just disapperaed . I also used a script along with this called 'WriteOnceReadMany' to track on column F and lock it once it is ticked. If i used only the script then the cells are locking immediately even before the tick mark. So in what way can i accomplish this either with formula or script.

Please help me accomplish in locking that particular row when check box in column F of that row is ticked in sheet1. and in sheet2 it should be locked when student tick it. Do suggest me, thank you. View question




Show last checked + two more (from array)

I have questionnaire of 20 checkboxes pulled from a JSON file into an array.

When an item is checked I push the question value to an array [1,3] that also stores in a cookie – so when the user returns, questions 1 + 3 remain checked.

var questions = ["1", "2", "3" ... "20"];

jQuery(this).change(function() {
    var question_value = jQuery(this).val();

    if (jQuery(this).is(':checked')) {
        Cookies.set('completed', questions_completed);
        questions_completed.push(question_value);
    } else {
        // splice/remove the item from the array    
    }
});

var questions_completed = [1, 3]; // stores checked/completed questions number

What I want to do is show 3 checkboxes at a time (not all 20).

The last question appears at the top (checked) and then two more from the list (not checked) until all questions are completed.

I can't figure out how to approach this correctly – I need to compare the completed array with the questions array, but I can't seem to do this within creating multiple loops within loops.




dimanche 24 mai 2020

My submenus didn't place themselves as I want + can't close them with a checkbox

I'm new to coding, learning back-end actually, but want to make something beautiful nonetheless. (And sorry for any english mistakes)

Anyway, I make this : https://codepen.io/morgane-demesmaeker/pen/QWjPLRx

HTML :

<header>
<nav>
    <a href="#" class="logo"><i class="fas fa-globe-asia fa-2x"></i><span>Title<br>Title</span></a>
    <input class="menu-btn" type="checkbox" id="menu-btn" />
    <label class="menu-icon" for="menu-btn"><span class="navicon"></span></label>
    <ul class="menu">
        <li><a href="index.php"><i class="fas fa-home mr-2"></i> Accueil</a></li>
        <li class="nav-expand"><a href="#" class="nav-link"><span><i class="fas fa-chalkboard-teacher mr-2"></i> Click here for submenu  </span></a>
            <ul class="nav-expand-content">
                <li><a href="">1</a></li>
                <li class="nav-expand"><a href="#" class="nav-link">2</a>
                    <ul class="nav-expand-content">
                        <li><a href="#">2.1</a></li>
                        <li><a href="#">2.2</a></li>
                    </ul>
                </li>
                <li class="nav-expand"><a href="#" class="nav-link">3</a>
                    <ul class="nav-expand-content">
                        <li><a href="#">3.1</a></li>
                        <li><a href="#">3.2</a></li>
                    </ul>
                </li>
                <li class="nav-expand"><a href="#" class="nav-link">4 : click here for another submenu</a>
                    <ul class="nav-expand-content">
                        <li><a href="#">4.1</a></li>
                        <li class="nav-expand"><a href="#" class="nav-link">Test lvl 3</a>
                            <ul class="nav-expand-content">
                            <li class="nav-expand"><a href="#" class="nav-link">Test lvl 4</a>
                                <ul class="nav-expand-content">
                                <li class="nav-expand"><a href="#">Test lvl 5</a></li>
                                </ul>
                            </li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">5</a></li>
                <li><a href="#">6</a></li>
                <li><a href="#">7</a></li>
                <li><a href="#">8</a></li>
            </ul>
        </li>   
    </ul>
</nav>

CSS :

    /* ---------------------------------------------------------------- 
                                ALL
---------------------------------------------------------------- */


*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}



/* ---------------------------------------------------------------- 
                                HEADER
---------------------------------------------------------------- */

header {
    background-color: rgb(235, 235, 235);
    box-shadow: 1px 1px 4px 0 rgba(0,0,0,.5), inset 0px 5px #C44816;
    padding-top: 5px;
    position: fixed;
    width: 100%;
}

header ul {
    margin: 0;
    padding: 5px;
    list-style: none;
    overflow: hidden;
    background-color: rgb(235, 235, 235);
}

header li a {
    display: block;
    padding: 20px 20px;
    border-right: 1px solid rgb(225, 225, 225);
    border-left: 1px solid rgb(225, 225, 225);
    text-decoration: none;
    color: #333;
}

header li a:hover {
    background-color: rgb(225, 225, 225);
}

.logo {
    display: block;
    float: left;
    font-size: 20px;
    padding: 10px 20px;
    text-decoration: none;
    color: #333;
}

.logo span {
    vertical-align: bottom;
    display: inline-block;
}

header .menu { /* Objectif : cacher le menu par défaut */
    clear: both;
    max-height: 0;
    transition: max-height .2s ease-out;
  }


    /* ----------------- Hamburger menu-icon ----------------- */

header .menu-icon {
    cursor: pointer;
    float: right;
    padding: 28px 20px;
    position: relative;
    user-select: none; /* L'icone du menu ne peut pas être sélectionnée par l'utilisateur */
}

header .menu-icon .navicon { /* Barre du milieu qui disparait en transition */
    background: #333;
    display: block;
    height: 2px;
    width: 18px;
    position: relative;
    transition: background .2s ease-out;
}

header .menu-icon .navicon:before,
  header .menu-icon .navicon:after { /* Les deux autres barres */
    background: #333;
    content: '';
    display: block;
    height: 100%;
    width: 100%;
    position: absolute;
    transition: all .2s ease-out;

  }

header .menu-icon .navicon:before { /* Barre du bas */
    top: 5px;
}

header .menu-icon .navicon:after { /* Barre du haut */
    top: -5px;
}



    /* ----------------- Hamburger Menu button behavior ----------------- */

header .menu-btn {
    display: none;
}

header .menu-btn:checked ~ .menu {
    max-height: 100vh;
}

header .menu-btn:checked ~ .menu-icon .navicon { /* Barre du milieu qui disparait*/
    background: transparent;
}

header .menu-btn:checked ~ .menu-icon .navicon:before { /* Barre du bas qui tourne */
    transform: rotate(-45deg);
}

header .menu-btn:checked ~ .menu-icon .navicon:after { /* Barre du haut qui tourne */
    transform: rotate(45deg);
}

header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:before,
  header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:after { /* Les deux barres se croisent en leur milieu */
    top: 0;
  }

    /* ----------------- Sous-catégories ----------------- */

.nav-expand-content {
    position: absolute;
    top: 76px;
    left: 0;
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    transform: translateX(100%);
    transition: 0.3s;
    visibility: hidden;
}

.active > .nav-expand-content {
    transform: translateX(0);
    visibility: visible;
    box-shadow: 1px 1px 4px 0 rgba(0,0,0,.5);
}

.nav-link {
    display: flex;
    justify-content: space-between;
}




    /* ----------------- Media Queries ----------------- */

@media (min-width: 768px) {
    header li {
        float: left;
    }
    header li a {
        padding: 20px 30px;
    }
    header .menu {
        clear: none;
        float: right;
        max-height: none;
    }
    header .menu-icon {
        display: none;
    }
}

JS :

    /* -------------------------------------
            Menu + sub-menu
--------------------------------------*/

let navExpand = document.querySelectorAll('.nav-expand')
let backLink = `<li class="nav-item">
    <a class="nav-back-link" href="javascript:;">
        <i class="fas fa-caret-left"></i> Back 
    </a>
</li>`
let forwardIcon = '<i class="fas fa-caret-right"></i>'

navExpand.forEach(item => {
    item.querySelector('.nav-expand-content').insertAdjacentHTML('afterbegin', backLink)
    item.querySelector('.nav-link').insertAdjacentHTML('beforeend', forwardIcon)
    item.querySelector('.nav-link').addEventListener('click', () => item.classList.add('active'))
    item.querySelector('.nav-back-link').addEventListener('click', () => item.classList.remove('active'))
})



    /* ----------- Close sub-menu when checkbox unchecked ----------- */

let checkBox = document.getElementById('menu-btn');

checkbox.addEventListener('change', e => {

    if(e.target.checked==false){
        navExpand.forEach(item => {
            item.classList.remove('active')
        })
    }
})

Knowing that right now, I'm working on a mobile first, so, you'll need to resize to see my problems.

Problem 1 : CSS problem

The first level of submenu works as intended, above the original menu, and we can still see the titles and hamburger logo. But after this, the next level comes just under it, instead of over it, and so on. I don't know how to stack them without them having another position. If I put their top position to 0, they work as I intended them, but over ma titles and icon. So, I put 76px under this... I try a lot of different things, but these two are the nearest to what I want.

Someone advises me to put everything in another div, as a sidebar. I began to make this, but then, for a larger screen, it makes it looks awfully harder to do, since then I'd have 2 navs working as one. Seems harder than to make one nav working as two for a mobile device, I guess? And I don't understand why it shoudln't be working if it's inside the same nav, (and I don't like it when I don't undertand something) so I stopped. Even if as so, the sidemenu was working as intended. So, I guess if I can't work it out, I'll go there. But I'd love to avoid it.

Problem 2 : JS problem

As you can see, this make a lot of submenus, and with the active class, we have to remove them one by one. I made some code to make it as if we unchecked the menu hamburger, they should all remove their active class, but whatever the code, it doesn't work, and I can't even begin to understand why.

Thanks for your time and advice in advance

PS : I don't know any JQuery yet '^^




Checkbox not appearing

I'm writing a .NET Core 3.1 WinForms application but I've an issue with checkboxes. They simply don't appear on my form.

I tried to use both Visual Studio 2019 Version 16.5.2 and Visual Studio 2019 Preview Version 16.7.0 Preview 1.0. I activated the option Use the preview Windows Forms designer for .NET Core apps (this option seems to be missing on the non-preview VS) but even with that the checkbox control is missing from the designer.

So instead I just manually added my checkboxes in the MyForm.Designer.cs file

// 
// checkboxRotate
// 
this.checkboxRotate.Visible = true;
this.checkboxRotate.Location = new System.Drawing.Point(400, 40);
this.checkboxRotate.Name = "checkboxRotate";
this.checkboxRotate.Size = new System.Drawing.Size(104, 24);
this.checkboxRotate.TabIndex = 0;
// 
// checkboxFlip
// 
this.checkboxFlip.Visible = true;
this.checkboxFlip.Location = new System.Drawing.Point(370, 40);
this.checkboxFlip.Name = "checkboxFlip";
this.checkboxFlip.Size = new System.Drawing.Size(104, 24);
this.checkboxFlip.TabIndex = 0;

I set the locations based on other controls, these checkboxes should be at 40 on the vertical axis and 370 and 400 seem good to me on the horizontal axis.

However when I debug they still don't appear on my form. I tried to convert the application to .NET 5 (Preview 4 in installed on my machine) but nothing changed.

So how can I get the checkbox control to work? Can I get it in the designer in some way?

All the screenshots on the web are showing the checkbox control in the designer even this one from 5 days ago. They say the new designer is available in VS 2019 16.7 Preview 1 if the Use the preview Windows Forms designer for .NET Core apps option is checked which is exactly what I did. So why don't I have this control?

Thanks




Add "other"-input to HTML-Form-checkbox using javascript

I wanted a checkbox with an adjacent text input where the user can specify an "other"-option. As it took me a while and I did not find anything usesful on this topic I just want to share my solution:

HTML (using bootstrap.css):

<input class="form-check-inline" type="checkbox" id="checkbox1.1" value="Other: ">
<label class="form-check-label" for="checkbox1.1">Other: </li></label>
<input class="input-sm" type="text" id="checkbox1.1.text" onkeyup="checkValueOther('checkbox1.1')">

and javascript:

function checkValueOther(elem) {        
    document.getElementById(elem).value = "Other: " + document.getElementById(elem + ".text").value;
    document.getElementById(elem).checked = true;   
}

If you know a more elegant solution, let me know.

Pat




Data binding checkboxes in svelte

in a svelte/sapper form I want to send data to a user model

<input type="text" bind:value={user.label}>

..works as expected. But how to send user.offer_ids

let offer_ids = [];

{#each offers as offer}
  <label>
   <input type=checkbox bind:group={offer_ids} value="{offer.id}">{offer.label}
  </label>
{/each}

I can't find any svelte sample how to do this job, which I think is basic in forms.. Thanks for help




React checkbox if checked add value to array

Hi this might be a very newbie question to ask but here is my question. I have check boxes that represent all the days of the week. If a day is checked I want to add it to a array so that on submit I can pass the array to back-end. I copied check box structure from bootstrap to start with. I tried to add logic to see if a box is checked and if it is checked I want to push it to my empty array in state. Also if a checkbox was checked but then unchecked I want to remove the item from the state array. So far I haven't found a way to make this all work.

import React from 'react'

class CalenderSettingsModal extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            workStart: 8,
            workEnd: '',
            workDays:[],

        }

        handleCheckboxChange = (event)=> this.setState({workDays: event.target.value});


    }

    render() {


        return (
            <React.Fragment>
                        <form>
                            <div>
                                <h5>Select your workday(s):</h5>
                                <div class="custom-control custom-checkbox " >
                                    <input type="checkbox" class="custom-control-input" id="monday" value="monday"  onChange={this.handleCheckboxChange}/>
                                    <label class="custom-control-label" for="monday">Monday</label>

                                </div>
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="tuesday" value="tuesday" onChange={ this.handleCheckboxChange}/>
                                    <label class="custom-control-label" for="tuesday">Tuesday</label>

                                </div>

                        </form>
                            <button >Save settings</button>



            </React.Fragment>

        );
    }
}

export default CalenderSettingsModal;

With this so far I tried to accomplish assigning the value to workDays when the box is checked but isn't working and I'm not sure how I could accomplish what I want to do. Any insight would be appreciated.