dimanche 31 mars 2019

Using checkbox and sliders in slide menu (in Drawer), is it possible?

I'm trying to add widgets inside a slide menu in flutter, I don't know if it's possible or not. I want to use the slide menu as filter selection page for a search page.




how i can add dynamicly checkbox with checkbox array and difrent index and use in jquery

i have this codes and i want to add checkbox according to fetched number from database and each checkbox has a Proprietary row in another table so when i show this code in browser,browser set status checkbox 1 for all checkbox(each checkbox has a 2 status 0 and 1) so i tried to make a array for my fetched checkbox and i have to send checkbox changes to php code with jquery and save in db but i cannt write a useful code for solve this problem any body can help me or edit my code?

$conn = mysqli_connect('localhost', 'root', '', 'win');
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$lights = $row['lights'];
$sql1 = "SELECT * FROM `lights` WHERE id='1'";
$result1 = mysqli_query($conn, $sql1);
$row1 = mysqli_fetch_assoc($result1);
$bord_number = $row1['bord_number'];
$i = 0;
$checkbox[0] = "<label class=\"switch\">
            <input type=\"checkbox\">
            <span class=\"slider round\"></span>
            </label></br>";
$checkbox[1] = "<label class=\"switch\">
            <input type=\"checkbox\" checked=\"checked\">
            <span class=\"slider round\"></span>
            </label></br>";

?>
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="mysty.css">
 <script src="../js/ajax.js"></script>
    <script>
        $(document).ready(function () {
            $('#mycheckbox').change(function () {
                var returnVal = ("Are " + "you sure?");
                if (returnVal) {
                    postToServer($(this).prop("checked"));

                } else {
                    $(this).prop("checked", !$(this).is(":checked"));
                }
            });

            function postToServer(state) {
                let value = (state) ? 1 : 0;
                //alert('Posted Value: ' + value);
                $.ajax({
                    type: 'POST',
                    url: 'checkbox.php',
                    data: {'value': +value},
                    success: function (response) {
                        //handle response
                    }
                });
            }
        });
</head>
<body>
<div>
    <?php
    while ($row1 = mysqli_fetch_assoc($result1)) {
        $status = $row1['status'];
        $bord_number = $row1['bord_number'];


        while ($i < $lights) {

            if ($status < '1') {
                echo $checkbox[0];

            } else {
                echo $checkbox[1];

            }
            $i++;

        }
    }

    ?>
</div>
</body>
</html>




DYNAMIC UI CONTROL CREATION FAILING IN UWP APP

My UWP app running on Windows 10 has custom Profile fields (either Text, checkboxes, multi select check boxes, radio buttons) which can be set from web end. Thus, the api call gets the question type object in response, and dynamic UI controls are to be created in StackPanel. Everything is just working fine in all laptops except some dell laptops (reported by client). Whenever profile fields included checkbox, radio button or rating control, the StackPanel creation fails and the page comes as blank, while when the question type is TextBlock, magic happens and it's created. How??? The moment my for loop reaches custom fields (not textblock type), it fails. Error: Unspecified Error 0x80004005. Windows version 1709 (OS Build 16299.904) Dell laptop versions: Dell Latitude E5470 and a Dell Latitude E7470




I cant store checkbox value into session

I am trying to put checkbox value into session. when i am trying to save it .it save the name field of the checkbox like foo[].

i am using larave . i am new in laravel.

<ul class="check-square"> 
<?php Session::put('selectsubservice','selectsubservice[]'); ?> @foreach($subservices as $subservice)
 <li><input type="checkbox" name="selectsubservice[]" value=""></li> 
@endforeach 
</ul> 





samedi 30 mars 2019

How to increase clickable area of checkbox for touch screen

I'm trying to increase the clickable area for a checkbox in label.

However, there are also 2 anchor tags in it, and when I try to click on the checkbox on tablet, I get redirected to the hyperlink because the clickable area for checkbox is small, but the area for anchor tag is bigger.

I need to make both of them clickable on tablet, but be able to click on the checkbox too.

Here is the current layout. Since I also can't address :before as a DOM element on jQuery, I can't also modify it. Is there any recommendations ?

[type="checkbox"]:not(:checked)+label:before,
[type="checkbox"]:checked+label:before {
    content: '';
    position: absolute;
    left: 0;
    top: 1px;
    width: 16px;
    height: 16px;
    border: 1px solid #000;
    background: transparent;
}




Why using command switch with a variable inside returns empty variable when using a windows form?

i've made a wimdowsform with checkboxes in powershell.

i use switch command to make check/uncheck. it works like i want. If we check a checkbox i add a variable but it's still empty.

...
$checkbox_un.Add_CheckStateChanged(
{
switch ($checkbox_un.Checked) {
    $false { $checkbox_deux.enabled=$true; $checkbox_deux.Checked=$False; break }
    $true { $checkbox_deux.Enabled=$False; $checkbox_deux.Checked=$False; $fs="FAT32"; break }
    }

})
$checkbox_deux.Add_CheckStateChanged(
{
switch ($checkbox_deux.Checked) {
    $false { $checkbox_un.Enabled=$true; $checkbox_un.Checked=$False; break }
    $true { $checkbox_un.Enabled=$false; $checkbox_un.Checked=$false; $fs="NTFS"; break }
    }

})
...

$fs returns always empty , i don't understand why ?




vendredi 29 mars 2019

how add checkbox according to while loop and database

i have this codes and i have a table in db i want to add checkbox according to fetched number from database if db number is 4 add 4 checkbox and i have css codes to change checkbox to toggle switch my codes work for checkbox without css code but not work when css codes work and when css code is excuted i can't checked or unchecked I think this is a problem with my php code my how i can solve this problem to work my query code is:enter image description here

enter image description here enter image description here




for="" is checking multiple inputs

There is not much to say about this... Its really weird... I have some <label> tags they contain <input> from type checkbox. Every label have an unique for that is bindet do the same named inputs id.. I did it exactly like w3c on the demo site: https://www.w3schools.com/howto/howto_css_custom_checkbox.asp

Demo: https://stackblitz.com/edit/angular-fzbvx5




How to add checkboxes with Javascript dynamically

Trying to insert dynamic checkboxes and collection elements from Materializecss site to my html using document.createElement() (as many checkboxes as my names in a loop - each name should have own checkbox).

My questions:

1) It works with collections but checkboxes do not appear in my sidebar.

2) Do I need a different ID and For attributes for each checkbox?

3) I want to use values gotten from checkboxes and correspondent names. For that I have to place names in a <span> tag of checkboxes here:

    <label>
    <input type="checkbox" class="filled-in" checked="checked" />
    <span>Filled in</span>
    </label>

But I want to keep names in this Collection tags rather than in checkboxes tags because a) it looks great b) I want to have links on names in a way I have now.

 <div class="collection">
    <a href="#!" class="collection-item">Alvin</a>
  </div>

The question is will I be able to read corresponding values from 2 different elements?

             
            //collection element from Materializecss site
             var collection = document.getElementById("coll")
             
             //form element from Materializecss site
             var form = document.getElementById("form")
    
             for (var i = 0; i < names.length; i++) {
    
                 //getting each name
                 var name = names[i]                     
                
                 //creates a label tag for each checkbox
                 var newLabelTag = document.createElement("LABEL") 
                   
                 newLabelTag.setAttribute("for", "item"); 
                 
                 //add item to the mother collection element
                 form.appendChild(newLabelTag);
                 
                 
                 
                 //creates a span tag for each checkbox
                 var newSpanTag = document.createElement("SPAN")                  
              
                 // Add names to it
                 var Text = document.createTextNode(name);
                 
                 //new line
                 var br = document.createElement("BR");
                 
                 newSpanTag.appendChild(br);
                 
                 //append the text with names to the tag
                 newSpanTag.appendChild(Text);
                 
                 //add item to the mother collection element
                 form.appendChild(newSpanTag);
                 
                 
                 
                 //creating a new <input> tag
                 var newInputTag = document.createElement("INPUT") 
                 
                 //set a class to a new tag
                 newInputTag.setAttribute("class", "filled-in");
                 
                 newInputTag.setAttribute("id", "item");
                 
                 newInputTag.setAttribute("type", "checkbox");                 
                              
                 //add item to the mother collection element
                 form.appendChild(newInputTag);
                 
                 
                 
                 //creating a new <a> tag (Collection items)
                 var newATag = document.createElement("A") 
                 
                 //set a class to a new tag
                 newATag.setAttribute("class", "collection-item");
                 
                 // add the URL attribute
                 newATag.setAttribute("href", "https//blah");
                 
                 // Add names to it
                 var newText = document.createTextNode(name);
                 
                 //append the text with names to the tag
                 newATag.appendChild(newText);
                 
                 //add item to the mother collection element
                 collection.appendChild(newATag);

    }



How to display multiple checkboxes both horizontally and vertically css

I'm trying to set a collection of checkboxes both horizontally and vertically, but they don't come out uniformally. The labels for each checkbox can vary in size, e.g. one label for a checkbox says "International Casaulty Treaty" whereas another only says WIP.

I was going over this vertical example here. http://jsfiddle.net/zcuLgbxt/

How to can I neatly arrange them so they are all in alignment both vertically and horizontally? Thanks very much in advance!

Here is my simple HTML/CSS

<!DOCTYPE html>
<html>

<head>
<title>Filters 16</title>
</head>

<style>
li {
    margin: 5px;
}

input {
    width: 20px;
    background-color: blue;

    position: relative;
    left: 200px;

    vertical-align: middle;
}

.vertical-list {
    width: 200px;


    position: relative;
    left: -20px;

    display: inline-block;
    vertical-align: middle;
}


li{


    list-style:none;

    }

.horizontal-list{

    display: inline;

    }


</style>

<body>

<center>    
<ul>        
    <li>
        <input type="checkbox" value="1" name="test[]" id="myid1">
        <label  class="vertical-list"for="myid1"> label1  label1  label1</label>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label class="horizontal-list" for="myid2">label2</label>
    </li>
    <li>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label class="vertical-list" for="myid2">label2label2label2</label>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label class="horizontal-list" for="myid2">label2label2</label>

    </li>

    <li>
        <input type="checkbox" value="4" name="test[]" id="myid3">
        <label class="vertical-list" for="myid1"> label4  label4  label4</label>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label class="horizontal-list" for="myid2">label2</label>
    </li>
</ul>


</center>




How to create checkboxes in a html/css table where header and the first column is pulled from the mysql database?

I'm working on creating a html and css checklist table, I have populated the header and the first column from a mysql database using for loops. How do I create checkboxes for the rest of the columns?

Here's the code:

schema-functions.php

class Schema{

public function getCourse(): ?array {
    $objectArray = array();
    $conn = DatabaseConnection::getConnection();
    $stmt = $conn->prepare('SELECT * FROM Course');
    if ($stmt->execute()) {
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($objectArray, Factory::createCourse($result['commonName'], $result['courseId'], $result['courseNumber'], $result['subjectCode'], $result['yearGiven']));
        }
        return $objectArray;
    } else {
        return null;
    }


public function getObjective(): ?array {
    $objectArray = [];
    $conn = DatabaseConnection::getConnection();
    $stmt = $conn->prepare('SELECT * FROM Objective ORDER BY objectiveId ASC');
    if ($stmt->execute()) {
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($objectArray, Factory::createObjective($result['objective'], $result['objectiveId']));
        }
        return $objectArray;
    } else {
        return null;
    }
}

}

table.php

<?php
require_once 'pages/header.php';
require_once './functions/schema-functions.php';

$course = Schema::getCourse();
$objective = Schema::getObjective();
?>




        <table id="table1">

  <thead>
     <tr> 
         <th>Objectives</th>
    <?php     
       for ($i = 0; $i < count($course); $i++) {               
         echo"           

  <th id='rotate1'> {$course[$i]->commonName} </th>

  ";    
 } 

?>
</tr>

  </thead>
  <tbody>
      <tr>
  <td>
    <?php     
 for ($i = 0; $i < count($objective); $i++) {               
             echo"           
    <tr>
          <th class=row-header> {$objective[$i]->objective} </th>
           <td><input name=column3[] type=checkbox value=row1-column3></td> 
    </tr>  ";
     } 

 ?>


main.css

#rotate1 {
  transform: 

    rotate(315deg);
  width: 2%;

    }


#th.row-header {
padding: 0 10px;
border-bottom: 2px solid #ccc;
height: 50px;
 border-top: 1px solid #ddd;
  } 


#table1{    
 border:2px solid #ddd!important;
 border-collapse: collapse;
 font-size: 14px;
 font-family: "Times New Roman", Times, serif;

  }

#table1 tbody{
  display:block;
  width: 100%;
  overflow: auto;
  height: 1000px;
  }

I'm stuck at creating two things - the checkboxes and I want to fix the header with the web page as it scrolls down. Currently the header is fixed to the table.




Uncheck radiofield

I need to click on a radiofield and check it, click another time on the same radiofield and uncheck it.

My code doesen't work because the getChecked() is always true! This is my function, triggered on click event

                        listeners: {
                            click: {
                                element: 'element',
                                fn: function (event, target) {
                                    var radioField = this.component;
                                    if (radioField.getChecked()) {
                                        radioField.setChecked(false);
                                    }
                                    else {
                                        radioField.setChecked(true);
                                    }
                                }
                            }
                        },




jeudi 28 mars 2019

how to get selected checkboxes

I am using Checkbox in MVC my CShtml is like this :

List mylist1 = ViewBag.hobbies;

foreach (var h in mylist1)
{
                <tr>
                    <input type="checkbox" name="hobbies" value="@h.Hobbie" class="checkboxTwo" style="background-color:aliceblue" />@h.Hobbie

                </tr>
}

Now i want check box list checked in Edit mode .

In Edit Mode of Controller i written this code:

public ActionResult Edit(int? id)

    {
        TestEntities db = new TestEntities();
        ViewBag.hobbies = db.hobbies.ToList();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        string[] times = (employee.hobbies).Split(',');
      //  string hobbies = collection["hobbies"];
       // collection["hobbies"] = string hobbies;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var item in employee.hobbies)
        {

            if (item)
            {
                //append each checked records into StringBuilder
                sb.Append(item + ",");

            }


        }

public ActionResult Edit(int? id)

    {
        TestEntities db = new TestEntities();
        ViewBag.hobbies = db.hobbies.ToList();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        string[] times = (employee.hobbies).Split(',');
      //  string hobbies = collection["hobbies"];
       // collection["hobbies"] = string hobbies;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var item in employee.hobbies)
        {

            if (item)
            {
                //append each checked records into StringBuilder
                sb.Append(item + ",");

            }


        }

M expecting checkbox list get checked in Edit Modeenter image description here




WPF checkbox event is not firing when I install my program in some Windows environment

Until now, There are many times I installed this program. checkbox event firing well in all Window 10 environment. But, in recent environment, checkbox not firing. Recent Enviroment is also Window 10. why checkbox event not firing?

  • xaml.cs

    private void checkBox1_Checked(object sender, RoutedEventArgs e)
    {
        //code..
    }
    
    
  • xaml

    <CheckBox Content="test1" Foreground="White" Height="16" 
    HorizontalAlignment="Left" Margin="459,-29,0,0"
    Name="checkBox1" 
    VerticalAlignment="Top" 
    IsThreeState="True" 
    Checked="checkBox1_Checked" Unchecked ="checkBox1_Unchecked" 
    Indeterminate="checkBox1_Indeterminate"/>
    
    



Android some problem with check box while displaying

Some times randomly tick mark i missing when moving from one fragment to another fragment(The checkbox values are true i can see blue color only tik mark is missing). enter image description hereenter image description here




Set checkbox validation if checkbox unchecked

In my Angular 6 application's register form, I have a checkbox which is already checked. I need to check whether the user has unchecked the checkbox and if it is so I want to display an error message.

This is my checkbox in .html file,

 <div class="form-group">
       <div class="round">
            <input
                  type="checkbox"
                  id="checkbox33"
                  formControlName="agree">
             <label for="checkbox33"></label>
        </div>
        <small class="text-muted">Agree to our <a href="#" class="link">Terms
                  Of Use</a> and <a href="#" class="link">Privacy Policy</a>.
                </small>
        <span *ngIf="!worldWideRegisterForm.get('agree').valid" class="text-danger">You should agree!</span>

  </div>

This is my ngOnInit() in .ts file

ngOnInit() {
    this.worldWideRegisterForm = new FormGroup({
      'userName': new FormGroup({
        firstName: new FormControl(null, Validators.required),
        lastName: new FormControl(null, Validators.required)
      }),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'phone': new FormControl(null, Validators.required),
      'address': new FormGroup({
        line1: new FormControl(null, Validators.required),
        line2: new FormControl(null),
      }),
      'area': new FormGroup({
        'province': new FormControl(null, Validators.required),
        'city': new FormControl(null, Validators.required),
        'postalCode': new FormControl(null, Validators.required),
      }),
      'password': new FormControl(null, [Validators.required, Validators.minLength(6)]),
      'agree': new FormControl(true, Validators.required)
    });
  }




mercredi 27 mars 2019

VBA - Runtime Error when clicking out of rich text field on ms-word

Not super familiar with VBA, so I feel like this may be a fairly simplistic question, but I can't find a resolution for my issue.

In ms-word, I've made a form in which initially, I wanted specific aspects of the form to hide/display based on different interactions with the form (code down below), which, with some help from another post, works fine, but now I've added text-fields which is causing run-time errors.

Now my issue is that the ContentControlOnExit function is being applied to when a user clicks out of a text field, which I only wanted to apply to when a user clicks out of a chechkbox, which is causing run-time error's.

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

    Dim bChecked As Boolean
    bChecked = (ContentControl.Checked = True)

    If ContentControl.Title = "checkbox1" Then
        ActiveDocument.Bookmarks("approve").Range.Font.Hidden = bChecked
    End If

    If ContentControl.Title = "checkbox2" Then
        ActiveDocument.Bookmarks("sign1").Range.Font.Hidden = bChecked
        ActiveDocument.Bookmarks("sign2").Range.Font.Hidden = bChecked
    End If

    If ContentControl.Title = "checkbox3" Then
        ActiveDocument.Bookmarks("note").Range.Font.Hidden = bChecked
    End If

End Sub

Is there any simple statement I can add so that it doesn't do this check when clicking out of a text-field?




How can I store Unchecked box data in database in PHP?

In PHP I used Multi check box in foreach loop, When I Unchecked then I want to count and store that data in Database and also for Checked data, so How can I do that? And I've a condition for that it is...

If(checked)
{
 Insert Present
}
Elseif(Unchecked)
{
 Insert Absent
}

Check box is in foreach loop, so there is multiple checkbox with different names.

Here presently I store data for Checked, but I can't store data for Unchecked, so please help me to solve this problem.




Sweet alert 2 multiple checkbox

I'm using this "sweet alert 2", I I need of multiple checkbox, In documentation there is 'input-radio' option with multiple choice, but only single choice for checkbox option.

Is there possibily to use this script with checkbox multiple choice?

https://sweetalert2.github.io/#input-radio

https://sweetalert2.github.io/#input-checkbox

// inputOptions can be an object or Promise
const inputOptions = new Promise((resolve) => {
  setTimeout(() => {
    resolve({
      '#ff0000': 'Red',
      '#00ff00': 'Green',
      '#0000ff': 'Blue'
    })
  }, 1000)
})

const {value: color} = await Swal.fire({
  title: 'Select color',
  input: 'radio',
  inputOptions: inputOptions,
  inputValidator: (value) => {
    if (!value) {
      return 'You need to choose something!'
    }
  }
})

if (color) {
  Swal.fire({html: 'You selected: ' + color}

single checkbox

const {value: accept} = await Swal.fire({
  title: 'Terms and conditions',
  input: 'checkbox',
  inputValue: 1,
  inputPlaceholder:
    'I agree with the terms and conditions',
  confirmButtonText:
    'Continue <i class="fa fa-arrow-right></i>',
  inputValidator: (result) => {
    return !result && 'You need to agree with T&C'
  }
})

if (accept) {
  Swal.fire('You agreed with T&C :)')
}

thanks




Best way to store/send truth values of checkboxes to a function or file

So I just got back into programming so everything is a bit rusty or just forgotten, never was a pro. I am making a program where the user needs to select what filetypes they want to sort. I'm doing this through checkboxes.

Now im wondering what the best way would be to store these values and give them to the next step in the progress, which will be something along the lines of: ..\image.jpg >> check file extension >> check list >> move to image folder ..\danksong.mp3 >> check file extension >> check list >> move to music folder

and it runs through all files in a folder to sort them out. So basicly I would like to know what the best way of storing the selections would be and then go through the list of selected extensions and filter the items.




Click evt is registered to div surrounding checkbox instead of the checkbox itself

I have a list of documents with a checkbox next to each. Clicking on a checkbox is supposed to append that document to a separate div (aka a "Favorites List"). This does not work as intended, however clicking on the div that surrounds the checkbox correctly appends that document. Another issue is that clicking on a checkbox when the Favorites contains one or more documents clears the list, which is also not intended.

How can I properly register the checkbox itself to the click event rather than the div surrounding the checkbox? I've tried different methods, such as $( "input[type='checkbox']" ), but I've been coming up short so I thought I'd ask about it here.

JS snippet:

import $ from 'jquery';

import testDocs from '../test.json';
import { basename } from 'path';

import dt from 'datatables.net';

var categories = '';
var tableRes = '';

  export default class {
      constructor() {
        this.loadTableData();
      }

// this area contains code that's irrelevant for my question //

// ------ Rendering checkboxes ------- //
  $("#km-table-id tbody tr").on("click", function(evt) {
    evt.stopPropagation();
    if (evt.target.type !== "checkbox") {
      $(":checkbox", this).on("click");
    }      
  });

  // ------ Appending checkboxes ------- //
  let inputType = $("<input />", {"type": "checkbox"})
  let chkboxCol = $("#km-table-id tbody tr > td:nth-child(3)");

  chkboxCol.append(inputType).addClass("checkbox-class");


  // --- My Favorites functionality ---- //
  function faveFunc(evt) {
    let anchor = $($(evt.target).prev().find("a")[0]).clone();
    // let ancTxt = $(anchor).text();
    switch($(".populate-faves").find("a:contains(" + $(anchor).text() + ")").length)
    {
      case 0:
        $(".populate-faves").append(anchor);
        break;
      default:
        $(".populate-faves > a:contains(" + $(anchor).text() + ")").remove();
        break;
    }
  };


  function newList() {
    let data = $(evt.target).prev().find("a").eq(0).html();
    let outputList = $(".populate-faves");

    $(".populate-faves").html("");

    $("#km-table-id tbody tr)").each(function(i, el) {
        let cntxFave = $(".add-id", el);
        let fave = $(".checkbox-class", el);
        let itemText = $(data, el);

        if(cntxFave.is(".add-id")) {
          outputList.append("<li>" + itemText.html() + "</li>");
        }

        if(fave.prop("checked")) {
          outputList.append("<li>" + itemText.html() + "</li>");
        }
      });
  }; // ------------ newList

  $(".checkbox-class").on("click", faveFunc);

HTML snippet:

<div class="col-md-14"> <!-- Right -->

        <table id="km-table-id" class="cell-border display stripe-hover">
          <thead>
            <tr>
              <!-- <th></th> -->
              <th></th>
              <th></th>
              <th>Title</th>
              <th></th> <!-- Keep here--this is for checkbox col -->
            </tr>
          </thead>

          <tbody></tbody> 
    </table>




In React how do you check if at least one checkbox has been selected

I wrote a Checkbox component, with React, that is reused to generate a list of checkboxes. I know that a react element is different from a DOM in terms of state. But how do I check if at least 1 checkbox has been selected by the user on form submit?

I have searched in SO and Google but all examples are either in jQuery or vanilla JS. For my case I want a React example.

component

const Checkbox = ({ title, options, id, name, onChange }) => {
  return (
    <div className="checkbox-group">
      <h4>{title}</h4>
      {options.map(option => (
        <label htmlFor={`${name}-${index}`} key={`${name}-${index}`}>
          <input
            type="checkbox"
            name={name}
            value={option}
            onChange={onChange}
            id={`${name}-${index}`}
          />
          <span> {option}</span>
        </label>
      ))}
    </div>
  );
};

class Form extends Component {

  ...

  handleChange(event) {
    let newSelection = event.target.value;
    let newSelectionArray;

    newSelectionArray = [
      ...this.state.sureveyResponses.newAnswers,
      newSelection,
    ];

    this.setState(prevState => {
      return {
        surveyResponse: {
          ...this.state.surveyResponse,
          newAnswers: newSelectionArray,
      }
    )
  }

  handleSubmit() {
    // I'm guessing this doesn't work in React as it's using its own state!
    let checkboxes = document.querySelectorAll('[name="quiz-0"]:checked');

    for (let chk in checkboxes) {
      if (chk.checked) {
        return true;
      }
    }

    alert('Please choose at least one answer.');
    return false;
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <h4>Choose</>
        {this.state.surveyQuiz.map((quiz, index) => {
          return (
            <div key={index}>
              <Checkbox
                title={quiz.question}
                options={quiz.answers}
                name={`quiz-${index + 1}`}
                onChange={this.handleChange}
              />
            </div>
          );
        })};
        <button>Save answer(s)</span>
      </form>
    );
  }
}

When the user submits the form, it should check if at least a checkbox is checked, if not none is checked then prevent the form to submit, i.e. return false!




mardi 26 mars 2019

Nesting loops and statements in php

i have this code and i want to add checkbox according to fetched number from database with php and when clicked on checkbox update a field in db with jquery, this work for 1 checkbox but this cant work for more checkbox and Also my PHP loop does not work how i can add checkbox with loops and when user click on any checkbox update His own field on database, anybody can resolve my problem ? my jquery code:

        var returnVal = ("Are " + "you sure?");
        if (returnVal) {
            postToServer($(this).prop("checked"));

        } else {
            $(this).prop("checked", !$(this).is(":checked"));
        }
    });
    function postToServer(state) {
        let value = (state) ? 1 : 0;

        $.ajax({
            type: 'POST',
            url: 'checkbox.php',
            data: {'value': +value},
            success: function (response) {
                //handle response
            }
        });
    } 

and my php code:

   $sql1="SELECT * FROM `users` ";
   $result1= mysqli_query($conn,$sql1);
   $row1=mysqli_fetch_assoc($result1);
   $lights=$row1["lights"];
    for ($i=0; $i < $lights; $i++){
        if ($row["value"]=='1'){
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" checked=\"checked\">";
    }else {
            echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" >";
        }
    }




How to check/uncheck 3 secondary checkboxes according to 1 principal checkbox (19times)?

I have 19 cards of 4 checkboxes: 1 main checkbox (date) and 3 secondary checkboxes (options for that date). I would like the 3 secondary options to be checked when the main one is checked and conversely that they are unchecked when the main one is unchecked. I would like to use a single function for all 19 cards. However, checkboxes have different ids.

When I click on a main checkbox I get the id from the main checkbox I retrieve the number contained in the id I apply it to three values to create the id of 3 secondary checkboxes If the main checkbox is checked: I check the secondary checkboxes If the main checkbox is unchecked: I uncheck the secondary checkboxes

I tried with "onclick" and onchange.

function Autocheck(id) {

  var clicked_id = id;
  var StgNbr = clicked_id.substr(4);

  var diner = "Dîner" + StgNbr;
  var souper = "Souper" + StgNbr;
  var logement = "Logement" + StgNbr;

  if (clicked_id.checked = true) {
    alert('je suis coché');
    var items = document.getElementsByClassName('presence');
    for (var i = 0; i < items.length; i++) {

      if (items[i].id == diner)
        items[i].checked = true;
      if (items[i].id == souper)
        items[i].checked = true;
      if (items[i].id == logement)
        items[i].checked = true;
    }



  } else {
    alert('je suis décoché');
    var items = document.getElementsByClassName('presence');
    for (var i = 0; i < items.length; i++) {

      if (items[i].id == diner)
        items[i].checked = false;
      if (items[i].id == souper)
        items[i].checked = false;
      if (items[i].id == logement)
        items[i].checked = false;
    }

  }

}
<div class="row">
  <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
    <div class="card">
      <label for="date1"><div class="card-media"><input type="checkbox" id="date1" class="date presence" name="Dates" onclick="Autocheck(this.id)">&nbsp; &nbsp;Mardi 23/07</div></label>
      <div class="card-details">
        <input type="checkbox" class="presence" name="Dîner" id="Dîner1">
        <label for="Dîner1">&nbsp; &nbsp;Dîner</label><br>
        <input type="checkbox" class="presence" name="Souper" id="Souper1">
        <label for="Souper">&nbsp; &nbsp;Souper</label><br>
        <input type="checkbox" class="presence" name="Logement" id="Logement1">
        <label for="Logement">&nbsp; &nbsp;Logement</label><br>
      </div>
    </div>
  </div>
  <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
    <div class="card">
      <label for="date2"><div class="card-media"><input type="checkbox" id="date2" class="date presence" name="Dates" onchange="Autocheck(this.id)">&nbsp; &nbsp;Mercredi 24/07</div></label>
      <div class="card-details">
        <input type="checkbox" class="presence" name="Dîner" id="Dîner2">
        <label for="Dîner2">&nbsp; &nbsp;Dîner</label><br>
        <input type="checkbox" class="presence" name="Souper" id="Souper2">
        <label for="Souper2">&nbsp; &nbsp;Souper</label><br>
        <input type="checkbox" class="presence" name="Logement" id="Logement2">
        <label for="Logement2">&nbsp; &nbsp;Logement</label><br>
      </div>
    </div>
  </div>

My secondary checkboxes are well cheched but they don't uncheck. Also : my 'test' alert is always saying that the principal checkbox is checked even if I uncheck it.

Thank you for your help.




Input checkbox ridiculously big on iOS Safari

Checked my site on iOS Safari and I get this huge checkbox input that looks like it's system styled. Can this be styled, or maybe made a bit smaller?

The issue can be checked here

1




Clicking on a checkbox toggles other checkbox at times

So I got 5 checkbox. All below one another. They have been made using svg and polyline. When I click on the label of each checkbox, it toggles the correct one, but when I click on the image of the checkbox, at times it toggles the incorrect box!

.cbx {
  margin: auto;
  margin-top: 2px;
  -webkit-user-select: none;
  user-select: none;
  cursor: pointer;
}
.cbx span {
  display: inline-block;
  vertical-align: middle;
  transform: translate3d(0, 0, 0);
}
.cbx span:first-child {
  position: relative;
  width: 18px;
  height: 18px;
  border-radius: 3px;
  transform: scale(1);
  vertical-align: middle;
  border: 1px solid #9098A9;
  transition: all 0.2s ease;
}
.cbx span:first-child svg {
  position: absolute;
  top: 3px;
  left: 2px;
  fill: none;
  stroke: #FFFFFF;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-dasharray: 16px;
  stroke-dashoffset: 16px;
  transition: all 0.3s ease;
  transition-delay: 0.1s;
  transform: translate3d(0, 0, 0);
}
.cbx span:first-child:before {
  content: "";
  width: 100%;
  height: 100%;
  background: #506EEC;
  display: block;
  transform: scale(0);
  opacity: 1;
  border-radius: 50%;
}
.cbx span:last-child {
  padding-left: 8px;
}
.cbx:hover span:first-child {
  border-color: #506EEC;
}

.inp-cbx:checked + .cbx span:first-child {
  background: #506EEC;
  border-color: #506EEC;
  animation: wave 0.4s ease;
}
.inp-cbx:checked + .cbx span:first-child svg {
  stroke-dashoffset: 0;
}
.inp-cbx:checked + .cbx span:first-child:before {
  transform: scale(3.5);
  opacity: 0;
  transition: all 0.6s ease;
}

@keyframes wave {
  50% {
    transform: scale(0.9);
  }
}

The html

<div class="ax-cb-div">
  <input class="inp-cbx" id="1" type="checkbox" style="display: none;"/>
  <label for="1" class="cbx"><span>
    <svg width="12px" height="10px" viewbox="0 0 12 10">
      <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
    </svg></span><span>Checkbox number 1</span>
  </label>
</div>

<div class="ax-cb-div">
  <input class="inp-cbx" id="2" type="checkbox" style="display: none;"/>
  <label for="2" class="cbx"><span>
    <svg width="12px" height="10px" viewbox="0 0 12 10">
      <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
    </svg></span><span>Checkbox number 2</span>
  </label>
</div>

<div class="ax-cb-div">
  <input class="inp-cbx" id="3" type="checkbox" style="display: none;"/>
  <label for="3" class="cbx"><span>
    <svg width="12px" height="10px" viewbox="0 0 12 10">
      <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
    </svg></span><span>Checkbox number 3</span>
  </label>
</div>

<div class="ax-cb-div">
  <input class="inp-cbx" id="4" type="checkbox" style="display: none;"/>
  <label for="4" class="cbx"><span>
    <svg width="12px" height="10px" viewbox="0 0 12 10">
      <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
    </svg></span><span>Checkbox number 4</span>
  </label>
</div>

Select checkbox 1, 2, 3, 4. Then click on checkbox 3 to uncheck it. Checkbox 4 gets unchecked instead. Upon clicking again on checkbox 3, it gets unchecked.

Link to codepen




How can I update the underlying data value of checkbox on click

I am using Office Fabric React in an spfx web part and within a MarqueeSelection /DetailsList in each row have a checkbox to represent a boolean value, On click the default callback function writes out to log whether the isChecked value is true/false.

How can I correctly wire up my component so that it correctly updates the value of the line data on click?

I have been unable to overload the bound function to pass an identifier value to update the value.

the component output is :

the function binding is: this._onCheckboxChange = this._onCheckboxChange.bind(this);

the callback function is: private _onCheckboxChange(ev: React.FormEvent, isChecked: boolean): void { console.log(The option has been changed to ${isChecked}.); }

I have been unable to overload the bound function to pass an identifier value to update the value.

I have also tried to wrap it in a span tag and fire an event on click

The end result should ideally update the 'Displayed' value of the associated object in the array of data to reflect the change in boolean value.




Grey out check boxes depending on Radio button selection

I am trying to grey out or disable the checkboxes depending on the selection of the radio button. For example if I select the "BRF" radio button I would like the "BRF" checkbox to be disabled but all the other ones enabled and so forth...I am very new to Tkinter and can't figure out why my code is not working.

I have tried setting the state on the condition of the radio selection but it appears not to do anything.

import tkinter as tk
from tkinter import ttk 

window = tk.Tk()
window.configure(background='white')
window.geometry("500x600") # This sets the Window size to work with
window.title('Please select scan options')

button = tk.Button(window, font="Heltavica",text ="PROCEED", command=window.destroy)
button.config(bd=8, font="Ariel", justify="center")
button.pack(side=tk.BOTTOM)

comp = [('BRF','Orange'), ('SHG','Green') ,('THG','Purple'), ('ETA','Blue'), ('MAIN TEC', 'Red')]

power_scan = tk.IntVar()
check1 = tk.Checkbutton(window, text='Get power', 
        command=power_scan.get, variable = power_scan ,
        onvalue=1, offvalue=0)

check1.place(x=400,y=50)

noise_scan = tk.IntVar()
check2 = tk.Checkbutton(window, text='Get noise', 
        command=noise_scan.get(), variable = noise_scan ,
        onvalue=1, offvalue=0)

check2.place(x=400,y=100)


if power_scan.get():
    # do something
    print("Power scan selected")
if noise_scan.get():
    # do something
    print("Noise scan selected")

tk.Label(window, 
        text="""Please select a parameter scan :""",
        justify = tk.LEFT,
        padx = 20).pack()

def disable_button():
    print('disable button')
    button.config(state=tk.DISABLED)

def enable_button():
    print('enable button')
    button.config(state=tk.NORMAL)

def changebutton():
    print('changebutton=', var1.get())
    if var1.get()==1:
        enable_button()
    else:
        disable_button()     

def selected1():
    print(var1.get())


def selected2():
    print(var2.get())


var1 = tk.StringVar() #used to get the 'value' property of a tkinter.Radiobutton
var2 = tk.IntVar()

components = [("BRF", "BRF"),
              ("SHG", "SHG"),
              ("THG", "THG"),
              ("ETA", "ETA"),
              ("MAIN TEC", "MAIN TEC")
              ]


count = 0
for text, mode in components :
        a = tk.Radiobutton(window, text=text,
                        variable=var1, value=mode, command = selected1,indicatoron = 0)

        a.place(x=130,y=40+15*count*2)

        count += 1       


if selected1() == None:
    brfstate='enabled' 
    shgstate='enabled'
    thgstate ='enabled' 
    etastate='enabled'
    maintstate='enabled' 

if selected1() == "BRF":
    brfstate='disabled' 
    shgstate='enabled'
    thgstate ='enabled' 
    etastate='enabled'
    maintstate='enabled' 

elif selected1() == "SHG":
    brfstate='enabled' 
    shgstate='disabled'
    thgstate ='enabled' 
    etastate='enabled'
    maintstate='enabled' 

elif selected1() == "THG":
    brfstate='enabled' 
    shgstate='enabled'
    thgstate ='disabled' 
    etastate='enabled'
    maintstate='enabled' 

elif selected1() == "ETA":
    brfstate='enabled' 
    shgstate='enabled'
    thgstate ='enabled' 
    etastate='disabled'
    maintstate='enabled'

elif selected1() == "MAIN TEC":
    brfstate='enabled' 
    shgstate='enabled'
    thgstate ='enabled' 
    etastate='enabled'
    maintstate='disabled'


brf = ttk.Checkbutton(window, text="BRF", variable=tk.IntVar(), state=brfstate, onvalue=1, offvalue=0)
brf.place(x=300,y=40+15*0*2)

shg = ttk.Checkbutton(window, text="SHG", variable=tk.IntVar(), state=shgstate, onvalue=1, offvalue=0)
shg.place(x=300,y=40+15*1*2)        

thg = ttk.Checkbutton(window, text="THG", variable=tk.IntVar(), state=thgstate, onvalue=1, offvalue=0)
thg.place(x=300,y=40+15*2*2)

eta = ttk.Checkbutton(window, text="ETA", variable=tk.IntVar(), state=etastate, onvalue=1, offvalue=0)
eta.place(x=300,y=40+15*3*2)  

maint = ttk.Checkbutton(window, text="MAIN TEC", variable=tk.IntVar(), state=maintstate, onvalue=1, offvalue=0)
maint.place(x=300,y=40+15*4*2) 

window.mainloop()

I expect when the radio button parameter on the left is selected that the equal and opposite checkbox would be disabled. Instead all of the checkboxes are enabled regardless of my radio button selection...Can anyone help? I'm totally stuck!




How to get checkbox checked from database array using Laravel and Ajax

I'm trying to get data from database to checkboxes as checked. The checkbox data in database are as array that have been inserted with json and they are dynamic data based on insert function.

My tasks table:

id |employee_id | startDate  | endDate   | ...
---|------------|------------|-----------|--------
1  |["1","2"]   | .......... | ..........| ....

My TasksController.php

function fetchdata(Request $request)
    {
        $id = $request->input('id');
        $task = Task::find($id);
        $output = array(
            'employee_id'    =>  $task->employee_id,
            'name'    =>  $task->name,
            'description'    =>  $task->description,
            'startDate'    =>  $task->startDate,
            'endDate'    =>  $task->endDate,
            'percentage'    =>  $task->percentage       

        );
        echo json_encode($output);
    }

    public function getEmployeesList()
    {

        $employeesList = Employee::all();


        return view('adminlte::tasks', ['employeesList' => $employeesList]);


    }

My tasks.blade.php

 @foreach($employeesList as $emplist)
    <label class="checkbox-inline">
      <input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="" ></label>    
 @endforeach


My Ajax function inside blade:

$(document).on('click', '.edit', function(){
        var id = $(this).attr("id");
        $('#form_output').html('');
        $.ajax({
            url: "",
            method: 'get',
            data: {id:id},
            dataType: 'json',
            success:function(data)
            {
                $('#id').val(data.id);
                $('#employee_id').val(data.employee_id);
                $('#name').val(data.name);
                .......................
                ..................
            }
        })
    });

So, how can I retrieve data from database to checkboxes as checked, because for now I'm getting null "employee_id" value when I try to update a record.

Thank you in advance




lundi 25 mars 2019

if any changes happen in records then only button should be enable while using checkbox for value manipulation in react

handleCheckboxChange = (id, checked) => {
    const { data } = this.state;
    _.map(data, e =>
      _.filter(e.option, m => m[COMPONENT_ID] === id).map(n => {
        const temp = n.isVisible;
        n.isVisible = checked ? 'Y' : 'N'; // eslint-disable-line no-param-reassign
        if (n.isVisible !== temp) {
          this.setState({
            isEnable: false
          });
        } else {
          this.setState({
            isEnable: true
          });
        }
        return n;
      })
    );
    this.setState({ data });
}

I 'm just trying to depand my button's visibility on isEnable state while i'm just checking the checkbox everytime it is calling to handleCheckboxChange method.so my req. is when i changed into the value of isVisible from Y to N or N to Y then only button visibility should enabled, if user just checked the checkbox and then simply unchecked then button visibility should be hidden




how to add checkbox in listview using xamarin forms

i want to create a checkbox in listview using xaml, after selecting the multiple checkbox click button to get all selected value.My code is :

<ContentPage.Content>
    <ListView  x:Name="ProductsListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Spacing="0">
                            <Label Text="{Binding retail_modified_item_id}" 
                               TextColor="Blue" FontSize="13" />
                            <Label Text="{Binding name, StringFormat='Name : 
                               {0:N}'}" TextColor="black" FontSize="10"  />
                            <Label Text="{Binding retail_price, 
                               StringFormat='Price : {0:N}'}" 
                               TextColor="black" FontSize="10" />
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>                            
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

my output is; output without checkbox

i tried some sample code from https://www.ignatiuz.com/blog/xamarin/button-check-box-with-list-item-in-xamarin-forms-listview/

but i'm getting input:checkbox not found

i am new to xamarin please give some sample code or link to do this




Changing value of hidden input on click event of check box

I have created checkbox in table row dynamically.

To check the value of checkbox, I have created hidden input for particular checkbox. But after adding the multiple rows and clicking on checkbox, all the hidden input values are changed. For example, If the hidden input value is True, then after clicking the checkbox, all the hidden input values are changed to False.

Please show the below example:

$(".add_initep_row").click(function(){           
        var markup = "<td style='width: 122px;'><div class='input-group'><input type='text' class='form-control textmodify_newSchedule datepicker_recurring_start' id='ep_date' ><span class='input-group-addon datepicker_recurring_start_calender'><span class='glyphicon glyphicon-calendar'></span></span></div></td><td><textarea></textarea></td><td><input type='hidden'  class='ep_cmpl_val' value='False'><input type='checkbox' class='cmpl_checkbox' onclick='myfunction()'></td>";
        $('#init_ep_table tbody') // select table tbody
        .prepend('<tr />') // prepend table row
        .children('tr:first') // select row we just created
        .append(markup) // append four table cells to the row we created
        /*$("table tbody").append(markup);*/
    });


function myfunction()
        {
                
                var input = $('.cmpl_checkbox').prev('.ep_cmpl_val').val();
                alert(input);
                if (input == 'False') 
            {
                $('.cmpl_checkbox').prev('.ep_cmpl_val').val('True');
            }
            else
            {
                $('.cmpl_checkbox').prev('.ep_cmpl_val').val('False');
            }
        }
  
  $(document).ready(function(){
                 $('.cmpl_checkbox').click(function() {
                        var input = this.previousSibling.value;
      //alert(input);
                        if (input == 'False') 
                    {
                        this.previousSibling.value='True';
                    }
                    else
                    {
                        this.previousSibling.value='False';
                    }
                  });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="init_ep_table">
  <tr>
                                        <td>
                                                <div class="input-group">
                                    <input type="text" class="form-control textmodify_newSchedule datepicker_recurring_start" > 
                                    <span class="input-group-addon ep_date4_calender datepicker_recurring_start_calender"><span class="glyphicon glyphicon-calendar"></span></span>
                                </div>
                            </td>
                            <td>
                                <textarea></textarea>
                            </td>
                            <td>
                                <input type="hidden" value="False"><input type="checkbox" class="cmpl_checkbox">
                            </td>
                                </tr>
</table>
<input type="button" class="add_initep_row" value="Add Row">

Default checkboxes are working fine but checkboxes which are created dynamically, are having issues with hidden input values.

Please help me with this issue.




input type checkbox to be true or false depended on the data

I'm trying to create a checkbox, which is depended on the database to show whether it should be initially checked or unchecked.

Played around the checkedbox and value with true/false, 0/1 and ""/blanks

$.each(customers, (index, customer) => {
$('#accordionAlarm').append(
`<tr>
<td class="card">

<input type="checkbox" name="checkBox[]" id="1${customer.customerId}" checked="${customer.alarmDateInitial === 'Y' ?  'true' : 'false' }"></input>
<input type="checkbox" name="checkBox[]" id="5${customer.customerId}" checked="${customer.alarmDateFifth === 'Y' ?  'true' : 'false' }"></input>
<input type="checkbox" name="checkBox[]" id="7${customer.customerId}" checked="${customer.alarmDateSeventh === 'Y' ?  'true' : 'false' }"></input>

</td>
</tr>`)
});

Expected:

  • When data = Y, checkbox is checked
  • When data != Y, checkbox is not checked



How to submit checkbox values in Ajax Json to Flask?

I want to be able to send a JSON dictionary of true or false values from multiple checkboxes. Unfortunately, when I submit, whether checked or unchecked, the values sent to Flask are always "on", not true or false. Can anyone please help? I'd be very grateful.

Here is my HTML/JQuery code

checkbox1.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" href="/static/images/neptune-icon2.png" type="image/png" sizes="16x16">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" href="/static/images/neptune-icon2.png" type="image/png" sizes="16x16">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
        integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>

<title>Check Box 1</title>
</head>
<body>



<center>



<input type="checkbox" id="checking-1" checked="false">
<input type="checkbox" id="checking-2" checked="false">

<br>
<input type="submit" name="submit" class="grab-checkboxes">

</center>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script   src="http://code.jquery.com/jquery-3.3.1.min.js"   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="   crossorigin="anonymous"></script>
<script   src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"   integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="   crossorigin="anonymous"></script>


<script type="text/javascript">


 $(document).on("click", ".grab-checkboxes", function (e) {

            e.preventDefault();

            // var info = $(this).parent().siblings('#checking-1').text();

            var dateArray = [];

            $('#checking-1').each(function () {

                var check1 = $(this).val();
                var check2 = $(this).parent().find('#checking-2').val();

                dateArray.push({ 'checking1': check1, 'checking2': check2 });

            });

            console.log(dateArray);

            console.log(dateArray.length);
            console.log(Object.keys(dateArray));



            var server = "http://127.0.0.1:5000";

            var appdir = "/grab_checkboxes"


            $.ajax({

                 type:"POST",
                 url: server + appdir,
                 data: JSON.stringify(dateArray),
                 dataType: "json",
                 contentType: "application/json;charset=UTF-8",
                 success: function(data){

                     console.log(data);
                    console.log("Checking...");
                 }
             });

            return false;

        });




</script>


</body>
</html>

my flask code.

from flask import Flask, render_template, jsonify, request
import json

app = Flask(__name__)


@app.route("/checkbox1", methods = ["GET", "POST"])
def checkbox1():


    return render_template("checkbox1.html")

@app.route("/grab_checkboxes", methods = ["GET", "POST"])
def grab_checkboxes():



    print("Grabbing 1 or more checkboxes that are true!")

    data = request.get_json()


    print(data)


    return "1"




dimanche 24 mars 2019

iCheck Enable/Disable Input-File(Boostrap) Button when i check a checkbox

Hello im using iCheck(http://icheck.fronteed.com/) The problem is, when i click the checkbox, input-file button works but appears to be "disabled".

I'm using two events, ifChecked/ifUnchecked.

I tried before, using instead of .prop(), attr, removeclass, addclass

"input id="Archivo" name="Archivo" type="file" accept=".pdf,.doc" disabled"

 $("#Archivo").fileinput({
    language: "es",
    browseClass: "btn btn-primary",
    showCaption: true,
    showRemove: false,
    showUpload: false,
    browseLabel: "&nbsp;Buscar",
    allowedFileExtensions: ["pdf", "doc"],
    elErrorContainer: "#divErrorImagen",
    maxFileSize: 122880
}); 


$('input').on('ifChecked', function (event) {
    console.log("Checked OK")
   $('#Archivo').prop("disabled", false);


});
$('input').on('ifUnchecked', function (event) {
    console.log("Unchecked OK")
   $('#Archivo').prop("disabled", true);

});




How to display alert boxes if a checkbox is cheked in Javascript?

I need an alert box when one of the options is checked im using this

function validacion(){
  if (document.getElementById('op1').checked) {
      var x61=document.getElementById('op1').value;
} else {
    var x61="";
}

  alert(" Me gusta : " +x61 );
}

is not working , but i dunno what to do :c




How to hide checkbox options when another checkbox is selected

I'm in the process of trying to put together a form in ms-word, in which it is desired that if a user checks 1 of 3 check-box options, the other two and their adjacent text will be hidden.

I'm aware of how to hide the content some-what, but I'm completely unfamiliar with VBA/programming as a whole, so I don't quite know what is wrong in my If/Else loop, but it definitely doesn't show/hide everything.

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

If ContentControl.Title = "checkbox1" And ContentControl.Checked = True Then
    ActiveDocument.Bookmarks("Approve").Range.Font.Hidden = True
Else
    ActiveDocument.Bookmarks("Approve").Range.Font.Hidden = False
End If

If ContentControl.Title = "checkbox2" And ContentControl.Checked = True Then
    ActiveDocument.Bookmarks("Denied 1").Range.Font.Hidden = True
    ActiveDocument.Bookmarks("Denied 2").Range.Font.Hidden = True
Else
    ActiveDocument.Bookmarks("Sign1").Range.Font.Hidden = False
    ActiveDocument.Bookmarks("Sign2").Range.Font.Hidden = False
End If

If ContentControl.Title = "checkbox3" And ContentControl.Checked = True Then
    ActiveDocument.Bookmarks("pending").Range.Font.Hidden = True
Else
    ActiveDocument.Bookmarks("pending").Range.Font.Hidden = False
End If

End Sub

If I only keep one of the if/else parts it does work fine, but when I keep all 3 it doesn't work.

Any guidance is really appreciated!




I am unable to pick color picker in winium using c#

I am unable to pick the color in color picker and checkbox in winium driver c#

   driver.FindElementByName("Dependencies color").Click();
   driver.FindElementByName("Basic colors:").Click();
   driver.FindElementById("719").Click();
   driver.FindElementByName("Hue:").Click();

    driver.FindElementByName("Hue:").SendKeys(datawords[5].ToString());
    driver.FindElementByName("OK").Click();

I have to pick different color by sending keys




Custom checkbox not toggling

I am trying to make a custom checkbox such that I can retrieve the value in Flask, but for some reason it is not coming through.

Here is my HTML/CSS/JS:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .checkbox {
        height: 14px;
        width: 14px;
        border-radius: 3px;
        background-color: #fff;
        border: 1px solid black;
        cursor: default;
      }
      .checkbox p {
        display: none;
        font-size: 12px;
        line-height: 14px;
        max-height: 14px;
        vertical-align: middle;
        text-align: center;
        color: #777;
      }
      .checkbox.selected p {
        display: block;
      }
      input[type="checkbox"].hiddencheckbox {
        display: none;
      }
    </style>
  </head>
  <body>
    <form action="" method="post">
    <div class="checkbox" onclick="toggleCheck(this)">
      <p>&check;</p>
      <input type="checkbox" name="morning" class="hiddencheckbox">
    </div>
    <input type="submit" value="Submit">
    </form>
  </body>
  <script type="text/javascript">
    function toggleCheck(checkbox) {
      var realcheckbox = checkbox.childNodes[1];
      checkbox.classList.toggle("selected");
      realcheckbox.checked ^= 1;
    }
  </script>
</html>

And my Python:

from flask import Flask, request, render_template

app = Flask(__name__)


@app.route("/", methods=["POST", "GET"])
def load_checkbox():
    if request.method == "POST":
        print(request.form)
    return render_template("checkbox.html")


if __name__ == "__main__":
    app.run(debug=True)

Here is what it prints when I click submit, regardless of the state of the checkbox: ImmutableMultiDict([])

I would like it to print ImmutableMultiDict([('morning', 'on')]) (or similar) if the checkbox is checked, and ImmutableMultiDict([('morning', 'off')]) (or similar) or ImmutableMultiDict([]) if the checkbox is not checked.

What am I missing here? Why is it not working?

Thanks.




samedi 23 mars 2019

How to only post paired checkbox and textarea that have a checked checkbox? Post only textareas that have their checkbox checked?

I'm trying to post certain textboxes that have checkboxes with them. My code works when consecutive checkboxes are checked, it echoes "checkbox value 1 & text area value 1", "checkbox value 2 & text area value 2" and so on. However when I only check checkboxes 1 and 3, the code only echoes the values for checkbox 1 and textarea. How do I make it that I can post only those that their checkbox checked?

Currently, what I'm doing is having all checkboxes and text areas have the same name, literally. All checkboxes have the same name as all textareas. I'm also putting all these values in an array in my php. So that the first checkbox would be in the 0 place of the array and the text area corresponding it at 1, then the second checkbox at 2 and its corresponding textbox at 3, and so on. I'm using while loops for how many checkboxes are there, foreach for array values (not so sure what really this is for), and an if statement if the checkbox value in the array is checked or not.

When I only check the first and third checkbox the first checkbox is "checked" but as the loop goes on it says that the third checkbox is unchecked, using the array.

HTML Code

<form method="post">
<div class="form-group col-sm-4">
    <label><input type="checkbox" name="rel_crossed_eyes[]" value="Crossed Eyes" /> Crossed Eyes</label>
</div>
<div class="form-group col-sm-4">
    <input type="text" class="form-control" id="" name="rel_crossed_eyes[]"/>
</div>
<div class="form-group col-sm-4">
    <label><input type="checkbox" name="rel_crossed_eyes[]" value="Crossed Eyes" /> Crossed Eyes1</label>
</div>
<div class="form-group col-sm-4">
    <input type="text" class="form-control" id="" name="rel_crossed_eyes[]"/>
</div> 
<div class="form-group col-sm-4">
    <label><input type="checkbox" name="rel_crossed_eyes[]" value="Crossed Eyes" /> Crossed Eyes</label>
</div>
<div class="form-group col-sm-4">
    <input type="text" class="form-control" id="" name="rel_crossed_eyes[]"/>
</div>
<div class="form-group col-sm-4">
    <label><input type="checkbox" name="rel_crossed_eyes[]" value="Crossed Eyes" /> Crossed Eyes1</label>
</div>
<div class="form-group col-sm-4">
    <input type="text" class="form-control" id="" name="rel_crossed_eyes[]"/>
</div>
<div>
    <input type="submit" name="submit"/>
</div>
</form>

PHP Code

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "main";
$conn=mysqli_connect($servername, $username, $password);

if (!$conn){
    die("Database Connection Failed" . mysqli_error($conn));
}
$select_db = mysqli_select_db($conn, $dbname);
if (!$select_db){
    die("Database Selection Failed" . mysqli_error($conn));
}


$result = mysqli_query($conn,"SELECT * FROM inventory");

$numbers=("SELECT count(*) as total FROM inventory");
    $result=$conn->query($numbers);
    $row= $result->fetch_assoc();
    echo $row['total'];

$conditions = array("rel_crossed_eyes" => "Crossed Eyes");
if (isset($_POST['submit'])){
    $counted = 0;
    $counteds = 0;
    while ($row['total'] > $counted) {
        foreach ($conditions as $key => $value){
            if ($_POST[$key][$counteds] == $value){//if the checkbox is checked
                echo $_POST[$key][$counteds]." ". $_POST[$key][$counteds+1];
            }else{
            echo "mali";
            }
        $counted++;
        $counteds += 2;
        }

    }
}
?>




how can i hide or show some text fields on checkbox click in woo-commerce

i have some text field i.e in custom size(length,with) of product. i want include a check box , when i click on check box , custom size fields will show/hide on checkbox click.please help me how i can perform this without any code customization.

i had tried some plugins but they add text fields but not show/hide them on checkbox clickenter image description here




How to print a table made in JavaScript with the data filtered by checkboxes, without using jQuery?

I have a table displaying some data, made only in JavaScript. Now, I put some checkboxes in order to filter the the data and show the table with the matches selected before. Without using jQuery, and without "hidding" the rows unselected, I need to create a new table every time a checkbox is selected.

This is the HTML

<form action="/action_page.php">
            <input type="checkbox" name="sParty" value="democrat"> Democrat
            <input type="checkbox" name="sParty" value="republican"> Republican
            <input type="checkbox" name="sParty" value="independent" checked> Independent
            <input type="submit" value="Submit">
        </form>
    </div>
    <div class="row" id="tablerow">
        <div class="col">
        <table class="table table-hover table-sm" id="sendata">
        </table></div>
    </div>
    </div></div>

And this the JS (I started by getting the NodeList from the checkboxes)

var memberArr=data.results[0].members;  //BRINGS DATA FROM JSON FILA
            var newArr = [];                                
            for (var i = 0; i < memberArr.length; i++) {
                var obj = new Object; 
                obj.fullName= memberArr[i].first_name + " " + (memberArr[i].middle_name || " ") +  " " + memberArr[i].last_name;                    
                obj.party = memberArr[i].party;
                obj.state = memberArr[i].state;
                obj.seniority = memberArr[i].seniority;
                obj.votes_with_party_pct=memberArr[i].votes_with_party_pct + "  %" ;
                obj.nameLink=memberArr[i].url;
                newArr.push(obj);                           
            } //newArr is the array with all members(objects)

      var checkedBoxes = 
      document.querySelectorAll('input[name=mycheckboxes]:checked');  //GET 
VALUE OF CHECKED CHECKBOXES





            var headersSenate={
                HfullName:"Full Name",
                Party:"Party Affilication",
                State:"State",
                Senior:"Seniority",
                Votes:"Votes w/Party (pct)",

            }
            var datos="<tr><th>" + headersSenate.HfullName + "</th><th>"+ headersSenate.Party + "</th><th>" + headersSenate.State+ "</th><th>"
            +headersSenate.Senior+ "</th><th>"+headersSenate.Votes+"</th>";

            for(var i=0; i<newArr.length; i++){
                datos+="<tr><td><a target='_blank' href=" + newArr[i].nameLink + ">"+ newArr[i].fullName + "</a></td><td>" + newArr[i].party
                 + "</td><td>" + newArr[i].state + "</td><td>" + newArr[i].seniority + "</td><td>" + newArr[i].votes_with_party_pct + "</td>";
            }
            document.getElementById("sendata").innerHTML= datos;




How to apply required validation for checkbox using dynamically

I'm setting dynamic form validation using the following JSON. base on these JSON i have create dynamically form field using the following JSON format.

Data

  fields = [
    {
      type: 'text',
      name: 'firstName',
      label: 'First Name',
      value: '',
      required: true,
   },
   {
      type: 'checkbox',
      name: 'hobby',
      label: 'Hobby',
      required: true,
      options: [
        { key: 'f', label: 'Fishing' },
        { key: 'c', label: 'Cooking' }
      ]
    }
  ]

My commponent.ts file is following

form: FormGroup;

ngOnInit() {
  let fieldsCtrls = {};
    for (let f of this.fields) {
      if (f.type != 'checkbox') {
        fieldsCtrls[f.name] = new FormControl(f.value || '', 
          Validators.required)
      } else {
        let opts = {};
        for (let opt of f.options) {
          opts[opt.key] = new FormControl(opt.value);
        }
       fieldsCtrls[f.name] = new FormGroup(opts)
     }
   }
   this.form = new FormGroup(fieldsCtrls);
}  

I have apply required validation for all input field exclude checkbox.

How can apply required validation for the checkbox in this code?




vendredi 22 mars 2019

PHP - How to only post checked checkboxes in a loop?

I am working on a project that signs up students to specific classes("french", "math",...). The student id is already selected. True a while loop i display my classes out of my database with a checkbox in front of each class. I only wanna post te checked checkboxes in a form that will send it to a php file thats puts the student and his selected classes into the database. But i cant seem to solve how i only post the checked checkboxes because of the difficulty with the while loop. I hope someone can help me. Already thanks!




Odd issue while reading checkbox state

I have a checkbox column in a datagridview.When I try to iterate through the column,the results vary on each iteration despite no changes in the checkboxes.The following is the code:

Dim TotalRows As Integer = 0

        For RW As Integer = 0 To DGVMulyo.Rows.Count - 1
            MsgBox(DGVMulyo.Rows(RW).Cells(1).Value)
            If DGVMulyo.Rows(RW).Cells(1).Value = True Then
                TotalRows = TotalRows + 1
            End If
        Next

On each iteration of the loop,the messagebox will show differing results of the state of the checkboxes.Some times even if the checkbox is checked,the output is shown as 0. I also tried the following but the same issue persisted:

        For RW As Integer = 0 To DGVMulyo.Rows.Count - 1
            MsgBox(DGVMulyo.Rows(RW).Cells(1).State)
            If DGVMulyo.Rows(RW).Cells(1).State = True Then
                TotalRows = TotalRows + 1
            End If
        Next

In the end,the following code seems to work reliably:

Dim TotalRows As Integer = 0

        For RW As Integer = 0 To DGVMulyo.Rows.Count - 1
            'MsgBox(DGVMulyo.Rows(RW).Cells(1).Value)
            If DGVMulyo.Rows(RW).Cells(1).Value = True Or DGVMulyo.Rows(RW).Cells(1).Value = 1 Then
                TotalRows = TotalRows + 1
            End If
            '  MsgBox(TotalRows)
        Next

I am using VS-2017 Community edition with Windows-7 32 Bit OS.

Khalid.




Javascript Validate

I have a checkbox that I want to verify the checkbox (same names with different values) and to enable/disable if value is an E and it is checked.

function DisableETP() {
 var kk = document.getElementsByName('RQR')
 for (var i = 0; i < kk.length i++) {
    if (kk[i].value == 'E' and kk[i].checked == true) {
 document.getElementById('cp2').disabled = true
 document.getElementById('cp2').value = ""
 document.getElementById('rtp2').disabled = true
 document.getElementById('rtp2').value = ""
 document.getElementById('qty2').disabled = true
 document.getElementById('qty2').value = ""
 document.getElementById('cp3').disabled = true
 document.getElementById('cp3').value = ""
 document.getElementById('rtp3').disabled = true
 document.getElementById('rtp3').value = ""
 document.getElementById('qty3').disabled = true
 document.getElementById('qty3').value = ""
    } else {
 document.getElementById('cp2').disabled = false
 document.getElementById('cp2').value = ""
 document.getElementById('rtp2').disabled = false
 document.getElementById('rtp2').value = ""
 document.getElementById('qty2').disabled = false
 document.getElementById('qty2').value = ""
 document.getElementById('cp3').disabled = false
 document.getElementById('cp3').value = ""
 document.getElementById('rtp3').disabled = false
 document.getElementById('rtp3').value = ""
 document.getElementById('qty3').disabled = false
 document.getElementById('qty3').value = "" }
 }

Do I need to add ; to the lines or ???

Thank you.




Angular 6 check box doesn't change state based on ngModel

In an array say I have five mantras out of it users have to choose maximum of three. This is my implementation

<input class='f-z-14' type="checkbox" [(ngModel)]='mantrasSelected[i]' [checked]='mantrasSelected[i] === true' (change)='mantraChecked(i, mantrasSelected[i], mantra)'>

And in my ts

mantraChecked(i, event, mantra) {
    if (event) {
      if (this.selectedCount < 3) {
        this.selectedCount += 1;
        this.mantrasSelected[i] = true;
      } else {
        this.mantrasSelected[i] = false;
      }
    } else {
      if (this.selectedCount > 0 && this.selectedCount <= 3) {
        this.selectedCount -= 1;
        this.mantrasSelected[i] = false;
      }
    }
}

So If i choose first three means in this.mantrasSelected I will be having [true, true, true, false, false]. So If user checked fourth one means I'm checking in my mantraChecked() if count is greater than 3 means I dont want to check it. after I click 4th mantra I'm changing mantrasSelected to [true, true, true, false, false] but view shows it is checked. How can show to the user that they have checked only three box? How two biding work with checkbox? Thank you.




UserForm Run-time-error | Application-defined or object defined error

I made a UserForm with Excel. It has TextBoxes and CheckBoxes and command buttons. UserForm starts with TextBoxes and after that some CheckBoxes come up and TextBoxes goes on. cmdAddData_click is for to send data to sheet. I searched a lot but I'm a newbie around here.

When I want to send data it gives

run-time error, Application-defined or object defined error.

Appreciate for all helps.

Private Sub cmdAddData_Click()
lastrow = ThisWorkbook.Worksheets("00. Active Customers").Cells(Rows.Count, 1).End(xlUp).Row

ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 0).Value = txtDate.Text
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 1).Value = txtName.Text

'after 34 textboxes, now for checkboxes

If cbxADSL.Value = True Then
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 35).Value = "Yes"
Else
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 35).Value = "No"
End If


If cbxAlarm.Value = True Then
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 36).Value = "Yes"
Else
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 36).Value = "No"
End If


'after checkboxes, now for textboxes

ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 122).Value = txtFirstContact.Text
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 123).Value = txtLastContact.Text


End Sub




jeudi 21 mars 2019

How to print value in UILabel from the values of TableView dynamically

enter image description here

I'm having a tableView with a custom cell, whenever I click the checkbox button the value inside the cell increases i.e.,(0 to 1) in cell, and on uncheck value decreases, that works perfectly. But whenever I try to print those values from the cell to a UILabel outside tableView, the values are not changing.

This is the below code I have Used

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TabCell

    cell.checkB.tag = indexPath.row
    let ip = data[indexPath.row]
    cell.nameText.text = ip["title"] as? String
    if cell.nameText.text == "Mandatory testing" {

        cell.checkB.checkState = .checked
        cell.backgroundColor = UIColor.lightGray
        cell.checkB.backgroundColor = UIColor.lightGray
    }

    if ip["mandatory"] as? String == "yes" {
        moneyText.text = ip["amount"] as? String
       //moneyText is UILabel outside Tableview
        cell.amountValue.text = ip["amount"] as? String

        cell.checkB.isEnabled = false
    } else {
        moneyText.text = "0"
        if cell.amountValue.text == "1"{
            print("ONE")
        }
    }
    return cell
}

And for TableviewCell I Used

class TabCell: UITableViewCell {

@IBOutlet weak var checkB: M13Checkbox!

@IBOutlet weak var nameText: UILabel!

@IBOutlet weak var amountValue: UILabel!

var someValue: Int = 0 {
    didSet {
        amountValue.text = "\(someValue)"
    }
}

@IBAction func checkBAction(_ sender: M13Checkbox) {

    if checkB.checkState == .checked {
        someValue += 1

    } else if checkB.checkState == .unchecked {
        someValue -= 1

    }       
}

}

I tried first adding those values from cell to an Array, and then adding all the values in array and printing in UILabel, but the values are not changing, it was only incrementing.i.e., even after unchecking the checkbox the value is increasing.

I tried even using protocol it did not work for me

Any Help will be appreciated.




How to disable a checkbox if another checkbox is enabled? C#

My web-page have two check-boxes and What I want is:

  • Initially both check-boxes are unchecked.
  • if Checkbox1 is checked, Checkbox2 should becomes disabled.
  • if Checkbox2 is unchecked again, Checkbox2 should becomes enabled again.
  • and vice versa.

Please help me in modifying my code..

Here is my code:

protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
{
   //this.CheckBox1.CheckedChanged += new System.EventHandler(CheckBox1_CheckedChanged1);
    if (CheckBox1.Checked)
        CheckBox2.Enabled = false;
}

protected void CheckBox2_CheckedChanged2(object sender, EventArgs e)
{
    if (CheckBox2.Checked)
        CheckBox1.Enabled = false;
}

HTML

<asp:CheckBox ID="CheckBox1" runat="server" Height="33px" OnCheckedChanged="CheckBox1_CheckedChanged1" Font-Bold="True" style="margin-left: 33px" Text="Remove Blank Lines" TextAlign="Left" Width="162px" />


<asp:CheckBox ID="CheckBox2" runat="server" Font-Bold="True" Height="33px" OnCheckedChanged="CheckBox2_CheckedChanged2" style="margin-left: 28px" Text="Add Prefix/ Suffix to Blank Lines" TextAlign="Left" Width="259px" />



Using Macros to hide/show content in Microsoft word

I've tried using VBA for my issue, but im thinking Macros might be the better approach (just completely unsure of how to use them):

I've gone through a number of tutorials and instructional videos trying to achieve my intended result of simply allowing a checkbox in my form to hide content when selected, or re-show it when being de-selected, but nothing seems to be working.

Currently, I've created a bookmark for the content I want hidden, and try to call his this in VBA with the following statement - which a number of resources indicated as the solution:

Private Sub CheckBox1_Click()
ActiveDocument.Bookmarks("bookmark").Range.Font.Hidden = CheckBox1.Value
End Sub
But despite doing this, selecting the checkbox has no affect on the content.

Is there a simpler way of doing this/can this be done with macros that involves less coding?




Angular 7 - How to load material snackbar when checkbox checked in datatable

I have created datatable with checkbox. When user select checkbox, snackBar must be load (currently working good) with length of selected checkbox. But snakcbar loading everytime when user select more than one checkbox. How to load snackbar and just show length of selected ids.(without load snackbar everytime). Snackbar just need to show increment of selected ids. I push selected ids in public endorsementIds: string[] = [];. If endorsementIds length is 0, snackbar must hide. Here is my code in stackblitz. Thank you in advance :)




Using VBA to allow a checkbox to hide/show content in Microsoft Word

I've gone through a number of tutorials and instructional videos trying to achieve my intended result of simply allowing a checkbox in my form to hide content when selected, or re-show it when being de-selected, but nothing seems to be working.

Currently, I've created a bookmark for the content I want hidden, and try to call his this in VBA with the following statement - which a number of resources indicated as the solution:

Private Sub CheckBox1_Click()
ActiveDocument.Bookmarks("bookmark").Range.Font.Hidden = CheckBox1.Value
End Sub

But despite doing this, selecting the checkbox has no affect on the content.

Is there something additional I'm missing (I'm using Microsoft Word 2013).




Check if all checkboxes are checked, then add class to something

I need to add a class to an element after all input checkboxes are checked, without having the need to click on a submit button. I'd much prefer not to get jQuery involved since this would be the only javascript element on the page. Here's what I have so far and it looks like it's adding the class after the first click on the checkbox, which is not what I want.

Codepen link

JS

function showMe (box) {
  var checkbox = document.getElementsByName("selectPlant");
  for(var i=0;i<checkbox.length;i++) {
    if(checkbox[i].checked){
      document.getElementById(box).classList.add('show');
    }
  }
}

HTML

<a href="#" id="reward" style="opacity:0">
  TADA!
</a>
<form action="" id="">
  <input type="checkbox" name="selectPlant" onclick="showMe('reward')">
  <input type="checkbox" name="selectPlant" onclick="showMe('reward')">
  <input type="checkbox" name="selectPlant" onclick="showMe('reward')">
  <input type="checkbox" name="selectPlant" onclick="showMe('reward')">
</form>

CSS

#reward {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: red;
  color: white;
  pointer-events: none;
}

#reward.show {
  opacity: 1 !important;
}

input[type=checkbox] {
  width: 40px;
  height: 40px;
}

Any help would be awesome!




C# WPF Checkbox with null value?

I am currently making a GUI in WPF, and am working on a page intended to create and configure message rooms but the following code below

else if (Password_Enabled.IsChecked == true && Password.Text.Length == 0)
        {
            return false; 
        }

appears with an error of

Password_Enabled.IsChecked 'Password_Enabled.IsChecked' threw an exception of type 'System.NullReferenceException'

My Xaml for the CheckBox appears as follows

<CheckBox x:Name="Password_Enabled" IsChecked="False" Content="Password Enabled" HorizontalAlignment="Left" VerticalAlignment="Top" Checked="Password_Enabled_Checked" Unchecked="Password_Disabled_Checked" Margin="10,5,0,0" Grid.RowSpan="2"/>

I've searched online, but with errors like these it's standardised, I know it means that the checkbox is being treated as null. But while searching through my code haven't found anything stating why, any help on this would be much appreciated, thank you.




How to remove the tick in a custom checkbox?

How can I remove the tick in the checkbox and replace it to a letter?

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

w3schools.com or JSFiddle




Access: Dropdown list of CheckBoxes

I'm trying to figure out how to replicate something I did in VB.Net. I'm trying to create a dropdown box of checkboxes so that users can pick multiple options. I've been able to create the dropdown box, but am having trouble figuring out how to add checkboxes, and how to make it so long sentences aren't cut off (See highlighted).enter image description here

I'm trying to stay away from using any type of VBA code, but if that's the only way to do it I guess i'll have to bite the bullet.




How to center bootstrap custom-checkbox in a table header col

Maybe a dumb question but in a table head, I have to place the custom checkbox from bootstrap 4 in a col. and I can't center it.. the text-center class has no effects

here is : myfiddle

<tr class="text-white text-center bg-dark">
      <th scope="col" class="align-middle">
        <div class="custom-control custom-checkbox">
          <input type="checkbox" id="customCheck1" class="custom-control-input">
          <label for="customCheck1" class="custom-control-label"></label>
        </div>
      </th>
      <th scope="col" class="align-middle">Head-Col-1</th>
      <th scope="col" class="align-middle">Head-Col-2</th>
      <th scope="col" class="align-middle">Head-Col-3</th>
      <th scope="col" class="align-middle">Head-Col-3</th>
      <th scope="col" class="align-middle">Head-Col-3</th>
      <th scope="col" class="align-middle">Head-Col-3</th>
    </tr>

Thanks in advance




PHP Set a hook in a checkbox if the value is 1 or uncheck if the value is 0

i hope you can help me, i think the solution is simple, but i am beginner, so kick my brain.

Now i want on a new page that the checkbox will be shown as either checked or unchecked depending on the result.

The results are available as 1 or 0, but how can I now display a checkbox as checked or unchecked?

I'm grateful for every tip.




Javafx listview with CheckBoxListCell doesn't work with Drag and Drop

I have a ListView with with a custom CheckBox Item called CheckBoxListItem. Everthing looks good but now I need to implement Drag and Drop for easier sorting.

I know that I have to use a custom CellFactory and set the Drag and Drop Events to the cell itself. My Problem is that I already have a CellFactory and dont know how to add the Events.

The commented code is what I think could be the way to do it but the updateItem method doesn't worked.


My main class:

public class Main extends Application{

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {

        ListView<CheckBoxListItem> listView = new ListView<>();
        ScrollPane scrollPane = new ScrollPane(listView);
        scrollPane.setFitToHeight(true);
        scrollPane.setFitToWidth(true);

        for(int i=1; i<15; i++) {
            listView.getItems().add(new CheckBoxListItem("Value"+i));
        }

        listView.setCellFactory(CheckBoxListCell.forListView(CheckBoxListItem::selectedProperty, new StringConverter<    CheckBoxListItem>() {
            @Override
            public String toString(CheckBoxListItem object) {
                return object.getName();
            }

            @Override
            public CheckBoxListItem fromString(String string) {
                return null;
            }
        }));

        /*
        ObjectProperty<CheckBoxListCell<CheckBoxListItem>> dragSource = new SimpleObjectProperty<>();
        listView.setCellFactory(lv -> {
            CheckBoxListCell<CheckBoxListItem> cell = new CheckBoxListCell<CheckBoxListItem>(){
                @Override
                public void updateItem(CheckBoxListItem item , boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null) {
                        setGraphic(null);
                    }else {
                        setGraphic(?????);
                    }
                }
            };

            cell.setOnDragDetected(event -> {
                //TODO
            });
            cell.setOnDragOver(event -> {
                //TODO
            });
            cell.setOnDragDropped(event -> {
                //TODO
            });
            return cell ;
        });
        */

        Scene scene = new Scene(scrollPane, 350, 450);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void stop() {
        System.exit(0);
    }

}

and CheckBoxListItem.java:

public class CheckBoxListItem {
    private ReadOnlyStringWrapper name = new ReadOnlyStringWrapper();
    private BooleanProperty selected = new SimpleBooleanProperty(false);

    public CheckBoxListItem(String name) {
        this.name.set(name);
    }

    public CheckBoxListItem(String name, boolean selected) {
        this.name.set(name);
        this.selected.set(selected);
    }

    public String getName() {
        return name.get();
    }

    public BooleanProperty selectedProperty() {
        return selected;
    }

    public boolean isSelected() {
        return selected.get();
    }

    public void setSelected(boolean selected) {
        this.selected.set(selected);
    }
}




How to set the check box value in html using angular ts?

I am trying to set the checkbox dynamically with the value I got from an API call. From the API call the received output is [11,12,13] so Voice Call, SMS and Auto Dailer have to be checked. I have set the value like (11,12,13,... ) for each boxes. While submitting the form i have selected the checkboxes 11,12,13. So while loading another page, i have to set these checkboxes to true. Please look at my code below.

In ts File:

modeOfCommunicationData = new Map([[11, 'Voice Call'], [12, 'SMS'],
  [13, 'Auto Dailer'], [14, 'Dailer  Agent'], [15, 'Robo']]);

The API call to get the checkbox value:

loadModeComm_Category(templateId){
    if (templateId != null ) {
      console.log("template ID :", templateId)
      this.tms.GetModeAndCategoryByTemplate(templateId) // tms is the object for the API call from service.ts
      .subscribe(r => {
        this.records = r;
        console.log("onSelectHeaderComm :", this.records);

        let recordData = this.records;
        recordData = recordData.map((val) => {

          this.modeOfComm = val.Record.ModeOfCommunication;             
          console.log("modeOfComm :", this.modeOfComm)//the output is [11,12,13]

          this.modeOfComm.forEach((opt,key) => {  // trying to set the checkboxes to true         
            if(key == arval)
            mocCheckbox.controls[opt].setValue(true);
            });                       
        });
      })
    }
  }

HTML:

  <div class="col-sm-12">
     <div class="sub-title">
        <p> <strong> Mode of Communication </strong> </p>
     </div>
     <div class="communication-checkbox-box" formGroupName="modeOfComm">
         <mat-checkbox color="primary" id="mocSelectAll" (change)="onChangeSelectAll($event)"
                        [(ngModel)]="mocCheck" [ngModelOptions]="{standalone: true}"> Select All </mat-checkbox>
          <div *ngFor="let option of Form.get('modeOfComm').value | keyvalue : customOrder">
          <mat-checkbox color="primary" [formControlName]="option.key" (change)="mocDeSelect($event)"
                            [value]="option.value">  </mat-checkbox>
          </div>
     </div>         
    </div>

Please help me in resolving this issue. It could be better if i get an working code. Thanks in advance.