jeudi 30 avril 2020

How to search database and filter results using multiple checkboxes? PHP

I'm a complete newbie, so please bear with me.

I need to create a html form that searches through a music database (using GET method) called 'top_albums'. One of the requirements for the form is to create checkboxes (titled.. US, UK, FR, DE, CA, and AU) so that results are filtered so only albums in the corresponding country are displayed. I should be able to select as many or as few checkboxes as I want. And the results returned should show albums in ALL the countries selected.

How would I go about doing this? Also, in the top_albums database, columns are named artist, albums, US, UK, FR, DE, CA, AU.

So far, I've succeeded in creating a text input that allows filtering the database by artist name (which is also a requirement) and the checkboxes on the form (without php code).

Here is part of my html form:

<form action="results.php" method="get">
<fieldset><legend>Popular Music Database Search</legend>
<p>Artist Name: <input type="text" name="search" /></p>

<p><input type="checkbox" name="country[]" value="US">US
<input type="checkbox" name="country[]" value="UK">UK
<input type="checkbox" name="country[]" value="FR">FR
<input type="checkbox" name="country[]" value="DE">DE
<input type="checkbox" name="country[]" value="CA">CA
<input type="checkbox" name="country[]" value="AU">AU</p>

<p><input type="submit" /></p>
</form>

Here is my PHP:

 <?php
    $search = $_GET['search'];

    $servername = "localhost";
    $dbname = "";
    $username = "";
    $password = "";
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
?> 
<table>
  <tr>
    <th>Artist</th>
    <th>Album</th>
  </tr>
  <?php
    $sql = "select * from top_albums where artist like '%$search%'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0){
    while ($row = $result->fetch_assoc())
    {
      echo("<tr><td>".$row["artist"]."</td><td>".$row["album"]."</td></tr>");
    }
    } else {
        echo "0 records";
}

$conn->close();
 ?>
</table>

Thanks in advance




Calling function when checking checkbox - Google Sheets

I am trying to call a function when someone check a checkbox. I came up with this so far but it is not working. Checkboxes are in cells F2 and F3

function onEdit(e) {
  var range = e.range
  if(range.getCell() == "F2") {
    resetData()
  }
  else if(range.getCell() == "F3") {
    renameSheet()
  }
}



How to toggle and check a Material UI Checkbox in Enzyme / Jest Test

I've got a simple component wrapped around a Material UI Checkbox. I've stripped it down to the bare minimum here.

//@flow
import React from "react";
import { Checkbox } from "@material-ui/core";

function MyCheckboxComponent() {
  const [checkedState, setCheckedState] = React.useState(true);

  const handleChange = event => {
    setCheckedState(event.target.checked);
  };

  return <Checkbox checked={checkedState} onChange={handleChange} />;
}

export default MyCheckboxComponent;

I simply want to test this component and toggle the Checkbox value and check it. I cannot get my simple test passing. I'm at a loss as to why.

import React from "react";

import Enzyme, { mount } from "enzyme";
import { Checkbox } from "@material-ui/core";
import Adapter from "enzyme-adapter-react-16";

import MyCheckboxComponent from "./MyCheckboxComponent";
Enzyme.configure({ adapter: new Adapter() });

/** Interaction tests testing user interaction with PilzButton */
test("Toggle Checkbox test", () => {
  const wrapper = mount(<MyCheckboxComponent />);

  const checkBox = wrapper.find(Checkbox);
  expect(checkBox).toHaveLength(1);

  checkBox.simulate('change', { target: { checked: true } });

  expect(checkBox.props().checked).toBe(true);
});

Should checkBox.simulate('change', { target: { checked: true } }); work and toggle the value of the Checkbox ??

What I have so far is here on CodeSandbox ...

Edit toggle-material-ui-checkbox-jest




How could i add an on click event to this checkbox? (HTML Helpers)

I have a checkbox as follows:

@using (Html.BeginForm("ItemsEdit", "Items", FormMethod.Post))
       {

            @Html.CheckBox("itemCheck")

       }

I want to be able to send an additional value to a controller when it is clicked, similar to something like this:

<input id = "@dataLineItem.Split(Model.ItemList.delimiterChar)[0]" type="checkbox" value="true" name="Remember" onclick="sendCheckId(this.id)" />

However, if i were to use the method above, i wouldnt know how to pass the 'true/false' values of the checkbox, to the same controller.




creating multiple checkboxes in angular 9 not working for me

I have the need for a table containing a checkbox for every row in the table. I'm using Angular 9.

The table is defined in a form and I use an ngFor to create each row in the table. In the ngFor I loop over a collection of messages and I create a row for each message.

The user should be able to check the checkbox and the push a button to resend the selected messages.

The way I've written my code I do get errors I can't explain.

I have created a stackblitz thingy to share my code. https://stackblitz.com/edit/angular-4qqrzf?file=src%2Fapp%2Fapp.component.ts There are some things wrong with this code in Stackblitz. The most annoying one is that it keeps saying that it's loading while nothing seems to happen. I must be missing something there.

If I run the code on my own system I get this error:

[Error] ERROR – TypeError: this.form.controls.orders.push is not a function. (In 'this.form.controls.orders.push(control)', 'this.form.controls.orders.push' is undefined) — app.component.ts:36
TypeError: this.form.controls.orders.push is not a function. (In 'this.form.controls.orders.push(control)', 'this.form.controls.orders.push' is undefined) — app.component.ts:36
    defaultErrorLogger (vendor.js:12499)
    handleError (vendor.js:12552)
    run (polyfills.js:136)
    (anonymous function) (vendor.js:45404)
    onInvoke (vendor.js:44403)
    run (polyfills.js:136)
    (anonymous function) (polyfills.js:870)
    onInvokeTask (vendor.js:44381)
    runTask (polyfills.js:180)
    drainMicroTaskQueue (polyfills.js:582)
    promiseReactionJob

I have copied most of the code from https://stackblitz.com/edit/angular-stszta?file=src%2Fapp%2Fapp.module.ts where this problem does not occur.

app.component.ts:

import { Component } from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup;
  ordersData = [
    { id: 100, name: 'order 1' },
    { id: 200, name: 'order 2' },
    { id: 300, name: 'order 3' },
    { id: 400, name: 'order 4' }
  ];

  berichten = [
    {messageId: 123},
    {messageId: 234},
    {messageId: 345},
    {messageId: 456},
    {messageId: 567}
  ];

  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      orders: []
    });
    this.addCheckboxes();
  }

  private addCheckboxes() {
    this.ordersData.forEach((o, i) => {
      const control = new FormControl(i === 0); // if first item set to true, else false
      (this.form.controls.orders as FormArray).push(control);
    });
  }

  submit() {
    const selectedOrderIds = this.form.value.orders
      .map((v, i) => (v ? this.ordersData[i].id : null))
      .filter(v => v !== null);
    console.log(selectedOrderIds);
  }
}

app.component.html:

  <table>
    <thead>
    <tr>
      <td>
        <b>Selection</b>
      </td>
      <td>
        <b>MessageId</b>
      </td>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let bericht of berichten; let i = index" >
      <td>
        <input type="checkbox" [formControlName]="i">
      </td>
      <td>
        
      </td>
    </tr>
    </tbody>
  </table>
</form>

What am I doing wrong? (In Stackblitz and in my code)




ag grid floating filter mat select dropdown with multiple option checkbox not getting fliter results

Basically, in the current value, we are getting multiple options in form of the array but not able to filter it.

this.params.onFloatingFilterChanged({ model: this.buildModel(this.currentValue) });
this.params.parentFilterInstance( (instance) => {
  if (typeof this.currentValue === 'object') {
    if (this.currentValue.length > 0) {
      **instance.onFloatingFilterChanged('equals', this.currentValue);//this.currentValue=['enable','disable']**
    } else {
      instance.onFloatingFilterChanged('equals', '');
    }
  } else {
    instance.onFloatingFilterChanged('equals', this.currentValue);
  }
});



mercredi 29 avril 2020

Javascript select entire row (change background color) of a table with checkbox and deselect when next checkbox is clicked

I have table where I want to select entire row (change background color). Rows are selected by a checkbox and when a next row is selected, the previous row has to deselect.

This is my table

<table id="table" border="1">
  <tr>
    <th></th>
    <th>ID</th>
    <th>Name</th>
    <th>Surname</th>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(0)'>
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(1)'>       
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
  <tr>
    <td class='row'>
      <input type='checkbox' class='check' onclick='markRow(2)'>       
    </td>
    <td class='row'>-</td>
    <td class='row'>-</td>
    <td class='row'>-</td>
  </tr>
</table>
#table{
  border-collapse: collapse;
}

I named every table cell with class="row". Calculating an interval in which a specific row is positioned and using the for loop, I should be able to set background color to those table cells. Intervals are: for the first row its 0-3, second 4-7 and third 8-11.

I tried this:

var clear1 = 0;
var clear2 = 0;
//these two should clear the previous row

var counter = 0;  
//this will ensure that clearing doesn't happen the first time


//function parameter is given by this checkbox from table  
//<input type='checkbox' class='check'onclick='markRow(0)'> 
function markRow(rowNumber){  
  var row = document.getElementsByClassName('row');
  var checkboxes = document.getElementsByClassName('check');

  var interval = rowNumber*4;

  for(var i=interval;i<=interval+3;i++){
    row[i].style = "background-color: dodgerblue;";
  }
  //for example if function gets parameter rowNumber=2, then it will color the cells in interval 8-11

  counter++;
  if(counter>1){
    for(var i=clear1;i<=clear2;i++){
      row[i].style = "";
    }
    checkboxes[clear1].checked = false;
  }
  clear1 = interval;
  clear2 = interval+3;
  //these two will save the interval from the current row and next time, for loop will delete style 
  //using this interval
}

It works for the first row, but second row and third row sometimes don't check off and don't get deselected. I don't know what could be a problem.




Controlling javascript with checkbox

I'm building a chrome extension where i want to control javascript with this checkbox :

    <div class="modal-icons">
        <div class="flex-container">
            <div class="flex">
                <label class="switch">
                  <input id="check" type="checkbox" checked>
                  <span class="slider round"></span>
                </label>
            </div>
        </div>
    </div>

How can i get the state in the .js file?

I have tried :

document.addEventListener('DOMContentLoaded', function() {
const checked = document.getElementById('check').checked;
  # ACTION 
  });

and

var checked = document.getElementById('check').checked;
console.log('checked');

And also similar approaches but I'm not sure how to get the state.

I get the error message : Uncaught TypeError: Cannot read property 'checked' of null

Can I write this for instance?

if (checked == true) {
   console.log('checked');
}

Or will it give a value of 'checked'?

Could someone help me to explain this, please?




How to print respective checkbox name when they are checked in tkinter?

I want to print respective checkbox names in console when a checkbox is checked.

For example, when I check 'COPYRIGHT' checkbox:

What I want to be printed: 'copyright'

What is printed: 'creation'

I found that when I replace creation with other elements of metadata_list, that newly replaced element is always printed out. In general, last element of the metadata_list is always printed by the temp() function no matter which checkbox I check. I think there is some hulululu going on when I pass 'key' as command in the function.

But correct key value is displayed when key is printed from outside the temp() function like there is inside for loop. What am I doing wrong here?

This is main file:

import tkinter as tk
import variable_container as vc

metadata_frame = tk.Tk()

def temp(key):
    print(key)

for key,i in vc.metadata_list.items():
    i[1] = tk.IntVar()
    tk.Checkbutton(metadata_frame, text = key.upper(), variable = i[1], command = lambda: temp(key)).grid(row = i[0])
    print(key)

metadata_frame.mainloop()

And this is variable_container.py file:

# Values are the row information and respective checkbox variables
metadata_list = {
    'copyright': [0, var_copyright],
    'location': [1, var_location],
    'creation': [2,var_creation]
}




Get checkboxs value with Jquery return wrong values sometimes but not everytime

I try to get the checkbox checked values, It "works" not really well, sometimes I have the right value, sometime not, could you explain me why and how I can fix this ?

The purpose is at this end to build an array of all the values checked

Here a snippet :

$( "input" ).on( "click", function() {
                alert('test : ' + $( "input:checked" ).val() + " is checked!"  );
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="options-check">
    <div class="row">
      <div class="col-sm-4  col-lg-4">

        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="abc" value="all">
          <label class="form-check-label" for="inlineCheckbox1">All</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="checkbox" id="inlineCheckbox2" name="abc"  value="businessrules">
          <label class="form-check-label" for="inlineCheckbox2">Business Rules</label>
        </div>
        <div class="form-check form-check-inline">
          <input  type="checkbox" id="inlineCheckbox3" name="abc" value="scriptinclude">
          <label class="form-check-label" for="inlineCheckbox3">Script Include</label>
        </div>
        <div class="form-check form-check-inline">
          <input  type="checkbox" id="inlineCheckbox4" name="abc" value="schedulejobs">
          <label class="form-check-label" for="inlineCheckbox4">Scheduled Jobs</label>
        </div>
      </div>
      <div class="col-sm-4 col-lg-4">
        <div class="form-check form-check-inline">
          <input  type="checkbox" id="inlineCheckbox5" name="abc" value="uiaction">
          <label class="form-check-label" for="inlineCheckbox5">UI Action</label>
        </div>
        <div class="form-check form-check-inline">
          <input  type="checkbox" id="inlineCheckbox6" name="abc" value="uipolicies">
          <label class="form-check-label" for="inlineCheckbox6">UI Policies</label>
        </div>
        <div class="form-check form-check-inline">
          <input  type="checkbox" id="inlineCheckbox7" name="abc" value="uimacro">
          <label class="form-check-label" for="inlineCheckbox7">UI Macro</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="checkbox" id="inlineCheckbox8" name="abc" value="uipage">
          <label class="form-check-label" for="inlineCheckbox8">UI Page</label>
        </div>
      </div>
      </div>
      </div>

Thanks a lot for your help




mardi 28 avril 2020

Is there any way to create a dropdown with checkboxes inside using Ruby on Rails

I have a query on Ruby on Rails :

I have an array say "names" of type string in a .rb file I want to create a dropdown with checkboxes for each item for "names" using Ruby on Rails. I am using erb.html file format. Once created , is there any way to dump the selected names into another array.




Limit Number Multiple Checkboxes in JS

I have multiple checkboxes with limits but it doesn't work with JS like this

$(".checkbox-limit").on('change', function(evt) {
 var limit = parseInt($(this).parent().data("limit"));

if($(this).siblings(':checked').length >= limit) {
       this.checked = false;
       alert("The limit is " + limit)
   }
});

and for html like this:

<div class="row js_check_two" data-limit="2">
    <div class="col-md-12">
        <label>
            <input type="checkbox" class="checkbox-limit" value="1">
        </label>
    </div>
    <div class="col-md-12">
        <label>
            <input type="checkbox" class="checkbox-limit" value="2">
        </label>
    </div>
    <div class="col-md-12">
        <label>
            <input type="checkbox" class="checkbox-limit" value="3">
        </label>
    </div>
    <div class="col-md-12">
        <label>
            <input type="checkbox" class="checkbox-limit" value="4">
        </label>
    </div>
</div>

This code not working,

Any suggestions would be gratefully receive!




Storing the values of dynamically added checkboxes from userforms

I have a user in which I am creating 7 checkboxes programmatically, and removing the same using 2 command buttons. Now, I am facing issues when I am trying to read/ store the value of a checkbox when clicked.

I have used the Class Module -

Public WithEvents cBox As MSForms.CheckBox

Private Sub cbox_click()
    msgbox cBox.Name & " clicked. Value is now " & IIf(cBox.Value, "Checked", "Unchecked")
End Sub

And in UserForm -

Dim chkBoxEvent As clsBoxEvent
Dim chkBoxColl As Collection

Private Sub btnAddClass_Click()
    Dim ctrl As Control, newCtrl As Control, offsetTop As Integer
    Set chkBoxColl = New Collection

    offsetTop = 36

    For Each ctrl In Me.Controls
        If TypeName(ctrl) <> "CommandButton" Then
            If ctrl.Top = btnAddClass.Top - offsetTop Then
                If TypeName(ctrl) = "ComboBox" Then
                    Set newCtrl = Me.Controls.Add("Forms.ComboBox.1")
                ElseIf TypeName(ctrl) = "TextBox" Then
                    Set newCtrl = Me.Controls.Add("Forms.TextBox.1")
                End If
                nchk = 7
                If TypeName(ctrl) = "CheckBox" Then
                For i = 1 To nchk
                    Set newCtrl = Me.Controls.Add("Forms.Checkbox.1")

                    With newCtrl
                        .Height = ctrl.Height
                        .Width = ctrl.Width
                        .Top = ctrl.Top + offsetTop
                        .Left = ctrl.Left
                        .Tag = nchk * 10
                    End With
                    Set chkBoxEvent = New clsBoxEvent
                    Set chkBoxEvent.cBox = Me.Controls(newCtrl.Name)
                    chkBoxColl.Add chkBoxEvent
                Next
                End If
                If TypeName(newCtrl) <> "CheckBox" Then
                    With newCtrl
                        .Height = ctrl.Height
                        .Width = ctrl.Width
                        .Top = ctrl.Top + offsetTop
                        .Left = ctrl.Left
                    End With
                End If
            End If
        End If
    Next ctrl

    btnAddClass.Top = btnAddClass.Top + offsetTop
    btnRemoveClass.Top = btnRemoveClass.Top + offsetTop
    Me.Height = Me.Height + offsetTop
End Sub

Private Sub btnRemoveClass_Click()
    Dim ctrl As Control, offsetTop As Integer
    offsetTop = 36

    For Each ctrl In Me.Controls
        If TypeName(ctrl) <> "CommandButton" Then
            If ctrl.Top = btnAddClass.Top - offsetTop Then
                Me.Controls.Remove (ctrl.Name)
            End If
        End If
    Next ctrl
    btnAddClass.Top = btnAddClass.Top - offsetTop
    btnRemoveClass.Top = btnRemoveClass.Top - offsetTop
    Me.Height = Me.Height - offsetTop
End Sub

Each time new set of checkboxes are added, the msgbox displays as "CheckBox22, 99, 110, 789" etc random numbers.




how to close "checkbox" dropdown onBlur in js?

I have a dropdown done by invisible checkbox. This dropdown is working ok, but it doesn't want to close unless I click on the label again.

The issue is that onBlur is never got called. Why? If I set onMouseOut - it triggers ok, but it closes the dropdown immedeately.

I've seen How to hide a dropdown when the user clicks outside of it but I didn't figure how to pass props to the very last solution...

        <div onBlur ={handleUncheckCheckbox} className="dropdown">
            <input id="check01" type="checkbox" name="menu"/>
            <label for="check01" className="sorting-element">click me</label>
            <div className="dropdown-content">
                <p>1</p>
                <p>2</p>
                <p>3</p>
            </div>
        </div>



How can I combine pagination and filtering in php?

I would like to display some products from database and use pagination as well as checkboxes for filtering. My pagination is working fine. And when I click checkboxes and press "submit," I do get filtered results on the first page. However, when I move to the second or any other page, the checkboxes automatically become unchecked and the filtering gets lost. Here is my HTML code:

<form action="" method="get">
  <input type="checkbox" name="brand[]" value="iPhone">iPhone<br>
  <input type="checkbox" name="brand[]" value="iPad">iPad<br>
  <input type="checkbox" name="brand[]" value="Samsung">Samsung<br>
  <input type="checkbox" name="brand[]" value="Huawei">Huawei<br>

  <input type="submit" name="submit" value="Submit">
</form>

<?php include 'display_products.php';?>

In order to apply filtering I use an IF statement:

if (isset($_GET['brand'])) {
  $filter = implode('","',$_GET['brand']);
  $sql='SELECT * FROM products WHERE brand IN ("' . $filter . '") LIMIT ' . $this_page_first_result . ',' .  $results_per_page;
  $result = mysqli_query($conn, $sql);

  while($row = $result->fetch_assoc()) {
    echo '<div><h3>' . $row['title'] . '</h3><img src="' . $row['image'] . '"<h4>' . $row['price']. '</h4></div>';
  }
} //else display all products from the table of the database

I assume that when I go to the next page, my checkboxes get unchecked, this $_GET['brand'] becomes empty and the "else" statement is activated. I tried to find solutions for this problem, but some of them were not effective and some were too hard for me to understand (I am a beginner). Could you please explain in simple terms how to keep the checkboxes checked and how to keep the filtering throughout all the pages? I saw such ideas as "use session" or "keep the data in url," but I can't figure out how to implement it. So if you are more specific, I would be super grateful. Thank you very much!




How can i use this checkbox value within my controller? (System.NullReferenceException: 'Object reference not set to an instance of an object.')

I have a boolean variable within my model assigned as false, which i am then using in my view within a checkbox in order to obtain true or false based on whether the checkbox is ticked or not.

In my view:

@using (Html.BeginForm("Items", "Items", FormMethod.Post, new { id = "checkBoxForm" } ))
        {
                @Html.CheckBoxFor(x => x.ItemList.itemCheck)
        }

In my ActionResult:

[HttpPost]
        public ActionResult Items(string ItemDescription, CategoryItemViewModel model)
        {


                var FkFile = Server.MapPath("~/App_Data/ForeignKeyValue.txt");

                var Fk = System.IO.File.ReadAllText(FkFile);

                var dataFileItems = Server.MapPath("~/App_Data/Item.txt");

                var numberOfLinesItems = System.IO.File.ReadLines(dataFileItems).Count();

                var textFileDataItems = model.ItemList.itemCheck + Environment.NewLine;

                System.IO.File.AppendAllText(dataFileItems, textFileDataItems);


            return View();
        }

I have tried to pass this value through 'model.ItemList.itemCheck', however when this ActionResult is executed, i receive a " System.NullReferenceException: 'Object reference not set to an instance of an object.' " error.




Excel Checkboxes and Arrays -VBA

Been skimming the sites that past week in search of answers for a VBA project that I am working. First time VBA programmer and a lot of the forums here have helped me get through it. I won't lie, my code doesn't look the best but so far the features i'm trying to add have been working but ultimately I've hit a road block with 2 things that maybe I'll be able to get some advice on.

I am creating a project tracker for the team I work with and what I want to do is copy all the project information for a single project in a single row. Then 2 columns in the row will be "Task Complete" and "Date Completed". Currently I'm using a Data Validation list to select "Complete" in the task complete cell. When "Complete" is listed, the Date Complete will auto populate with "Today's" date. I'm achieving this with just simple functions in excel.

I've then created VBA code so that a command button is clicked, it will highlight specific cells in the row, copy those cells, paste them in a empty worksheet, then clear the task and date complete cells. I've gotten most of these features to work but I've hit the roadblock in having excel copy the data in the blank work sheet in empty rows only (Row A1, A2, A3, etc). I am unsure how to have the code copy the data in empty rows. I know it can be achieved some how by using a variable (i) and loops.

My other question was, I originally wanted to use check boxes instead of a validated list but seem to have issues with formatting with the checkboxes. If my row size has to change to fit text, the checkboxes will crowd other cells. Is this just a flaw of forms/activeX in excel or am I missing part of the bigger picture.

As far as the code, I tried using an array to check the "Task Complete" column than individual If statements to add the date. Thanks in advanced for any help. Attached is a sample of my code:

Dim pjt As Worksheet
Dim datawks As Worksheet
Dim myBook As Workbook  'define worksheets and workboook
Set myBook = Excel.ActiveWorkbook
Set pjt = myBook.Sheets("Project Tracker")
Set datawks = myBook.Sheets("DATA")

Dim tskarray(16) As String
     tskarray(0) = Range("K4")
     tskarray(1) = Range("k5")
     tskarray(2) = Range("k6")
     tskarray(3) = Range("k7")
     tskarray(4) = Range("k8")
     tskarray(5) = Range("k9")
     tskarray(6) = Range("k10")
     tskarray(7) = Range("k11")
     tskarray(8) = Range("k12")
     tskarray(9) = Range("k13")
     tskarray(10) = Range("k14")
     tskarray(11) = Range("k15")
     tskarray(12) = Range("k16")
     tskarray(13) = Range("k17")
     tskarray(14) = Range("k18")
     tskarray(15) = Range("k19")
     tskarray(16) = Range("k20")


        If tskarray(0) = "Complete" Then
            Range("A4,B4,D4,F4,G4,J4,L4").Select
            Selection.Copy
            datawks.Select
            datawks.Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, skipblanks _
                :=False, Transpose:=False
            Sheets("Project Tracker").Select
            Application.CutCopyMode = False
            pjt.Range("J4,K4").Select
            Selection.ClearContents

        Else
        Debug.Print ("No Task to Complete")
        End If



Create an ActiveX checkbox that check and unchecks all other checkboxes

I've got a sheet with a lot of checkboxes. The first one has the caption Check All and when you click it, all checkboxes should be checked. That works fine, but I also want to uncheck all the checkboxes by unchecking it and I can't get that to work. I get the error 1004. This is the code I'm trying:

Private Sub CheckBox1_Click()
On Error GoTo finished
For i = 2 To 200
    If ActiveSheet.OLEObjects("CheckBox1").Object.Value = True Then ' <- this line gives the 1004 error
        ActiveSheet.OLEObjects("CheckBox" & i).Object.Value = False
    Else
        ActiveSheet.OLEObjects("CheckBox" & i).Object.Value = True
    End If
Next i
Exit Sub
finished:
End Sub



Component state not updating after unchecking checkbox in React

I simply want to change the state of my app with a handleChange method for multiple checkboxes.

My state is changed from false to true when I click each of my checkboxes, but when I un-check it, my state doesn't change to reflect it and I cant seem to figure out why!

import React, { Component } from "react";

export class StepOne extends Component {
    constructor(props) {
        super(props);
        this.state = {
            box1: false,
            box2: false,
            box3: false,
        };
    }

    handleChange = (evt) => {
        const box = evt.target.name;
        this.setState({ [box]: !this.state.box });
    };

    render() {
        return (
            <div>
                <input type="checkbox" name="box1" onChange={this.handleChange} />
                <input type="checkbox" name="box2" onChange={this.handleChange} />
                <input type="checkbox" name="box3" onChange={this.handleChange} />
            </div>
        );
    }
}



Saving form data with dynamic checkbox count in React

I’m doing an electronic journal of students for notes about visiting. Marks should be put down in checkboxes, and then go to the database in the JSON column. I insert student data using map. After clicking Submit, I should get an array of this format

[
  { SCHEDULE_ID : ''
    DATA : [ { NUMBER : '1', isChecked : true/false},
            { NUMBER : '2', isChecked : true/false},
            { NUMBER : '3', isChecked : true/false},
            ...
            { NUMBER : EMOUNT OF ELEMENTS, isChecked : true/false}
            ]
    }
]

My React code below.


<Table aria-label='Student table'>
    <TableHead color='primary'>
        <TableRow>
            <TableCell><b>№</b></TableCell>
            <TableCell><b>Призвіще, Ім&#39;я та По-Батькові</b></TableCell>
            <TableCell align='right'><b>Наявність</b></TableCell>
        </TableRow>
    </TableHead>
    <TableBody>
            {schedule_data.map(row => (
                <TableRow key={row.STUDENT_ID}>
                    <TableCell component='th' scope='row' size='small'> {Counter()} </TableCell>
                    <Tooltip placement='right-start' title={
                        <img className={classes.photo} src={`${row.STUDENT_PHOTO}`} alt='Фото студента'/>
                    }>
                        <TableCell size='small'>
                            <NavLink to="/profile" className={classes.a}>{row.STUDENT_LAST_NAME}&nbsp;{row.STUDENT_NAME}&nbsp;{row.STUDENT_SECOND_NAME}</NavLink>
                        </TableCell>
                    </Tooltip>
                    <TableCell align='right' size='small'>
                        <Checkbox color='primary'/>
                    </TableCell>
                </TableRow>
            ))}
    </TableBody>
</Table>
<Tooltip placement='left-center' title='Зберегти'>
    <Fab className={classes.fab} color='secondary' type='submit'>
        <SaveIcon/>
    </Fab>
</Tooltip>

I tried to make a form and send data to state but got errors.




Why is this value returning null to my controller?

I am trying to pass 'true' or 'false' to my ActionResult depending on whether a checkbox had been ticked or not. However, whenever the ActionResult is executed, the following error occurs during runtime:

"The parameters dictionary contains a null entry for parameter 'checkItem' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult Items(System.String, Boolean)' in 'u18043039_HW3.Controllers.ItemsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters"

My view where i am passing the value:

@using (Html.BeginForm("Items", "Items", FormMethod.Post))
             {
                  <input id="isItemChecked" name="checkItem" value="true" type="checkbox" />
             }

My ActionResult:

[HttpPost]
        public ActionResult Items(string ItemDescription, bool checkItem)
        {

            var FkFile = Server.MapPath("~/App_Data/ForeignKeyValue.txt");

            var Fk = System.IO.File.ReadAllText(FkFile);    

            var dataFileItems = Server.MapPath("~/App_Data/Item.txt");

            var numberOfLinesItems = System.IO.File.ReadLines(dataFileItems).Count();

            var textFileDataItems = ItemDescription + "," + numberOfLinesItems + "," + Fk + "," + checkItem + Environment.NewLine;

            System.IO.File.AppendAllText(dataFileItems, textFileDataItems);

            return View();
        }

I am also passing 'string ItemDescription' through to the ActionResult in the exact same way, and this appears to be working fine. Any idea on why this may be?




PHP Wordpress checkbox issue

I am building a wordpress plugin with the boilerplate framework (https://wppb.me/). That all works find. I have an annoying issues which I cannot solve.

I have a table with a Boolean field AM_ACTIVE

In the page layout I want this to be an checkbox. See method below. A array is initialized and with the shortcode_atts the array and the request parameters are merged. For an add new this works. But if I edit it. The edit page is showing the checked/non checked correctly. But save will always result in false. I have tried a million things. With True/false 0/1. Putting the value with cache values, item Values, request values. Most of the time I get an PHP Warning: A non-numeric value encountered in /var/www/vhosts/marcelvreuls.eu/httpdocs/wp-content/plugins/am

So I assume the checkbox is not know when it is not touched or something. I have no clue. Can anybody help me out. I just want to activated/deactived a record 😉.

Any help will be highly appreciated

First the page code, after that the save code

    function amarre_maingroup_form_meta_box_handler($item)
    {
        ?>
        <table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
            <tbody>
            <tr class="form-field">
                <th valign="top" scope="row">
                    <label for="am_name"><?php _e('Name', 'amarre')?></label>
                </th>
                <td>
                    <input id="am_name" name="am_name" type="text" style="width: 50%" value="<?php echo esc_attr($item['am_name'])?>"
                           size="50" class="code" placeholder="<?php _e('am_maingroup', 'amarre')?>" required>
                </td>
            </tr>         
            <tr class="form-field">
                <th valign="top" scope="row"> 
                    <label for="am_url"><?php _e('Afbeelding', 'amarre')?></label>
                </th>
                <td>
                    <input id="am_url" name="am_url" type="text" style="width: 50%" value="<?php echo esc_attr($item['am_url'])?>"
                           size="50" class="code" placeholder="<?php _e('Afbeelding', 'amarre')?>" required>
                </td>
            </tr>        
             <tr class="form-field">
                <th valign="top" scope="row">
                    <label for="am_active"><?php _e('am_active', 'amarre')?></label><?php echo $_POST['am_active']?>
                </th>
                <td>
                <?php 
                if ($item['am_active'] == 1)
                {
                    echo('<input name="am_active" type="checkbox"  value="1" checked="checked">');
                }
                else
                {
                    echo('<input name="am_active" type="checkbox"  value="0">' );
                }              
                ?>
                </td>
            </tr>      
            </tbody>
        </table>
        <?php
    }
function amarre_maingroup_form_page_handler()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'am_maingroup';

        $message = '';
        $notice = '';

        // this is default $item which will be used for new records
        $default = array(
            'id' => 0,
            'am_name' => '',
            'am_active' => '',
            'am_url' => ''
        );

        // here we are verifying does this request is post back and have correct nonce
        if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
            // combine our default item with request params
            $item = shortcode_atts($default, $_REQUEST);

            error_log( implode( ", ", $_REQUEST ));
            error_log( implode( ", ", $item ));
            // validate data, and if all ok save item to database
            // if id is zero insert otherwise update
            $item_valid =   $this->amarre_validate_maingroup($item);
            if ($item_valid === true) {  
                error_log( $item['am_name']);    
                error_log( $_REQUEST['am_active']);              
                if ($item['id'] == 0) {
                    $result = $wpdb->insert($table_name, $item);
                    $item['id'] = $wpdb->insert_id;
                    if ($result) {
                        $message = __('Item was successfully saved', 'amarre');
                    } else {
                        $notice = __('There was an error while saving item' + $result, 'amarre');
                    }
                } else {
                    $result = $wpdb->update($table_name, $item, array('id' => $item['id']));
                    if ($result) {
                        $message = __('Item was successfully updated', 'amarre');
                    } else {
                        $notice = __('There was an error while updating item' + $result, 'amarre');
                    }
                }
            } else {
                // if $item_valid not true it contains error message(s)
                $notice = $item_valid;
            }
        }
        else {
            // if this is not post back we load item to edit or give new one to create
            $item = $default;
            if (isset($_REQUEST['id'])) {
                $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $_REQUEST['id']), ARRAY_A);
                if (!$item) {
                    $item = $default;
                    $notice = __('Item not found', 'amarre');
                }
            }
        }




Bootstrap-Table : 'checkby' checks only for visible data, how to check for all the table?

I am having a problem with Bootstrap-table (bootstrap-table.com v1.16), as I am looking for a way to use the 'checkby' function with a table with more data than a page can display (I only have 30 rows, and I may not be able to display all the 30 rows by default for display reasons).

So, I have 30 rows and I want to check some rows by value, but some values are not on the current visible page. When I use the 'checkby' function, it only checks for the values that are currently displayed on the page. And then I try to order them by whether they are checked or not...

The #tableFonctions is already loaded with data before using this :

$("#tableFonctions").bootstrapTable('checkBy', { field: 'Id', values: idFonctions });
$("#tableFonctions").bootstrapTable('refreshOptions', { sortName: "Etat", sortOrder: "desc" });

Note that the field 'Etat' is my checkbox field. You can try this here : Live demo

Do you have any idea of how it can be done without modifying the source code ?

I succeeded by another mean (using a modified 'updateRow' function I can provide you if you want) but I still have a problem, but I will find a way for this and is not the main topic :)

Thanks !




Material UI + React Form Hook + multiple checkboxes + default selected

I am trying to build a form that accommodates multiple 'grouped' checkboxes using react-form-hook Material UI.

The checkboxes are created async from an HTTP Request.

I want to provide an array of the objects IDs as the default values:

defaultValues: { boat_ids: trip?.boats.map(boat => boat.id.toString()) || [] }

Also, when I select or deselect a checkbox, I want to add/remove the ID of the object to the values of react-hook-form.

ie. (boat_ids: [25, 29, 4])

How can I achieve that?

Here is a sample that I am trying to reproduce the issue:

https://codesandbox.io/s/smoosh-dream-zmszs?file=/src/App.js

Bonus point, validation of minimum selected checkboxes using Yup

boat_ids: Yup.array() .min(2, "")

Thanks in advance!




lundi 27 avril 2020

Cake php checkbox handling

hello guys i have a checkbox input inside foreach looping like this , and then i want to get all checkbox value as array data, but i'm can't get all data, only index 0 when i'm try to print_r() in my controller like this and the the output only like this, only index 0 are show when i'm try to print_r() enter image description here. Sorry for bad my grammar any one can help me please in cake php??




Vue checkbox not updating with data change

Having problems with my data in Vue updating the UI, but only checkboxes seem to have this problem.

I'm trying to allow only one checkbox to be checked at one time, therefore I'm setting all the checkboxes to false upon clicking one of them. However, this works in the data but isn't rendered correctly in the checkboxes.

HTML:

<table class="buildings-modify--table table-full table-spacing">
    <thead>
       <tr>
          <th>Name</th>
          <th>Primary</th>
          <th>Address</th>
          <th>City/Town</th>
          <th>Province</th>
          <th>Postal Code</th>
          <th>Phone</th>
          <th>Active</th>
       </tr>
     </thead>
     <tbody>
       <tr v-for="landlord in selectedLandlords" :key="landlord.id">
         <td></td>
         <td>                            
           <input type="checkbox" :value="landlord.is_primary" @change.prevent="makePrimaryLandlord(landlord)">
         </td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
       </tr>
   </tbody>

Vue Code:

export default {
     data: function() {
    return {
         selectedLandlords: []
    }
    },
    methods: {
          makePrimaryLandlord: function(landlord) {
              this.selectedLandlords = this.selectedLandlords.map(item => { item.is_primary = false; return item});
    }

}

}

Only the checkbox appears to have an issue. If I change say the name, or a text value with a filtered array setting them all to a specific value they change but the checkboxes data change doesn't reflect in the UI, however the data in Vue is correct.




multiple checkboxes overwrite one another in react native

I have a list of conditions i need check boxes next to. I have been able to do this, but now once a second checkmark is introduced , the first disappears. My code is as follows:

import React, {useState} from 'react';
import {View, Text, Button} from 'react-native';
import styles from './Styles';
import { CheckBox } from 'react-native-elements'


export default class Symptoms extends React.Component {
state = {
    checkedId: 'false',
    checkboxes: [
        {id: 1, title: "Fever"},
        {id: 2, title: "Headache"},
     ]
  }

  handleCheck = (checkedId) => {
    this.setState({checkedId})
  }

render() {
    const { checkboxes, checkedId } = this.state

  return (
    <View style=>

        <View>
                {checkboxes.map(checkbox => (
                    <CheckBox
                    center
                    iconRight
                    checkedIcon='check-circle-o'
                    uncheckedIcon='circle-o'
                    checkedColor='#122fae'
                    uncheckedColor='#122fae'
                    key={checkbox.id}
                    title={checkbox.title}
                    checked={checkbox.id == checkedId}
                    onPress={() => this.handleCheck(checkbox.id)}

                    />
                ))}
        </View>
     </View>
  );
}

}




RShiny: how can I summarise/subset/filter data using checkboxGroupInput?

I'm trying to use checkbox input to subset, filter, and summarise data. I've mocked up the problem with iris data.

I'm trying to allow the user to summarise iris data by sepal width/length, petal width/length, or both. Individually, each checkbox works, but using multiple input options is NOT working. Selecting both "Sepal" and "Petal" returns only Sepal data.

UI:

ui <- fluidPage(
    fluidRow(
        box(
            title = "Choose data", width = 3, solidHeader = TRUE,
            status = "primary", collapsible = TRUE,
            checkboxGroupInput("iris_select", "Select measurements:",
                        choices = list("Sepal", "Petal"),
                        selected = c("Sepal")),
            verbatimTextOutput("whatdidiselect")),

        box(
            title = "See your data output", width = 9, solidHeader = TRUE,
            status = "success", collapsible = TRUE,
            DT::dataTableOutput("iris_output")
        )))

And server:

server <- function(input, output) {

     output$whatdidiselect <- renderText(input$iris_select)

     iris_summary <- reactive({
        if(all(c("Sepal") %in% input$iris_select)){
            iris %>% 
                group_by(., Species) %>%
                summarise(Mean_Sepal_Length = mean(Sepal.Length),
                          Mean_Sepal_Width = mean(Sepal.Width))}

            if(all(c("Petal") %in% input$iris_select)){
                iris %>% 
                    group_by(., Species) %>%
                    summarise(Mean_Petal_Length = mean(Petal.Length),
                              Mean_Petal_Width = mean(Petal.Width))}

                if(all(c("Sepal", "Petal") %in% input$iris_select)){
                    iris %>% 
                        group_by(., Species) %>%
                        summarise(Mean_Sepal_Length = mean(Sepal.Length),
                                  Mean_Sepal_Width = mean(Sepal.Width),
                                  Mean_Petal_Length = mean(Petal.Length),
                                  Mean_Petal_Width = mean(Petal.Width))} 
    })

    output$iris_output <- DT::renderDataTable({
        iris_summary()})
}

This seems like it should be simple. Can someone point out where I'm going wrong?




jQuery : How can I count total checked boxes per column in a table?

I have a table with checkboxes like this :

| First | Second | Third |
|  [x]  |   [ ]  |  [x]  |
|  [x]  |   [x]  |  [ ]  |
|  [x]  |   [x]  |  [ ]  |

I'd like to count the totals of checked boxes per column, so I can display them for each column, like so :

| First | Second | Third |
|  [x]  |   [ ]  |  [x]  |
|  [x]  |   [x]  |  [ ]  |
|  [x]  |   [x]  |  [ ]  |
--------------------------
|   3   |    2   |   1   |



dimanche 26 avril 2020

Blazor, Checkbox keep checked, event after StateHasChanged() method called

I have this code :

@foreach (var item in list)
{
 <input type="checkbox" @onchange="@(e => HandleCheckChanged(e, item.Name))" checked="@item.IsChecked">
}

private async Task HandleCheckChanged(ChangeEventArgs e, string itemName)
{
   // do something ...
   StateHasChanged();
}

if I check a checkbox it calls the HandleCheckChanged and the checkbox is checked
But if I change the list items the previews checked checkbox is still checked and is not updated based on the new list items.

for example suppose that I have a list of ordered numbers {1-20} I follow these steps :
1 : list = GetAll().Where(c => c.Id < 10);
2 : I check the first checkbox (number 1)
3 : list = GetAll().Where(c => c.Id >= 10); (list updated and state has changed)
4 : the problem raises here , checkbox 11 is checked ??? but its value is false




how to use the checkbox to append a string into an arrey?

I have 3 checkbox created in a html file next to a text input. I am trying to get the input values appended to an empty array if the input box is checked. how should i do that? thank you

question = document.getElementById("question").value;
result1 = document.getElementById("result1").value;
result2 = document.getElementById("result2").value;
result3 = document.getElementById("result3").value;
correctRes1 = document.getElementById("check1");
correctRes2 = document.getElementById("check2");
correctRes3 = document.getElementById("check3");
correct = [];

function check() {
if (correctRes1.checked == true) {
  correct.push(result1);
}
if (correctRes2.checked == true) {
  correct.push(result1);
}
if (correctRes3.checked == true) {
  correct.push(result3);
}
}

raw = JSON.stringify({
question: question,
answer: [result1, result2, result3],
correctAns: correct,
});
console.log(raw)

the code above is not working. its not appending when I am calling the function.




samedi 25 avril 2020

How to toggle checkbox value in React Hooks?

I have an input type checkbox as follow:

const [is_checked,set_is_checked]= useState(false);

const toggle_payment = () => {
    set_is_checked(!is_checked);
    console.log(is_checked);
}


return(
    <div>
        <input checked={is_checked}  onChange={toggle_value} type="checkbox"/>
    </div>
)

The problem

This seems to work fine, But when I console.log(is_checked) it looks like it prints the previous value. I tried both onChange and onClick but got the same result. What confuses me is that the checkbox is getting checked / unchecked each time I click on the box, but the console.log prints different value than what expected to print, like when I check the box with the mouse click, the box got checked but the console.log prints false




Select All - CheckBoxes

I have a custom listview with two textviews and one checkbox and there is a separated checkbox outside of the listview named "Select All".

The Problems:

  1. When I click the "Select All" checkbox it check the checkboxes in the listview but when I hit "Done" button it is only gets the values of the items of the listview those can be seen in the screen (e.g in my device I can only see 7 items) and ignore the rest.
  2. When I click it again in order to uncheck the boxes it only uncheck those I can't see.

NOTE : By saying "those I can see or can't" I mean those are hidden down in the scrolling side. Yeah I can see them when I scroll up.

Help me to solve it.

  1. When I click the "Select All" checkbox - let it check those are in the listview and vise vasa.
  2. When I click the "Done" button - let it gets the value of all checked boxes.

BUT NOTE : This last problem only happens when I use the "Select All" functionality. But If I will check them one-by-one it gets all of the item values - which is contacts.

Thanks in advance!




Get values from a Reactive Form check box

Good, I am implementing a Reactive Form, but I have a problem getting the values from the checkbox, only the value of the first of the value I select appears and not the others. I attach my code:

Component.ts

registerForm: FormGroup;

  builder(
     private Restservice: RestserviceService,
     private route: ActivatedRoute,
     private router: Router,
     private formBuilder: FormBuilder
   ) {

     this.registerForm = this.formBuilder.group ({
       text: [""],
       checkArray: [""],
       radiobutton: [""],
       array: [""],
       list: [""],
       archive: [""],
       date: [""],
       numeric: [""],
       CommonData: [""],
     });
   }

// I show the values of the Form
  submit () {
     if (this.registerForm.valid) {
       console.log ("complete", this.registerForm.value);
       // this.createAnswers ();
     } else {
       alert ("FILL ALL FIELDS");
     }
   }

I use primeng's p-checkbox here but the problem is that it only recognizes the first value selected and the others don't.

 Html.

<div *ngIf="p.codigo_tipopreguntas == 2">
                            <ng-container *ngFor="let v of valores; let i=index">
                              <div *ngIf="p.id === v.codigo_pregunta">
                                  <p-checkbox  value=""
                                    label="" formControlName="checkbox"></p-checkbox>
                              </div>
                            </ng-container>
                          </div>

 <button class="btn btn-info btn-just-icon btn-round btn-link" pTooltip="Guardar" tooltipPosition="top"
              (click)="submit()">
              <i class="material-icons">remove_red_eye</i>
            </button>

attached picture of what the submit function prints




HTML how do a condition: if checkbox was ever changed

i have an html file like this:

<article class="question">
    <input id="revert" name ="revert" type="checkbox">
    <label for="revert">
        <section  class="front">
            <?php echo $question ?>
        </section>

        <section class="back">
            <?php echo $answer ?>
        </section>
    </label>
</article>

<form method="post">
    <input type=text name="reponse" placeholder="Ecrivez votre réponse ici"/>
    <input type=submit name="envoi_reponse" id="envoi_reponse_1" value="Envoyer"/>
</form>

i want to see in PHP, if the checkbox "revert" was changed or not, i don't want to see if it's checked, i need to know if it was ever changed. So if the user check it, and then uncheck then the condition = true

Maybe with some javascript ? I don't know js but i can try to use it, if it's not super hard




If first checkbox is checked , disable others based on condition

I have a page with a list of checkboxes with values. Each checkbox has data attributes with corresponding values. If the first checkbox is checked , I only want checkboxes whose data attributes are equal to the current checkbox's data attributes to remain selectable whilst all others are disabled.

I have got this working to a degree but if I uncheck any of the valid selected boxes, all the other checkboxes are enabled. I only want all other checkboxes to be enabled if I haven't got any valid ones selected.

HTML

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <label>Number:7967</label>
<input type="checkbox" class="my-check" data-number="7867" data-code="CB45" / >
 <label>Number:3307</label>
<input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" / >
 <label>Number:3307</label>
<input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" / >
 <label>Number:5645</label>
<input type="checkbox" class="my-check" data-number="5645" data-code="KLY" / >
</body>
</html>
$(function(){


    $(".my-check").each(function (e, elem) {
            $(elem).on("change", function () {
                var num = $(this).data("number");
                var co = $(this).data("code");
                if ($(this).eq(0).is(':checked')) {

                    $('.my-check:not([data-number=' + num + '])').attr('disabled', true);
                    $('.my-check:not([data-code=' + co + '])').attr('disabled', true);
                } else {
                    $(".my-check").not($(this)).attr('disabled', false);
                }

            });

        })

Sample code here




How to Update the parent component when child component updates in React

I have a child component that's basically four checkbox that has values from 1 to 4, so here's my problem, each time the user clicks on one of them it should pass the value to my api and it will return item's based on that value, the problem i'm facing is those i don't know how to pass those values to parent and i want the parent component to update each time the user clicks on one of the checkbox, the componentDidUpdate method works fine in the child component, but it doesn't have any effect on parent component, and here's what i do in child component:


class PriceRange extends React.Component {
    state = {
        checked5: false,
        checked6: false,
        checked7: false,
        checked8: false,
        checked9: false,
        FilterPrice: ''
    }
    componentDidUpdate() {
        localStorage.setItem("FilterPrice", this.state.FilterPrice)
        console.log(localStorage.getItem("FilterPrice"))
    }

    render() {
        const clearFilters = () => {
            this.setState({
                checked5: false,
                checked6: false,
                checked7: false,
                checked8: false,
                checked9: false,
                FilterPrice : null
            });
        }
        return (
            <div className="day-range price-range col-xl-12 col-lg-12 col-md-12 col-sm-6 col-12 ">
                <div className="title">
                    <div className="range">
                        <span>محدوده قیمت</span>
                    </div>
                    <div className="clear" onClick={clearFilters}>
                        <div className="icon">
                            <i className="fa fa-times" aria-hidden="true"></i>
                        </div>
                        <span> حذف فیلترها</span>
                    </div>
                </div>
                <div className="form-group">
                    <Checkbox
                        nativeControlId='5'
                        checked={this.state.checked5}
                        onChange={(e) => {
                            this.setState({
                                checked5: e.target.checked,
                                checked6: false,
                                checked7: false,
                                checked8: false,
                                checked9: false,
                                FilterPrice: 5
                            })

                        }

                        }
                        onClick={this.props.action}
                    />
                    <label htmlFor='5'>کمتر از 100,000 تومان</label>
                </div>
                <div className="form-group">
                    <Checkbox
                        nativeControlId='6'
                        checked={this.state.checked6}
                        onChange={(e) => {
                            this.setState({
                                checked6: e.target.checked,
                                checked5: false,
                                checked7: false,
                                checked8: false,
                                checked9: false,
                                FilterPrice: 6
                            })

                        }

                        }
                        onClick={this.props.action}
                    />
                    <label htmlFor='6'>از 100,000 تومان تا 200,000 تومان</label>
                </div>
                <div className="form-group">
                    <Checkbox
                        nativeControlId='7'
                        checked={this.state.checked7}
                        onChange={(e) => {
                            this.setState({
                                checked7: e.target.checked,
                                checked6: false,
                                checked5: false,
                                checked8: false,
                                checked9: false,
                                FilterPrice: 7
                            })

                        }

                        }
                        onClick={this.props.action}
                    />
                    <label htmlFor='7'>از 200,000 تومان تا 400,000 تومان</label>

                </div>
                <div className="form-group">
                    <Checkbox
                        nativeControlId='8'
                        checked={this.state.checked8}
                        onChange={(e) => {
                            this.setState({
                                checked8: e.target.checked,
                                checked6: false,
                                checked7: false,
                                checked5: false,
                                checked9: false,
                                FilterPrice: 8
                            })
                        }

                        }
                        onClick={this.props.action}
                    />
                    <label htmlFor='8'>از 400,000 تومان تا 600,000 تومان</label>
                </div>
                <div className="form-group">
                    <Checkbox
                        nativeControlId='9'
                        checked={this.state.checked9}
                        onChange={(e) => {
                            this.setState({
                                checked9: e.target.checked,
                                checked6: false,
                                checked7: false,
                                checked8: false,
                                checked5: false,
                                FilterPrice: 9
                            })

                        }

                        }
                        onClick={this.props.action}
                    />
                    <label htmlFor='9'>بیشتر از 600,000 تومان</label>
                </div>

            </div>
        )
    }



}

export default PriceRange;


and what i'm using for the parent component is something like this,

state = {
   priceRange:localStorage.getItem("FilterPrice")
}



componentDidUpdate(){
     if(this.state.priceRange==localStorage.getItem("FilterPrice")){
        console.log("same")

     }else{
         this.setState({priceRange:localStorage.getItem("FilterPrice")})
         console.log(this.state.priceRange)
     }  
}

so basically i have two questions here, how can i pass those values without using localstorage and how can i update the parent component whenever the user clicks on one of checkboxes?




vendredi 24 avril 2020

Can we group the check box in html

I have a basic question about html. I know when we are using radio button we can group several buttons by giving them the same "name" attribute, i.e. only one of them can be selected. e.g.:

<p> example
<input type="radio" name="example" value="option 1"> option 1
<input type="radio" name="example" value="option 2"> option 2
<input type="radio" name="example" value="option 3"> option 3</p>

So in the example, user can only choose one among option 1, option 2, option 3. My question is whether we can do the same thing for checkbox ? Thank you




check button in table field to select multiple rows (asp.net)

I searched the related questions and can't find something that works for me.

I have a page, where I have to fill in different text boxes (some mandatory, others not). One of them when you click opens a table that has different columns with data.

the first column is a button that selects the entire row, I would need that button to become a check so I can select multiple rows, not just one.

keep in mind that this is in javascript

This is the data that I must change:

 "<td><a href='#' class='btn btn-minier btn-inverse' onclick='return confirmarDato(" + '"' + est[i]._ID + '"' + "," + '"' + est[i]._DATO + '"' + ")'>Select</a> </td>" +



Why checkbox is not checking? (reactjs)

I have weird situation where my App component is working fine except for checking the checkbox, and the same App component, which I copy-paste in another project, is working totally fine. I created again new project with only App component, copy-pasted, same thing, everything is fine except checkbox. Can anyone explain to me what is going on here? How is it possible that the same component is working fine in one project and in others doesn't? And I restarted everything. So here is my code, just a simple to do list:

import React, { useRef, useReducer } from 'react'

function App() {

    const inputRef = useRef<HTMLInputElement>(null)

    const handleSubmit = (e: any) => {
        e.preventDefault()
        inputRef.current?.value !== "" && dispatch({ type: 'ADD_TODO', payload: inputRef.current?.value })
        inputRef.current && (inputRef.current.value = "")
    }

    const [todo, dispatch] = useReducer((state: any, action: any): any => {
        switch (action.type) {
            case 'ADD_TODO':
                return [...state, { id: state.length, name: action.payload, isCheck: false }]
            case 'CHECK_TODO':
                return state.filter((item: any, index: any):any => {
                    if (index === action.id) {
                        item.isCheck = !item.isCheck
                    }
                    return item
                })

        }
    }, [])

    const todos = todo.map((item: any, index: number) => {
        return (
            <li key={index}>
                <input type="checkbox" checked={item.isCheck} onChange={() => dispatch({ type: "CHECK_TODO", id: index })} />
                {item.name}
            </li>
        )
    })

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    placeholder="Buy milk"
                    ref={inputRef}
                />
            </form>
            <ul>{todos}</ul>
        </div>
    )
}

export default App

here, in some old project is working fine, I can check it and uncheck it: enter image description here

here, in any other new project is not working at all:

enter image description here

I didn't do anything unusual, created it with npx create-react-app . --template typescript

EDIT

Here is console log with snippet when clicked on checkbox 'eggs' (don't know why is it rendering twice, in project that works it's rendering only once):

case 'CHECK_TODO':
    return state.filter((item: any, index: any): any => {
        if (index === action.id) {
            item.isCheck = !item.isCheck
            console.log('click')
            console.log(`${index} === ${action.id}`)
            console.log(item.isCheck)
        }
        return item
    })

enter image description here




How to make a "link" from CheckboxlistTile to another page on Flutter

I'm making a Terms and Conditions agreement and I want this sentence to be highlighted and clickable, when clicked it should take the user to another page in the app where they can read the agreement. I'm having trouble creating something that's both clickable and higlighted.



     CheckboxListTile(
        value: checkboxValue,
      onChanged: (val) {
        if (checkboxValue == false) {
          setState(() {
            checkboxValue = true;
          });
        } else if (checkboxValue == true) {
          setState(() {
            checkboxValue = false;
          });
        }
      },
      subtitle: !checkboxValue
          ? Text(
              'Required.',
              style: TextStyle(color: Colors.red),
            )
          : null,
      title: new Text(
        'I agree to the Terms and Conditions.',
        style: TextStyle(fontSize: 14.0),
      ),
      controlAffinity: ListTileControlAffinity.leading,
      activeColor: Colors.green,
    ),
    ```





How to show the text of the selected checkbox in a Toast?

I have tried this:

public void onCheckboxClicked(View view) {
    // La view è checked?
    boolean checked = ((CheckBox) view).isChecked();
    // Seleziona quale casella di controllo selezionare
    switch (view.getId()) {
        case R.id.checkBox:
            if (checked)
                Toast.makeText( getApplicationContext(), "Hai selezionato: " + checkBox.getText(), Toast.LENGTH_SHORT ).show();}

But I get this error:

java.lang.IllegalStateException: Could not execute method for android:onClick

The OnClick method is missing, but how can I use it together with the onCheckboxClicked method? Sorry I'm a beginner. Thanks




Bootstrap toggle checkbox not working on alternate page load

I am using bootstrap toggle checkbox. Following css and js included

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

I am creating checkbox like this

<input type="checkbox"  id="currentSeason"  name="currentSeason" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-size="small">

But toggle checkbox is getting checked on alternate page load means when i open page it works and then i open same page again, it doesn't work.




How to check all the checkboxes by a single click?

I have a list of items in my Recyclerview. At first, the checkbox is not visible.When I longclick on any item, checkbox appears on each item and it can be checked . But how to provide SELECT ALL option and check all the checkboxes by a single click?

Here is my Adapter class

package adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mynotes.R;

import java.util.ArrayList;
import java.util.List;

import callbacks.NoteEventListener;
import model.Note;
import utils.NoteUtils;

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteHolder> {
    private Context context;
    private ArrayList<Note> notes;
    private NoteEventListener listener;
    private boolean multiCheckMode = false;


    public NotesAdapter(Context context, ArrayList<Note> notes) {
        this.context = context;
        this.notes = notes;
    }


    @NonNull
    @Override
    public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.note_layout, parent, false);
        return new NoteHolder(v);
    }

    @Override
    public void onBindViewHolder(NoteHolder holder, int position) {
        final Note note = getNote(position);
        if (note != null) {
            holder.noteText.setText(note.getNoteText());
            holder.noteDate.setText(NoteUtils.dateFromLong(note.getNoteDate()));
            // init note click event
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    listener.onNoteClick(note);
                }
            });

            // init note long click
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    listener.onNoteLongClick(note);
                    return false;
                }
            });

            // check checkBox if note selected
            if (multiCheckMode) {
                holder.checkBox.setVisibility(View.VISIBLE); // show checkBox if multiMode on
                holder.checkBox.setChecked(note.isChecked());
            } else holder.checkBox.setVisibility(View.GONE); // hide checkBox if multiMode off

        }
    }

    @Override
    public int getItemCount() {
        return notes.size();
    }

    private Note getNote(int position) {
        return notes.get(position);
    }


    /**
     * get All checked notes
     *
     * @return Array
     */
    public List<Note> getCheckedNotes() {
        List<Note> checkedNotes = new ArrayList<>();
        for (Note n : this.notes) {
            if (n.isChecked())
                checkedNotes.add(n);
        }

        return checkedNotes;
    }


    class NoteHolder extends RecyclerView.ViewHolder {
        TextView noteText, noteDate;
        CheckBox checkBox;

        public NoteHolder(View itemView) {
            super(itemView);
            noteDate = itemView.findViewById(R.id.note_date);
            noteText = itemView.findViewById(R.id.note_text);
            checkBox = itemView.findViewById(R.id.checkBox);
        }
    }


    public void setListener(NoteEventListener listener) {
        this.listener = listener;
    }

    public void setMultiCheckMode(boolean multiCheckMode) {
        this.multiCheckMode = multiCheckMode;
        if (!multiCheckMode)
            for (Note note : this.notes) {
                note.setChecked(false);
            }
        notifyDataSetChanged();
    }
}

MainActivity

package com.example.mynotes;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import adapters.NotesAdapter;
import callbacks.MainActionModeCallback;
import callbacks.NoteEventListener;
import db.NotesDB;
import db.NotesDao;
import model.Note;


import static com.example.mynotes.EditNoteActivity.NOTE_EXTRA_Key;

public class MainActivity extends AppCompatActivity implements NoteEventListener {
    private static final String TAG = "MainActivity";
    private RecyclerView recyclerView;
    private ArrayList<Note> notes;
    private NotesAdapter adapter;
    private NotesDao dao;
    private MainActionModeCallback actionModeCallback;
    private int chackedCount = 0;
    private FloatingActionButton fab;
    private SharedPreferences settings;
    public static final String THEME_Key = "app_theme";
    public static final String APP_PREFERENCES="notepad_settings";
    private int theme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        theme = settings.getInt(THEME_Key, R.style.AppTheme);
        setTheme(theme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        settings = this.getSharedPreferences("My Data", MODE_PRIVATE);


        // init recyclerView
        recyclerView = findViewById(R.id.notes_list);


        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // add new note
                onAddNewNote();
            }
        });

        dao = NotesDB.getInstance(this).notesDao();
    }


    private void loadNotes() {
        this.notes = new ArrayList<>();
        List<Note> list = dao.getNotes();// get All notes from DataBase
        this.notes.addAll(list);

        String mSortSettings = settings.getString("Sort", "ascending");
        if (mSortSettings.equals("ascending"))  {

                Collections.sort(notes, Note.BY_TITLE_ASCENDING);

        }

        else if (mSortSettings.equals("descending")) {

                Collections.sort(notes, Note.BY_TITLE_DESCENDING);

        }

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        this.adapter = new NotesAdapter(this, this.notes);
        // set listener to adapter
        this.adapter.setListener(this);

        this.recyclerView.setAdapter(adapter);
        showEmptyView();

        // add swipe helper to recyclerView
        swipeToDeleteHelper.attachToRecyclerView(recyclerView);
    }

    /**
     * when no notes show msg in main_layout
     */
    private void showEmptyView() {
        if (notes.size() == 0) {
            this.recyclerView.setVisibility(View.GONE);
            findViewById(R.id.empty_notes_view).setVisibility(View.VISIBLE);

        } else {
            this.recyclerView.setVisibility(View.VISIBLE);
            findViewById(R.id.empty_notes_view).setVisibility(View.GONE);
        }
    }

    /**
     * Start EditNoteActivity.class for Create New Note
     */
    private void onAddNewNote() {
        startActivity(new Intent(this, EditNoteActivity.class));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_sort) {
            showSortDialog();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



    private void showSortDialog () {
        String[] options = {"Ascending", "Descending"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Sort by");

        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (which == 0) {
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("Sort", "ascending");
                    editor.apply();
                    loadNotes();

                }
                else if (which == 1) {
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("Sort", "descending");
                    editor.apply();
                    loadNotes();

                }
            }
        });
        builder.show();
    }



    @Override
    protected void onResume() {
        super.onResume();
        loadNotes();
    }

    @Override
    public void onNoteClick(Note note) {
        // note clicked : edit note
        Intent edit = new Intent(this, EditNoteActivity.class);
        edit.putExtra(NOTE_EXTRA_Key, note.getId());
        startActivity(edit);

    }

    @Override
    public void onNoteLongClick(Note note) {
        // note long clicked : delete 

        note.setChecked(true);
        chackedCount = 1;


        adapter.setMultiCheckMode(true);

        // set new listener to adapter intend off MainActivity listener that we have implement
        adapter.setListener(new NoteEventListener() {
            @Override
            public void onNoteClick(Note note) {


                note.setChecked(!note.isChecked()); // inverse selected
                if (note.isChecked())
                    chackedCount++;
                else chackedCount--;


                if (chackedCount == 0) {
                    //  finish multi select mode wen checked count =0
                    actionModeCallback.getAction().finish();
                }

                actionModeCallback.setCount(chackedCount + "/" + notes.size());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onNoteLongClick(Note note) {

            }
        });

        actionModeCallback = new MainActionModeCallback() {
            @Override
            public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.action_delete_notes)
                    onDeleteMultiNotes();

                actionMode.finish();
                return false;

            }
        };

        // start action mode
        startActionMode(actionModeCallback);
        // hide fab button
        fab.setVisibility(View.GONE);
        actionModeCallback.setCount(chackedCount + "/" + notes.size());
    }

    private void onDeleteMultiNotes() {
        //delete multi notes

        List<Note> chackedNotes = adapter.getCheckedNotes();
        if (chackedNotes.size() != 0) {
            for (Note note : chackedNotes) {
                dao.deleteNote(note);
            }
            // refresh Notes
            loadNotes();
            Toast.makeText(this, chackedNotes.size() + " Note(s) Deleted successfully !", Toast.LENGTH_SHORT).show();
        } else Toast.makeText(this, "No Note(s) selected", Toast.LENGTH_SHORT).show();

        adapter.setMultiCheckMode(false);
    }

    @Override
    public void onActionModeFinished(ActionMode mode) {
        super.onActionModeFinished(mode);

        adapter.setMultiCheckMode(false); // uncheck the notes
        adapter.setListener(this); // set back the old listener
        fab.setVisibility(View.VISIBLE);
    }

    // swipe to right or to left to delete
    private ItemTouchHelper swipeToDeleteHelper = new ItemTouchHelper(
            new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    //  delete note when swipe

                    if (notes != null) {
                        // get swiped note
                        Note swipedNote = notes.get(viewHolder.getAdapterPosition());
                        if (swipedNote != null) {
                            swipeToDelete(swipedNote, viewHolder);

                        }

                    }
                }
            });

    private void swipeToDelete(final Note swipedNote, final RecyclerView.ViewHolder viewHolder) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage("Delete Note?")
                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // delete note
                        dao.deleteNote(swipedNote);
                        notes.remove(swipedNote);
                        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
                        showEmptyView();

                        Toast.makeText(MainActivity.this, "Note deleted", Toast.LENGTH_SHORT).show();

                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // TODO: 28/09/2018  Undo swipe and restore swipedNote
                        recyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());

                    }
                })
                .setCancelable(false)
                .create().show();

    }
}

Model class

package model;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;

import java.util.Comparator;

@Entity(tableName = "notes")
public class Note {
    @PrimaryKey(autoGenerate = true)
    private int id; // default value
    @ColumnInfo(name = "text")
    private String noteText;
    @ColumnInfo(name = "date")
    private long noteDate;

    @Ignore // we don't want to store this value on database so ignore it
    private boolean checked = false;

    public Note() {
    }


    public static final Comparator<Note> BY_TITLE_ASCENDING = new Comparator<Note>() {
        @Override
        public int compare(Note o1, Note o2) {

            return o1.getNoteText().compareTo(o2.getNoteText()) ;
        }
    };

    public static final Comparator<Note> BY_TITLE_DESCENDING = new Comparator<Note>() {
        @Override
        public int compare(Note o1, Note o2) {

            return o2.getNoteText().compareTo(o1.getNoteText()) ;
        }
    };



    public Note(String noteText, long noteDate) {
        this.noteText = noteText;
        this.noteDate = noteDate;
    }

    public String getNoteText() {
        return noteText;
    }

    public void setNoteText(String noteText) {
        this.noteText = noteText;
    }

    public long getNoteDate() {
        return noteDate;
    }

    public void setNoteDate(long noteDate) {
        this.noteDate = noteDate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    @Override
    public String toString() {
        return "Note{" +
                "id=" + id +
                ", noteDate=" + noteDate +
                '}';
    }
}

Please help me with this




jeudi 23 avril 2020

JQuery | How to display variables when associated checkbox is checked

I'm creating a website that grabs weather information based on the location entered by the user. At the moment there are some features on the page with no functionality, it is still a work in progress. I apologies for the sloppy code.

I have 9 checkboxes at the top of my form that have the info that should be displayed and I'm not sure of the best method to edit the output accordingly.

$(document).ready(function() {
  var inputType = 1;

  $("#Radio1").click(function() {
    $("#lbl1").text("City Name:");
    $("#lbl2").text("Country Code:");
    $("#Firstbox").removeAttr("min max step");
    $("#Secondbox").removeAttr("min max step");
    document.getElementById('Firstbox').value = '';
    document.getElementById('Secondbox').value = '';


    $("#Firstbox").attr({
      "type": "text",
      "pattern": "[a-zA-Z]{2,}",
      "placeholder": "Regina"
    });

    $("#Secondbox").attr({
      "type": "text",
      "pattern": "[a-zA-Z]{2}",
      "placeholder": "ca"
    });

    inputType = 1;
  });

  $("#Radio2").click(function() {
    $("#lbl1").text("Postal Code:");
    $("#lbl2").text("Country Code:");
    $("#Firstbox").removeAttr("min max step");
    $("#Secondbox").removeAttr("min max step");
    document.getElementById('Firstbox').value = '';
    document.getElementById('Secondbox').value = '';

    $("#Firstbox").attr({
      "type": "text",
      "pattern": "[A-Z][0-9][A-Z]",
      "placeholder": "S4X"
    });

    $("#Secondbox").attr({
      "type": "text",
      "pattern": "[a-zA-Z]{2}",
      "placeholder": "ca"
    });

    inputType = 2;
  });

  $("#Radio3").click(function() {
    $("#lbl1").text("Latitude:");
    $("#lbl2").text("Longitude:");
    $("#Firstbox").removeAttr("pattern");
    $("#Secondbox").removeAttr("pattern");
    document.getElementById('Firstbox').value = '';
    document.getElementById('Secondbox').value = '';

    $("#Firstbox").attr({
      "type": "number",
      "min": "-90",
      "max": "90",
      "step": "any",
      "placeholder": "50.4"
    });

    $("#Secondbox").attr({
      "type": "number",
      "min": "-180",
      "max": "180",
      "step": "any",
      "placeholder": "-105.5"
    });

    inputType = 3;
  });

  $("#SearchButton").click(function() {
    if (checkValidity()) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var SearchResponse = this.responseText;

          var obj = JSON.parse(SearchResponse);
          var city_name = obj["name"];
          var country_name = obj["sys"]["country"];
          var longitude = obj["coord"]["lon"];
          var latitude = obj["coord"]["lat"];
          var weather_description = obj["weather"][0]["description"];
          var temp = obj["main"]["temp"] - 273.15;
          var pressure = obj["main"]["pressure"];
          var humidity = obj["main"]["humidity"];
          var wind_speed = obj["wind"]["speed"];
          var wind_direction = obj["wind"]["deg"];
          var sunrise = new Date(obj["sys"]["sunrise"] * 1000);
          var sunset = new Date(obj["sys"]["sunset"] * 1000);

          var SearchResultsHTML = "City: " + city_name + "<br />" +
            "Country: " + country_name + "<br />" +
            "Longitude: " + longitude + "<br />" +
            "Latitude: " + latitude + "<br />" +
            "Weather: " + weather_description + "<br />" +
            "Temperature: " + temp + "<br />" +
            "Pressure: " + pressure + "<br />" +
            "Humidity: " + humidity + "<br />" +
            "Wind Speed: " + wind_speed + "<br />" +
            "Wind Direction: " + wind_direction + "<br />" +
            "Sunrise: " + sunrise.toLocaleTimeString() + "<br />" +
            "Sunset: " + sunset.toLocaleTimeString() + "<br />";

          $("#SearchResults").html(SearchResultsHTML);
        }
      }



      var Firstbox = $("#Firstbox").val();
      var Secondbox = $("#Secondbox").val();

      var apiKey = "52453f34dee0d65b1a41a02656142c6b";

      if (inputType == 1) {
        var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
          "?q=" + Firstbox + "," + Secondbox +
          "&APPID=" + apiKey;
      } else if (inputType == 2) {
        var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
          "?zip=" + Firstbox + "," + Secondbox +
          "&APPID=" + apiKey;
      } else if (inputType == 3) {
        var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
          "?lat=" + Firstbox + "&lon=" + Secondbox +
          "&APPID=" + apiKey;
      }

      xhttp.open("GET", SearchString, true);
      xhttp.send();
    }
  });

  function displayError() {
    var first = document.getElementById('Firstbox');
    var second = document.getElementById('Secondbox');

    if (first.validity.valid) {
      if (inputType == 1 || inputType == 2) {
        alert("Country code must be 2 characters in length.");
      } else {
        alert("Longitude must be between -180 and 180");
      }
    } else {
      if (inputType == 1) {
        alert("City name must be longer than 1 character.");
      } else if (inputType == 2) {
        alert("Postal code must be 3 characters in length, following the format 'S4X'");
      } else {
        alert("Latitude must be between -90 and 90");
      }
    }
  }

  function checkValidity() {
    var first = document.getElementById('Firstbox');
    var second = document.getElementById('Secondbox');

    if (first.validity.valid && second.validity.valid) {
      return true;
    } else {
      displayError();
      return false;
    }
  }

  function checksSelected() {

  }
});
.validated:valid {
  background-color: #BDF0A8;
}

.validated:invalid {
  background-color: #FAC3C9;
}

.row {
  margin-bottom: 10px;
}

.ticksel {
  border: solid black 1px;
}

tr,
td {
  border: solid black 1px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="weather.css">

<form id="searchForm" method="POST" action="URL">
  <div class="row col-md-12">
    <h2>OpenWeatherMap Weather Search</h2>
  </div>
  <div class="row">
    <div class="col-md-6">
      <h4>Search by:</h4>
      <input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
      <input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
      <input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
    </div>
    <div class="col-md-6">
      <h4>Show in search results:</h4>

      <div class="row">
        <div class="col ticksel"><input type="checkbox" checked id="" value="yes"> Longitude</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Latitude</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Temperature</div>
      </div>
      <div class="row">
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Pressure</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Humidity</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Speed</div>
      </div>
      <div class="row">
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Direction</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunrise</div>
        <div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunset</div>
      </div>

    </div>
  </div>
  <div class="row col-md-12">
    <label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" placeholder="Regina" />
    <label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" placeholder="ca" />
    <input id="SearchButton" type="button" value="Search" />
  </div>
</form>

<div class="row col-md-12">
  <h4>Current Weather</h4>
</div>
<div class="row col-md-12">
  <p id="SearchResults"></p>
</div>

<div class="row col-md-12">
  <table width="100%">
    <thead>
      <tr>
        <th>City</th>
        <th>Country</th>
        <th>Longitude</th>
        <th>Latitude</th>
        <th>Weather</th>
        <th>Temperature</th>
        <th>Pressure</th>
        <th>Humidity</th>
        <th>Wind Speed</th>
        <th>Wind Direction</th>
        <th>Sunrise</th>
        <th>Sunst</th>
        <th><a class="deleteAll" href="#">Clear Log</a></th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>