jeudi 28 février 2019

call different method for two checkbox list

I have two checkbox lists and when any checkbox from any two list is checked i call the method through this event

 $("input[type='checkbox']").change(function () {
            var val = $(this).val();
            if (this.checked) // if changed state is "CHECKED"
            {
                MainClass.onLayer(val);

                // do the magic here
            } else {
                if (val != undefined) {
                    MainClass.offLayer(val);
                }
    //            alert("false");
            }
        });
    });

So now the problem is need to call separate methods for the two checkbox lists?How can i do that?




Vue.Js, binding a value to a checkbox in a component

I'm making a component which is a wrapper around a checkbox (I've done similar with inputs of type 'text' and 'number') but I cannot get my passed in value to bind correctly.

My component is:

<template>
  <div class="field">
    <label :for="name" class="label">
      
    </label>
    <div class="control">
      <input :id="name" :name="name" type="checkbox" class="control" :checked="value" v-on="listeners" />
    </div>
    <p v-show="this.hasErrors" class="help has-text-danger">
      <ul>
        <li v-for="error in errors" :key="error"></li>
      </ul>
    </p>
  </div>
</template>
<script>
export default {
  name: 'check-edit',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    errors: {
      type: Array,
      default: () => []
    }
  },
  mounted () {
  },
  computed: {
    listeners () {
      return {
        // Pass all component listeners directly to input
        ...this.$listeners,
        // Override input listener to work with v-model
        input: event => this.$emit('input', event.target.value)
      }
    },
    hasErrors () {
      return this.errors.length > 0
    }
  },
}
</script>

I've imported it globally; and am invoking it in another view by doing:

<check-edit name="ShowInCalendar" v-model="model.ShowInCalendar" label="Show in calendar?" :errors="this.errors.ShowInCalendar"></check-edit>

My model is in data and the property ShowInCalendar is a boolean and in my test case is true. So when I view the page the box is checked. Using the Vue tools in firefox I can see the model.ShowInCalendar is true, and the box is checked. However, when I click it the box remains checked and the value of ShowInCalendar changes to 'on', then changes thereafter do not change the value of ShowInCalendar.

I found this example here: https://jsfiddle.net/robertkern/oovb8ym7/ and have tried to implement a local data property for it but the result is not working.

The crux of what I'm trying to do is have the initial checkstate of the checkbox be that of ShowInCalendar (or whatever property is bound via v-model on the component) and then have that property be update (to be true or false) when the checkbox is checked.

Can anyone offer me any advice please?

Thank you.




Finding all checkboxes in a Google Sheet

Ever since checkboxes were added to the native Google Sheets UI in 2018, developers have wanted to programmatically read them or treat them in certain manners, such as treating them as "radio buttons", resetting them to "unchecked", or setting them to "checked".

How can we best find checkboxes in a given Google Sheet, so that we avoid accidentally modifying other cells when manipulating their state?

One method is to inspect the values on a worksheet and treat any true/false values as checkboxes:

function getAllCheckboxes() {
  const wb = SpreadsheetApp.getActive();
  const checkboxes = [];

  wb.getSheets().forEach(function (sheet) {
    var rg = sheet.getDataRange();
    var values = rg.getValues();
    var sheetCheckBoxes = [];

    values.forEach(function (row, r) {
      row.forEach(function (val, c) {
        // Checkbox values are stored as `false` (unchecked) and `true` (checked)
        if (val === false || val === true) {
          sheetCheckBoxes.push({
            rowIndex: r,
            colIndex: c,
            value: val,
            r1c1: "R" + (r+1) + "C" + (c+1)
          });
        }
      });
    });
    if (sheetCheckBoxes.length) {
      checkboxes.push({
        name: sheet.getName(),
        sheetId: sheet.getSheetId(),
        boxes: sheetCheckBoxes
      });
    }
  });

  return checkboxes; // An array of objects describing a sheet and its checkboxes.
}

However, this won't work in all use cases: the cell might be displayed as the literal TRUE or FALSE, and not as a checkbox. The above code will treat it as though it is one, because it shares the same value.




How can I create a toggle button checklist with a limit?

I'm having trouble creating a simple toggle button checklist, where the user can only **Toggle-On 3 buttons at a time.

enter image description here

I plan to add a lot of buttons, but only allow a maximum of 3 Toggle-on buttons at a time.

How do I accomplish something like this?

I attempted using JQuery, but I'm pretty sure I'm doing something wrong. This code only works for checkboxes by themsleves, but not for the Toggle Button Checkbox used in Bootstrap. To replicate this problem you need the latest bootstrap. Here's a fiddle: https://jsfiddle.net/godsnake/t0cswbpo/4/

Please help me figure this out, I'm a complete noob in Jquery and JS and I'm guessing that's how you solve this issue.

JQuery:

var limit = 3;

    $('input.single-checkbox').on('change', function(evt) {
       if($(this).siblings(':checked').length >= limit) {
           this.checked = false;
       }
    });
    <div class="btn-group-toggle pricing-levels-3 d-inline-block" data-toggle="button-checkbox">

HTML

<div class="btn-group-toggle pricing-levels-3 d-inline-block" data-toggle="button-checkbox">


  <label class="btn btn-secondary">
    <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike" type="checkbox" autocomplete="off"> Checked
  </label>

  <label class="btn btn-secondary">
    <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike" type="checkbox" autocomplete="off"> Checked
  </label>



  <label class="btn btn-secondary">
    <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike" type="checkbox"  autocomplete="off"> Checked
  </label>

  <label class="btn btn-secondary">
    <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike" type="checkbox" autocomplete="off"> Checked
  </label>

        </div>




Angular form control array of checkboxes

I have an array of objects that I would like to use as a form control as a list of checkboxes. If a checkbox is checked, it adds the checkbox value to the form control (which is a list and starts out empty). This is what I have so far:

userAddForm = new FormGroup({
  firstName: new FormControl('', [Validators.required,
  Validators.minLength(4)]),
  lastName: new FormControl('', [Validators.required,
  Validators.minLength(4)]),
  email: new FormControl('', [Validators.required,
  Validators.email]),
  username: new FormControl('', [Validators.required,
  Validators.minLength(4)]),
  password: new FormControl('', [Validators.required,
  Validators.minLength(5)]),
});

When the component is initialized, I instantiate the array and build it from a data source, and then I am thinking I have to do this:

this.userAddForm.addControl(this.locations);

But then what would I do in my template to make this work?




Laravel: can't check checkbox

why can't I check this checkbox when I run my code? + how can i do error handling on the checkbox. It needs to be checked before submitting

checkbox code:

<div class="o-grid__col u-12/12">
            <div class="o-grid__col u-12/12@sm">
                {!! Form::checkbox('contact_prerequisite', 'contact_prerequisite', ['class' => 'c-input__checkbox required','id' => 'agree_toc','required']) !!}
                {!! Form::label('contact_prerequisite', __('profile.contactPrerequisite'),['class' => 'c-input__checkboxLabel p2','for' => 'agree_toc']) !!}
            </div>
        </div>

full code:

{!! Form::model($profile,['route' => ['profile.sendmail',$profile->id],'method' => 'POST']) !!}
<div class="events single-event">
    <div class="o-grid">
        <div class="o-grid__col u-6/12">
            <div class="o-grid__col u-12/12@sm">
                <h4>@lang('profile.contactTitle')</h4>
            </div>
            <div class="o-grid__col u-12/12@sm">
                {!! Form::label('', __('profile.contactSalutation').'*') !!}
                @if( Session::get('urlLang') == "en" )
                    {!! Form::select(__('contact_contactSalutation'), array('Miss' => 'Miss', 'Sir' => 'Sir'),array('class' => 'c-dropdown c-dropdown__simple u-mb-x6'),['required' => 'required']) !!}
                @else
                    {!! Form::select(__('contact_contactSalutation'), array('Frau' => 'Frau', 'Herr' => 'Herr'),array('class' => 'c-dropdown c-dropdown__simple u-mb-x6'),['required' => 'required']) !!}
                @endif
            </div>
            <br>
        </div>
        <div class="o-grid__col u-6/12">
            <div class="o-grid__col u-12/12@sm">
                <p style="color: #696978; font-size: 14px; text-align: right">@lang('profile.mandatoryField')</p>
            </div>
        </div>
    </div>
    <div class="o-grid">
        <div class="o-grid__col u-6/12">
            <div class="o-grid__col u-12/12@sm">
                {!! Form::label('contact_first_name', __('profile.contactFirstName').'*') !!}
                {!! Form::text('contact_first_name', null, ['placeholder' => __('profile.contactFirstName'),'class' => 'c-input required','id' => 'contact_first_name','required']) !!}
            </div>
            <div class="o-grid__col u-12/12@sm">
                {!! Form::label('contact_e_mail', __('profile.contactEmail').'*') !!}
                {!! Form::text('contact_e_mail', null, ['placeholder' => __('profile.contactEmail'),'class' => 'c-input required email','id' => 'contact_e_mail','required']) !!}
            </div>
        </div>
        <div class="o-grid__col u-6/12">
            <div class="o-grid__col u-12/12@sm">
                {!! Form::label('contact_last_name', __('profile.contactLastName').'*') !!}
                {!! Form::text('contact_last_name', null, ['placeholder' => __('profile.contactLastName'),'class' => 'c-input required','id' => 'contact_last_name','required']) !!}
            </div>
            <div class="o-grid__col u-12/12@sm">
                {!! Form::label('contact_phone', __('profile.contactPhone')) !!}
                {!! Form::text('contact_phone', null, ['placeholder' => __('profile.contactPhone'),'class' => 'c-input','id' => 'contact_phone']) !!}
            </div>
        </div>

        <div class="o-grid__col u-12/12">
            <div class="o-grid__col">
                {!! Form::label('text', __('profile.contactMessageInfo')) !!}
                {!! Form::textarea('contact_text',null,['class' => 'c-input c-input__text required','placeholder' => __('profile.contactMessageInfo'),'id' => 'contact_text','required']) !!}
            </div>
        </div>

        <div class="o-grid__col u-12/12">
            <div class="o-grid__col u-12/12@sm">
                {!! Form::checkbox('contact_prerequisite', 'contact_prerequisite', ['class' => 'c-input__checkbox required','id' => 'agree_toc','required']) !!}
                {!! Form::label('contact_prerequisite', __('profile.contactPrerequisite'),['class' => 'c-input__checkboxLabel p2','for' => 'agree_toc']) !!}
            </div>
        </div>
        <div class="o-grid__col u-text-right">
            <button id="submit" class="c-btn c-btn--small c-btn--red" type="submit">
                <span>@lang('profile.contactSendMessage')</span></button>
        </div>
    </div>
</div>






How to get all checked checkboxes in WPF?

I tried to find any solutions for this problem but I did not succeed. I only found solutions for WinForms which do not work for WPF.

I have a simple form that has some checkboxes on it. I want to know what checkboxes are checked. The only way I know to do it is to create a method for each checkbox like

"Checkbox1_Checked(object sender, RoutedEventArgs e)" 

and add the name of a checkbox in a List (and remove it from list if the box is unchecked).

Is there any other way I can get all the checked checkboxes? Something like

foreach (var cb in this.Controls)
{
    if (cb is Checkbox && cb.IsCheked()) // blablabla
}




Android checkbox losing state on scroll using cursorAdapter

I'm currently working on a simple Android application which will allow a user to add/remove/delete a record from a sqlite DB using checkboxes. The main activity has a listview which renders objects from an exercise adapter. The adapter extends from cursor adapter. The issue I'm having is when selecting a checkbox, then scrolling down the list so that the checkbox is out of view, the state is lost. Here are extracts of my main activity and my exercise adapter:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbManager = new DBManager(this);
        dbManager.open();
        adapter = new ExerciseAdapter(this, dbManager.fetch());
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
    }

    public void deleteExercise(View view) {
        for (int i = 0; i < adapter.getCount(); i++) {
            CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
            if (c.isChecked()) {
                deleteIds.add(adapter.getItemId(i));
            }
        }
        for (Long deleteId : deleteIds) {
            dbManager.delete(deleteId);
            adapter.update(dbManager.fetch());
        }
    }

ExerciseAdapter:

public class ExerciseAdapter extends CursorAdapter {

    public ExerciseAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.exercise, parent, false);}

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Find fields to populate in inflated template
        TextView exerciseTitle = view.findViewById(R.id.exerciseTitle);
        TextView exerciseDesc = view.findViewById(R.id.exerciseDescription);
        TextView exerciseDate = view.findViewById(R.id.exerciseDate);

        // Extract properties from cursor
        String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
        String desc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
        String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));

        // Populate fields with extracted properties
        exerciseTitle.setText(title);
        exerciseDesc.setText(String.valueOf(desc));
        exerciseDate.setText(String.valueOf(date));
    }

    public void update(Cursor cursor) {
        this.swapCursor(cursor);
        this.notifyDataSetChanged();
    }
}

This is adopted code so would like to keep the classes similar to how they are now, unless there is no other option and a big change is required.

Thanks.




How to return boolean values for checkbox checked and unchecked in ANGULAR Material 6

The concept i would want to get is ON selection of a checkbox i want the value to be returned as TRUE and ON de-selection of the same checkbox i want the value to be returned as False

This is my HTML code

<div class="form-group m-form__group row">
                                        <div class="col-lg-4">
                                            <mat-checkbox class="example-margin" type= checkbox value = "true" formControlName ="rti_cover" [checked] = "true">RTI</mat-checkbox>
                                        </div>
                                        <div class="col-lg-4">
                                            <mat-checkbox class="example-margin" type= checkbox value = "true" formControlName ="nildep_cover" [checked] = "true" >Nil Dep</mat-checkbox>
                                        </div>
                                    </div>




Weird checkbox behaviour in Edge

I made a group of checkboxes that look like this in chrome: enter image description here if you deselect the 3. one, the second one is enabled. this works perfectly in all browsers except for Edge.

In Edge it looks like this: enter image description here

CSS:

-webkit-backface-visibility:hidden
-webkit-text-size-adjust:auto
-webkit-transition-delay:0s
-webkit-transition-duration:0s
-webkit-transition-property:all
-webkit-transition-timing-function:cubic-bezier(0.25, 0.1, 0.25, 1)
-webkit-user-select:text
background-color:rgba(17, 117, 217, 0.05)
background-image:none
background-position-x:0%
background-position-y:0%
background-repeat:repeat
background-size:auto
border-bottom-left-radius:4px
border-bottom-right-radius:4px
border-top-left-radius:4px
border-top-right-radius:4px
box-shadow:none
box-sizing:border-box
color:rgb(51, 51, 51)
cursor:pointer
display:inline-block
font-family:"Open Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol"
font-size:16px
font-weight:600
height:124px
left:0px
line-height:24px
margin-bottom:0px
padding-bottom:16px
padding-left:52px
padding-right:16px
padding-top:12px
pointer-events:auto
position:relative
text-align:left
top:0px
transition-delay:0s
transition-duration:0s
transition-property:all
transition-timing-function:cubic-bezier(0.25, 0.1, 0.25, 1)
width:632px




Get Values through Multiple checkbox using filter

I have a list of students and their courses opted.NOw i need to create a checkbox of those subjects and after clicking a particular subject the list of students who have opted that particular subjects should be displayed.Need to do this just by using FILTER no formControl or any other method. IN HTMl

<div class="container">
<div class="row">
<div class="col-4" (change)="(show(crse))">
   <input type="checkbox" [(ngModel)]="and">
  <label>Android</label><br>
   <input type="checkbox" [(ngModel)]="ang">
  <label>Angular</label><br>
   <input type="checkbox" [(ngModel)]="java">
  <label>Java</label><br>  
  <input type="checkbox" [(ngModel)]="ALL">
  <label>All</label><br>  
  </div>
  <div class="col-8">
   <div class="row">
    <div class="col-6 bg-dark text-light">Name</div>
    <div class="col-6 bg-dark text-light">Course</div>
    </div>
    <div class="row" *ngFor="let st of showStudents">
    <div class="col-6 border"></div>
    <div class="col-6 border"></div>
   </div></div></div></div>

in .Ts

allStudents : Student[]=[
{name:'James',course:'Angular'},
{name:'Kary',course:'Android'},
{name:'Bob',course:'Java'},
{name:'Pam',course:'Java'},
{name:'Steve',course:'Angular'},
{name:'Williams',course:'Android'},
{name:'Julis',course:'Angular'},
{name:'Matt',course:'Java'},
{name:'Willy',course:'Android'},
  ];

showStudents:Student[]=[];
showCourses:string[];

crse:string='';
ang:boolean=false;
and:boolean=false;
java:boolean=false;
ALL:boolean=false;
s:string='Angular';

show(crse) {
if(this.ALL===true){
this.showStudents=this.allStudents;
this.showStudents;
 }
 else if(this.ang===true){ 
 this.allStudents.course==this.s;
 this.showStudents=this.allStudents;
  }}

there might be some useless variables also which i might have created while i was trying different methods.

Please help!!

https://stackblitz.com/edit/angulaar-aman?file=src%2Fapp%2Fapp.component.ts this is the entire work.




mercredi 27 février 2019

Checkbox not working within mapping function react js css

i have a mapping function within modifiers.js that is used by itemlist to show checkboxes inside a pop up, after doing this mapping function, the checkbox stopped working, i think it is the css (hidden checkbox communication) because it works well without css.

Modifiers.js

import React from "react";
import "./Modifiers.css";

//import "./Modifiers.scss";

const Modifiers = props => {
  const id = props.childId + props.childp
  return (
    <form className="form">
      <div>
        <h2>{props.title}</h2>
          <div className="inputGroup">
          {props.options && props.options.map(item => {
              console.log(item)
                return (
                    <div>
                      <label for={id}>{item.name}</label>
                      <input
                      id={id}
                      name="checkbox"
                      type="checkbox"
                    />
                    </div>
                )
              })}
          </div>
      </div>
    </form>
  );
};

export default Modifiers;

Modifiers.css

.inputGroup {
  background-color: #fff;
  display: block;
  margin: 10px 0;
  position: relative;
  border-radius: 20px;
}
.inputGroup label {
  padding: 12px 30px;
  width: 100%;
  display: block;
  text-align: left;
  color: #3c454c;
  cursor: pointer;
  position: relative;
  z-index: 2;
  border-radius: 20px;
  transition: color 200ms ease-in;
  overflow: hidden;
}
.inputGroup label:before {
  width: 90%;
  height: 10px;
  content: "";
  background-color: #5562eb;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%) scale3d(1, 1, 1);
  transition: all 300ms cubic-bezier(0.4, 0, 0.2, 1);
  opacity: 0;
  z-index: -1;
}
.inputGroup label:after {
  width: 32px;
  height: 32px;
  content: "";
  border: 2px solid #d1d7dc;
  background-color: #fff;
  background-image: url("data:image/svg+xml,%3Csvg width='32' height='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M5.414 11L4 12.414l5.414 5.414L20.828 6.414 19.414 5l-10 10z' fill='%23fff' fill-rule='nonzero'/%3E%3C/svg%3E ");
  background-repeat: no-repeat;
  background-position: 2px 3px;
  border-radius: 50%;
  z-index: 2;
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all 200ms ease-in;
}
.inputGroup input:checked ~ label {
  color: #fff;
}
.inputGroup input:checked ~ label:before {
  transform: translate(-50%, -50%) scale3d(56, 56, 1);
  opacity: 1;
}
.inputGroup input:checked ~ label:after {
  background-color: #54e0c7;
  border-color: #54e0c7;
}
.inputGroup input {
  width: 32px;
  height: 32px;
  order: 1;
  z-index: 2;
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  visibility: hidden;
}
.form {
  padding: 0 16px;
  max-width: 100%;
  margin: 50px auto;
  font-size: 18px;
  font-weight: 600;
  line-height: 36px;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}
html {
  box-sizing: border-box;
}
code {
  background-color: #9aa3ac;
  padding: 0 8px;
}

and the rest of the code you can find on codebox.

https://codesandbox.io/s/p32k93k660?fontsize=14&moduleview=1




Qt How to know when a checkbox is selected when created dynamically?

I am trying to dynamically create a checkbox for each restaurant in a vector. I was able to dynamically create checkboxes, but I would then like to know which ones were selected. Here is my code:

for(unsigned int i = 0; i < restaurantList.size(); i++)
{
   QCheckBox *thisCheckBox = new QCheckBox(restaurantList.at(i).GetName());
   CTui->verticalLayout->addWidget(thisCheckBox);
}

I currently have 5 restaurants filled in the vector, and as of now I have it look something like this:

() McDonalds

() Papa John's

() Burger King

() Dominos

() Taco Bell

When they click an "OK" button, I would like to know which ones were selected. They are all called thisCheckBox, so I don't know how to get each specific one. How can I do this? Any help is much appreciated!




Make required checkbox with input name

I have a very simple checkbox:

Can't able to make required with jQuery based on just the input name. Do you have any idea how to solve this?




Emmet wrap with abbreviation

I'm trying to make a checklist in a more time saving way. I have to do this thing underneath for every page like 17 times. So to save some time I was hoping for Emmet to be te solution. What's the abbreviation to produce the following code after selecting the lines below:

Video
DVD
CD

To produce:

<div class="form-group">
   <div class="col-sm-12">
     <div class="checkbox">
        <label>
          <input type="checkbox" name="item1" value="Done" /> Video
        </label>
      </div>
    </div>
</div> <!-- form-group -->
<div class="form-group">
   <div class="col-sm-12">
     <div class="checkbox">
        <label>
          <input type="checkbox" name="item2" value="Done" /> DVD
        </label>
      </div>
    </div>
</div> <!-- form-group -->
<div class="form-group">
   <div class="col-sm-12">
     <div class="checkbox">
        <label>
          <input type="checkbox" name="item3" value="Done" /> CD
        </label>
      </div>
    </div>
</div> <!-- form-group -->




mardi 26 février 2019

How to identify checkboxes in a flat pdf?

Team,

I have to validate a flattened pdf as part of a requirement. This pdf has checkboxes. I used Apache PDFBOX library to read the contents of this PDF. It is only reading the text but not identifying the checkboxes. Please find attached a screenshot of a similar pdf file that i am using Flat PDF with Checkbox :

enter image description here

Can you please provide me any approach to identify and validate these checkboxes

Code Snippet used

        PDFTextStripper stripper = new PDFTextStripper() ;
        PDDocument document = new PDDocument() ;            
        document = PDDocument.load(new File("D:\\test.pdf"));
        stripper.setStartPage(1);
        stripper.setEndPage(1);
        stripper.setSortByPosition(true);
        pdfTextContent = stripper.getText(document);
        System.out.println(pdfTextContent);




Material UI checkbox complaining to be uncontrolled

I'm using Material UI kit for React. I'm making Checkboxes dynamically from states and updating them,

But I'm getting uncontrolled element error.

this.state = {
    services : [{service: "s1", value: 1},
                {service: "s2", value: 2},
                {service: "s3", value: 3},
               ]
};

handleServiceCheck = (i) => {
    let services = this.state.services;
    services[i].value = !services[i].value;
    this.setState({ services: services });
};

this.state.services.map((service, i) => (
    <FormControlLabel key={i}
        control={
            <Checkbox
                checked={service.value}
                onChange={() => this.handleServiceCheck(i)}
                value={service.service}
                className={classes.checkBox}
            />
        }
        label={service.service}
    />
))

Uncontrolled Input Element




Check box conditional formatting formula google sheets

What can be the way to cut a specific row and paste it into another tab of same sheet when checkbox condition meet is true?




use checkboxes to update a counter

I have some labels in a frame with checkboxes and I would like to update a counter each time a checkbox is ticked (or unticked). So far I failed to implement it... I would like the output to appear in the text: number of flag1/flag2 selected (/10): with the overal number corresponding to how many flag1/flag2 boxes have been ticked.

I'd like the update to be triggered as soon as a box is checked.

I am adding the code below. Any help would be greatly appreciated! Regards, Pierre.

import tkinter as tk
import webbrowser


class Pierre:
    def __init__(self, master, urls, chk_lbl):
        self.urls = urls
        self.chk_lbl = chk_lbl
        self.counter = 0
        self.vars = []

        i=0
        for url in self.urls:
            lbl = tk.Label(master, text=url, fg="blue", cursor="hand2")
            lbl.grid(row=i, column=1)
            lbl.bind("<Button-1>", self.callback)


            ic = 2
            for lbl in self.chk_lbl:
                var = tk.IntVar()
                chk = tk.Checkbutton(master, text=lbl, variable=var)
                chk.grid(row=i, column=ic)
                self.vars.append(var)
                ic += 1
            i+=1

    def state(self):
        return map((lambda var: var.get()), self.vars)

    def callback(self, event):
        webbrowser.open_new(self.url)

class TestClass(tk.Tk):
    def __init__(self, **kwargs):
        root = tk.Tk.__init__(self, **kwargs)
        self.title('Test')

        # --- Changes starts from here --- #
        def onFrameConfigure(canvas):
            canvas.configure(scrollregion=canvas.bbox('all'))

        self.topframe = tk.Frame(root)
        self.topframe.pack(side=tk.TOP, pady=30)

        self.canvas = tk.Canvas(root)
        self.bottomframe = tk.Frame(self.canvas)
        # self.bottomframe.pack( side = tk.BOTTOM )
        self.scrollbar = tk.Scrollbar(root, orient='vertical', command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.scrollbar.set)
        self.canvas.pack(side=tk.LEFT, fill='y')
        self.scrollbar.pack(side=tk.LEFT, fill='y')
        self.canvas.create_window(0, 0, window=self.bottomframe, anchor='nw')
        self.bottomframe.bind('<Configure>', lambda event, canvas=self.canvas: onFrameConfigure(self.canvas))
        # --- Changes ends here --- #

        self.button = tk.Button(self.topframe, text='Click', command=self.output_value)
        self.button.pack(side="left", fill="both", expand=True)

        iai = 1 # hardcoded value. should be set to the number of time flag1 has been ticked over all labels
        ihf = 2 # hardcoded value. should be set to the number of time flag2 has been ticked over all labels

        tk.Label(self.topframe, text='number of flag1 selected (/10):%i' % iai).pack() 
        tk.Label(self.topframe, text='number of flag2 selected (/10):%i' % ihf).pack() 


    def output_value(self):
        urls = ["http://www.google.com", "http://www.facebook.com", "http://bbc.co.uk"]
        chk_lbl = ['flag1', 'flag2']
        Pierre(self.bottomframe, urls, chk_lbl)

if __name__ == "__main__":
    root = TestClass()
    root.mainloop()




JS Tree Selecting un selected items

I am using JsTree checkbox which contains lot of sub fields.

When I am selecting one field it automatically selects the sub category of another field.

So that field shows partially checked.

For instance:

In my JsTree When I clicked "United States" it partially selects "Canada".

Please any one explains this behavior.

Since the tree is big I am not pasting the code instead of that I am posting an JsFiddle URL. Code:

$(function () {
    $("#tree").jstree({
        "checkbox": {
            "keep_selected_style": false
        },
            "plugins": ["checkbox"],
                                'core': {
                                    'data': {
  "id": "ALL",
  "text": "ALL",
  "children": [] ...

JSFiddle : http://jsfiddle.net/1r70vjmx/

Thanks in Advance.




Multiple selection on menu checkbox for Android

I'm trying to create a menu with filters on a map, the idea is to select multiple elements (like the screenshoot). But the problem is that every time I press an option, the menu is automatically hidden.

So I can only tap one checkbox everytime I open the menu. This behaviour is not the best because user has to open N times the menu to select N filters.

Any suggestion or advice about how to solve this? Thanks!

introducir la descripción de la imagen aquí

And this is my code (reduced to be more readable):

map_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_filtro"
        app:showAsAction="always" >

        <menu>
        <group android:checkableBehavior="all">
        <item
            android:id="@+id/nav_ciencia"
            android:icon="@drawable/ciencia"
            android:title="@string/filtro_ciencia"
            app:showAsAction="never"

             />
        <item
            android:id="@+id/nav_comercio"
            android:icon="@drawable/comercio"
            android:title="@string/filtro_comercio"
            app:showAsAction="never"
             />
        <item
            android:id="@+id/nav_cultura"
            android:icon="@drawable/cultura"
            android:title="@string/filtro_cultura"
            app:showAsAction="never"
             />
        <item
            android:id="@+id/nav_deporte"
            android:icon="@drawable/deporte"
            android:title="@string/filtro_deportes"
            app:showAsAction="never"
             />
        </group>
        </menu>
</item>
</menu>

Activity

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

        SharedPreferences prefs = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE);

        MenuItem item_ciencia = menu.findItem(R.id.nav_ciencia);
        item_ciencia.setChecked(prefs.getBoolean(Constants.pref_nav_ciencia, false));
        MenuItem item_comercio = menu.findItem(R.id.nav_comercio);
        item_comercio.setChecked(prefs.getBoolean(Constants.pref_nav_comercio, false));
        MenuItem item_cultura = menu.findItem(R.id.nav_cultura);
        item_cultura.setChecked(prefs.getBoolean(Constants.pref_nav_cultura, false));
        MenuItem item_deporte = menu.findItem(R.id.nav_deporte);
        item_deporte.setChecked(prefs.getBoolean(Constants.pref_nav_deporte, false));
        return true;
    }

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        SharedPreferences prefs = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        if (id == R.id.action_settings) {

            return true;
        }else  if (id == R.id.nav_ciencia) {
            item.setChecked(!item.isChecked());
            editor.putBoolean(Constants.pref_nav_ciencia, item.isChecked());
            editor.commit();
            return true;
        } else if (id == R.id.nav_comercio) {
            item.setChecked(!item.isChecked());
            editor.putBoolean(Constants.pref_nav_comercio, item.isChecked());
            editor.commit();
            return true;
        } else if (id == R.id.nav_cultura) {
            item.setChecked(!item.isChecked());
            editor.putBoolean(Constants.pref_nav_cultura, item.isChecked());
            editor.commit();
            return true;
        } else if (id == R.id.nav_deporte) {
            item.setChecked(!item.isChecked());
            editor.putBoolean(Constants.pref_nav_deporte, item.isChecked());
            editor.commit();
            return true;
        } 

        return super.onOptionsItemSelected(item);
    }




Excel checkbox forms has a strange size (smaller) on another device

I've got a strange issue with sizes of Microsoft excel controls (both Form Controls and ActiveX Controls).

On my laptop - W10x64, Office 2016 x64 - everything it's ok.

On another laptop W10x64, Office 2013 but with a touch screen, these issues appear ... see please the attached image.

Thanks in advance for your help!

Check Box size




lundi 25 février 2019

React redux Form checkbox `defaultChecked` not working

<Field
   defaultChecked={true}
   onChange={this.handleFormItemRadio}
   component={'input'}
   type={'checkbox'}
    name="tadmin" />

When the field is initialized, i expect it to be checked but it comes empty yet aim supplying in true value.

poited to number of solutions but am still not able to solve this.




How to add checkboxes to Multi Select in IE 11

I want to add checkboxes via css to a Multi Select using IE 11. The css I use works in Edge etc. , but does not for IE 11.

CSS and code:

<style>
option:before 
{
    content: "☐ "
}

option:checked:before 
{
    content: "☑ "
}

<select class="ddlRole" id="ddlRole" style="width: 810px;" size="6" multiple="">
    <option value="1">Administrator</option>
    <option selected="selected" value="2">Manager</option>
    <option value="3">User</option>
    <option selected="selected" value="4">Sub Manager</option>
    <option value="8">new role test 5</option>
</select>

Alternatively I'll use a table with 2 columns, the first being a checkbox column, the next the text/name of the option. Possibly even an expanded Ul with Li?, Though I really would rather not.

Thanks




Style a Bootstrap 4 Checkbox without label

I'm trying to style a Bootstrap 4 checkbox without a label:

<div class="form-check">
    <input class="form-check-input position-static" type="checkbox" id="blankCheckbox" value="option1">
</div>

My trial and error styles:

  .form-check {
      .form-check-input {
        color: #2c2b2c;
        font-size: 12px;
        line-height: 2.7;
        padding-left:15px;
        text-transform: uppercase;
        background-color: red;
      }
      .form-check-input::after,
      .form-check-input::before {
        height: 25px;
        width: 25px;
      }
      .form-check-input::before {
        background-color: #fff;
        border: 1px solid #2c2b2c;
      }
    }
  }

I'm able to style the label version, but unsuccessful with this version.




Get several values from checkbox

I'd like to get seevral values from checkboxes. The site is a Wordpress with a form created with cutom fields :

form table

If a user is checking a box (or several boxes), I need to get all the values for the line he checked. For now, I only need to return a mail for the site's owner.

Does someone have some clue about it ? Thanks




dimanche 24 février 2019

ASP.NET Clear CheckBox List in Function

I am trying to implement a Clear All Checkboxes upon a checkbox toggle.

<div class="form-group" id="divSelectDay" >
    <label class="control-label col-md-2" id="lblSelectDay">Select Day of Week</label>
    <div class="col-md-3">
        <div class="input-group">
            <asp:CheckBoxList ID="chkSelectDay" CssClass="chkLabel" ClientIDMode="Static" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table"> 
                <asp:ListItem Value="Monday">Mon</asp:ListItem>
                <asp:ListItem Value="Tuesday">Tue</asp:ListItem>
                <asp:ListItem Value="Wednesday">Wed</asp:ListItem>
                <asp:ListItem Value="Thursday">Thu</asp:ListItem>
                <asp:ListItem Value="Friday">Fri</asp:ListItem>
                <asp:ListItem Value="Saturday">Sat</asp:ListItem>
                <asp:ListItem Value="Sunday">Sun</asp:ListItem>
            </asp:CheckBoxList>
        </div>
    </div>
    <label class="control-label col-md-2"></label>
</div>  

On the same page, I have an existing toggle function, which shows/hide the checkbox list whenever "Daily" checkbox is checked or not. But it does not clear them.

function ToggleExecutionSchedule(controlId) {
    var frmControl = document.getElementById(controlId.id);
    var divDay = document.getElementById("divSelectDay");

    var checkbox = frmControl.getElementsByTagName("input");
    var counter = 0;
    for (var i = 0; i < checkbox.length; i++) {
        if (checkbox[i].checked)
        {
            if (checkbox[i].value == "Weekly")
                divDay.style.display = 'block';
        }
        else
        {
            if (checkbox[i].value == "Weekly") {
                divDay.style.display = 'none';
                //clear divDay/chkSelectDay checkboxlist <===
            }
        }
    }
}

I saw some articles on using CheckBoxList1.Items.Clear();, but I am unable to retrieve the value of my checkboxlist chkSelectDay inside my function.

Thank you.




Preventing Endless Loop on Checkbox Input Conditional

I have a form submission process where I have middleware with if/else statements are validating that values are present before my authentication controller is triggered, but for some reason my Checkbox input field is triggering ERR_TOO_MANY_REDIRECTS on form submission and even when I try to load the form page after the submission. The reason for my undefined check is because I noticed that the body does not contain this input if the value isn't checked. Is there a better condition to use to check if this value is checked or not checked that will eliminate the redirect loop I am seeing? Is there a way to set this middleware to only trigger on the POST portion of the route?

Middleware that I am using for /sign-up:

siteRoutes.use('/sign-up', function(req, res, next){
    console.log("Sign Up Use")
    console.log(req.body);
    models.User.findOne({
        where: {
            email: req.body.email
        }
    }).then(function(existingUser) {
    if (existingUser){
        req.flash('error', 'Email already exists.');
        return res.redirect('/sign-up');
    } else if (req.body.termsOfService === undefined) {
        console.log("TOS Check")
        req.flash('error', 'Accept terms');
        return res.redirect('/sign-up');
    } else {
        console.log("Next")
        next();
    }
    });
});

Input Fields:

   <input type="text" class="form-control" id="sign-up-fist-name"  name="firstName" value="" placeholder="First Name">
                <br />
                    <input type="text" class="form-control" id="sign-up-last-name"  name="lastName" value="" placeholder="Last Name">
                <br />
                    <input type="text" class="form-control" id="sign-up-username"  name="email" value="" placeholder="Email Address">
                <br />
                    <input type="password" class="form-control" id="sign-up-password"  name="password" value="" placeholder="Password">
                <br />
                    <input type="password" class="form-control" id="sign-up-confirm-password"  name="confirmPassword" value="" placeholder="Confirm Password">
                <br />
                    <label>
                        <input type="checkbox" name="termsOfService"> I confirm that I have read, consent and agree to Synotate's <a href="/terms-of-service">Terms of Service</a> and <a href="privacy-policy">Privacy Policy</a>
                    </label>




how to pass a value in a foreach loop in php when there is an exit in it

It is about this situation:

For copying files in a filemanagement, i use checkboxes which can be clicked. Every checkbox has its own value; the file! Like: uploads/image1.jpg or uploads/image2.jpg

All values are bind to 1 variable, $checkboxfiles (so its an array of files). For copying the checked files to another folder, i do a check if a file with the same name already exists in that folder. If yes, i show a popup with a form to confirm for overwriting or not.

The php code:

// Multiple copy and move (checkboxes)
if( isset($_POST["checkboxes_value"]) && isset($_POST["cbdestination"]) ) {

$checkboxfiles = explode("," , $_POST["checkboxes_value"]); // contains multiple values of files

foreach($checkboxfiles as $checkboxfile) {      
    $src_file = $checkboxfile;
    $fileName = basename($src_file);
    $new_dest = $_POST['cbdestination'];

    /* New path for this file */
    $dest_file = $MainFolderName.'/'. $new_dest . '/' . $fileName;

    /* check for overwriting */
    $allow = $_POST['overwrite'];
    if($allow == '') { // if not empty, the request comes from the popup and is confirmed
        if(file_exists($dest_file)) {                   
            include('alerts/file_copy_exists.php'); // includes a form to confirm overwriting                       
            exit; // i must use this and wait for confirmation
        }       
    }

    $copy = copy( $src_file, $dest_file );
    // and so on...

} // end foreach

The problem: Lets say i check 3 files, and want to copy them to another folder. 2 of them with the same name already exists in that folder. In that case, i have to use the exit; in the overwrite loop and wait for confirmation. But when i use the exit, the foreach works not anymore. The popup for the last file only appears.

When not using the exit; , 2 popups appear to confirm. But in that case, the files are already overwritten. So these popups are useless!

How can i deal with this situation?




Add Text Value to a Userform TextBox if Checkbox value if statement is TRUE

I have a userform to update my currency analysis sheets. I have a checkbox on the top right that will dictate whether the date from date picker is holiday or not. If it is (meaning the checkbox is checked and therefore TRUE, then all of the textboxes will become a value of "HOL". If unchecked (or FALSE) the the textboxes will be a value of blank and I can enter the daily numbers before clicking the Submit command button to send to the sheets. Of course I would like the HOL to be the value sent to the sheets if the Checkbox value is TRUE. Please help...thanks in advance. The Check box name is HOLIDAY.

Here is the userform

Daily entry userform

and Here is the code

Private Sub HOLIDAY_Click()
    If Me.HOLIDAY.Value = True Then
    Me.DTPicker1.Value = "HOL"
    Me.JP_Open.Value = "HOL"
    Me.JP_Hi.Value = "HOL"
    Me.JP_Lo.Value = "HOL"
    Me.JP_Close.Value = "HOL"
    Me.CAD_Open.Value = "HOL"
    Me.CAD_Hi.Value = "HOL"
    Me.CAD_Lo.Value = "HOL"
    Me.CAD_Close.Value = "HOL"
    Me.GBP_Open.Value = "HOL"
    Me.GBP_Hi.Value = "HOL"
    Me.GBP_Lo.Value = "HOL"
    Me.GBP_Close.Value = "HOL"
    Me.Swiss_Open.Value = "HOL"
    Me.Swiss_Hi.Value = "HOL"
    Me.Swiss_Lo.Value = "HOL"
    Me.Swiss_Close.Value = "HOL"
    Me.AUD_Open.Value = "HOL"
    Me.AUD_Hi.Value = "HOL"
    Me.AUD_Lo.Value = "HOL"
    Me.AUD_Close.Value = "HOL"
    Me.Euro_Open.Value = "HOL"
    Me.Euro_Hi.Value = "HOL"
    Me.Euro_Lo.Value = "HOL"
    Me.Euro_Close.Value = "HOL"
    Me.EURJPY_Open.Value = "HOL"
    Me.EURJPY_Hi.Value = "HOL"
    Me.EURJPY_Lo.Value = "HOL"
    Me.EURJPY_Close.Value = "HOL"
    Me.AUDNZD_Open.Value = "HOL"
    Me.AUDNZD_Hi.Value = "HOL"
    Me.AUDNZD_Lo.Value = "HOL"
    Me.AUDNZD_Close.Value = "HOL"
    Me.EURNZD_Open.Value = "HOL"
    Me.EURNZD_Hi.Value = "HOL"
    Me.EURNZD_Lo.Value = "HOL"
    Me.EURNZD_Close.Value = "HOL"
    Me.NZDCAD_Open.Value = "HOL"
    Me.NZDCAD_Hi.Value = "HOL"
    Me.NZDCAD_Lo.Value = "HOL"
    Me.NZDCAD_Close.Value = "HOL"
    Me.NZDUSD_Open.Value = "HOL"
    Me.NZDUSD_Hi.Value = "HOL"
    Me.NZDUSD_Lo.Value = "HOL"
    Me.NZDUSD_Close.Value = "HOL"
    Me.NZDJPY_Open.Value = "HOL"
    Me.NZDJPY_Hi.Value = "HOL"
    Me.NZDJPY_Lo.Value = "HOL"
    Me.NZDJPY_Close.Value = "HOL"
    Me.GBPJPY_Open.Value = "HOL"
    Me.GBPJPY_Hi.Value = "HOL"
    Me.GBPJPY_Lo.Value = "HOL"
    Me.GBPJPY_Close.Value = "HOL"
Else
    Me.DTPicker1.Value = ""
    Me.JP_Open.Value = ""
    Me.JP_Hi.Value = ""
    Me.JP_Lo.Value = ""
    Me.JP_Close.Value = ""
    Me.CAD_Open.Value = ""
    Me.CAD_Hi.Value = ""
    Me.CAD_Lo.Value = ""
    Me.CAD_Close.Value = ""
    Me.GBP_Open.Value = ""
    Me.GBP_Hi.Value = ""
    Me.GBP_Lo.Value = ""
    Me.GBP_Close.Value = ""
    Me.Swiss_Open.Value = ""
    Me.Swiss_Hi.Value = ""
    Me.Swiss_Lo.Value = ""
    Me.Swiss_Close.Value = ""
    Me.AUD_Open.Value = ""
    Me.AUD_Hi.Value = ""
    Me.AUD_Lo.Value = ""
    Me.AUD_Close.Value = ""
    Me.Euro_Open.Value = ""
    Me.Euro_Hi.Value = ""
    Me.Euro_Lo.Value = ""
    Me.Euro_Close.Value = ""
    Me.EURJPY_Open.Value = ""
    Me.EURJPY_Hi.Value = ""
    Me.EURJPY_Lo.Value = ""
    Me.EURJPY_Close.Value = ""
    Me.AUDNZD_Open.Value = ""
    Me.AUDNZD_Hi.Value = ""
    Me.AUDNZD_Lo.Value = ""
    Me.AUDNZD_Close.Value = ""
    Me.EURNZD_Open.Value = ""
    Me.EURNZD_Hi.Value = ""
    Me.EURNZD_Lo.Value = ""
    Me.EURNZD_Close.Value = ""
    Me.NZDCAD_Open.Value = ""
    Me.NZDCAD_Hi.Value = ""
    Me.NZDCAD_Lo.Value = ""
    Me.NZDCAD_Close.Value = ""
    Me.NZDUSD_Open.Value = ""
    Me.NZDUSD_Hi.Value = ""
    Me.NZDUSD_Lo.Value = ""
    Me.NZDUSD_Close.Value = ""
    Me.NZDJPY_Open.Value = ""
    Me.NZDJPY_Hi.Value = ""
    Me.NZDJPY_Lo.Value = ""
    Me.NZDJPY_Close.Value = ""
    Me.GBPJPY_Open.Value = ""
    Me.GBPJPY_Hi.Value = ""
    Me.GBPJPY_Lo.Value = ""
    Me.GBPJPY_Close.Value = ""

End If
End Sub

If you need more information or more of my code. Thanks in advance once again.




Get text from CheckButton and store in file in android studio

How to get text from checked checkbox and create those text as .txt file in my internal storage of android mobile.

I tried if-else , List array, but it show error




Woocommerce checkbox issue

In default WC checkout page there is a checkbox for different shipping address. When box is checked form appears, when unchecked form disappears.

What I need is to convert this checkbox in 2 radio buttons. By default first radio button is checked and form is hidden, when I click second radio button form appears...when click again on first radio form disappears.

How can I do this?

I did try to edit code inside form-shipping.php but I can't get it to work.




get all apps list in a multiple checkbox for android

i need to get all apps list in a multiple checkbox for android. it would be great if i can get both xml and java code.

i have got a piece of java code but i dont know how to add the collected data into the list

final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); 
}



samedi 23 février 2019

Delete extra space on top of labels from CSS stylized checkbox

I need some help.

I have been "googling" to find a solution but I wasn't able to find out why I'm getting this extra space on top of each label of my CSS stylized checkboxes.

Also I haven't found any similar question here on stack-overflow.

Even using the developer mode of Chrome and Firefox I see nothing (no margin, no padding) that generates that extra space.

<div class="row">
    <div class="col-12 col-lg-6 flex-order-1"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="1"><span class="fade-yellow-blue">Button A</span></label></div>
    <div class="col-12 col-lg-6 flex-order-3"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="2"><span class="fade-yellow-blue">Button B</span></label></div>
    <div class="col-12 col-lg-6 flex-order-5"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="3"><span class="fade-yellow-blue">Button C</span></label></div>
    <div class="col-12 col-lg-6 flex-order-7"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="4"><span class="fade-yellow-blue">Button D</span></label></div>
    <div class="col-12 col-lg-6 flex-order-9"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="5"><span class="fade-yellow-blue">Button E</span></label></div>
    <div class="col-12 col-lg-6 flex-order-11"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="6"><span class="fade-yellow-blue">Button F</span></label></div>
    <div class="col-12 col-lg-6 flex-order-13"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="7"><span class="fade-yellow-blue">Button G</span></label></div>
    <div class="col-12 col-lg-6 flex-order-2"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="8"><span class="fade-yellow-blue">Button H</span></label></div>
    <div class="col-12 col-lg-6 flex-order-4"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="9"><span class="fade-yellow-blue">Button I</span></label></div>
    <div class="col-12 col-lg-6 flex-order-6"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="10"><span class="fade-yellow-blue">Button J</span></label></div>
    <div class="col-12 col-lg-6 flex-order-8"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="11"><span class="fade-yellow-blue">Button K</span></label></div>
    <div class="col-12 col-lg-6 flex-order-10"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="12"><span class="fade-yellow-blue">Button L</span></label></div>
    <div class="col-12 col-lg-6 flex-order-12"><label class="w-100 boton-check"><input type="checkbox" name="my_buttons[]" value="13"><span class="fade-yellow-blue">Button M</span></label></div>
</div>

Here you can see the extra space over each button: https://codepen.io/herni_hdez/pen/Erqvpb

If I add a rule "margin-top: -1.5rem" they go to the desired position, but the labels overlap among checkboxes: https://codepen.io/herni_hdez/pen/bzXrxN




React - How do I handle checkbox data correctly

While I'm learning React, I started creating a rather simple project. A journey planner for TFL (Transport For London). The app gets some parameters such as From, To, and mode (Tube, Bus, Overground) and sends an API request to TFL API.

The mode data is being put together by 3 checkboxes, tube, bus and overground. It should be send as a string with commas between each word. Something like tube,bus,overground or only bus,overground etc.

This is the way I'm handling the checkbox values:

// Handling checkboxes
    const tubeVal = e.target.elements.tube.checked === true ? "tube" : "";
    const busVal = e.target.elements.bus.checked === true ? "bus" : "";
    const overgroundVal = e.target.elements.overground.checked === true ? "overground" : "";

    let mode = "";
    if (tubeVal && !busVal && !overgroundVal) {
      mode = tubeVal;
    }
    if (!tubeVal && busVal && !overgroundVal) {
      mode = busVal;
    }
    if (!tubeVal && !busVal && overgroundVal) {
      mode = overgroundVal;
    }
    if (tubeVal && busVal && !overgroundVal) {
      mode = tubeVal + "," + busVal;
    }
    if (tubeVal && !busVal && overgroundVal) {
      mode = tubeVal + "," + overgroundVal;
    }
    if (!tubeVal && busVal && overgroundVal) {
      mode = busVal + "," + overgroundVal;
    }
    if (tubeVal && busVal && overgroundVal) {
      mode = tubeVal + "," + busVal + "," + overgroundVal;
    }

Is it the right way to handle checkbox data in React? It doesn't seem right to me.




vendredi 22 février 2019

Boolean value in firestore toggled with check box. Requires 2 clicks to alter value?

I've created an adapter with an OnItemClickListener and set it to a check box. I've succeeded in making the check box toggle a Boolean value in Firebase firestore but it takes 2 clicks to change the value. When clicking the check box it doesn't toggle to checked until the second click. The same goes for unchecking.

The method is called in onCreate.

"done" is the Boolean field in my database.

The check box is on a recycler view nested in another recycler view. This is why it has a nested collection/document and a variable for an ID. I excluded the intents used to create the variables.

private void setUpCheckBox() {

    adapter.setOnItemClickListener(new ToDoAdapter.OnItemClickListener() {

        @Override
        public void onItemClick(DocumentSnapshot documentSnapshot, final int 
        position) {

        final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox_complete);


            Map<String, Object> done = new HashMap<>();

            if (checkBox.isChecked()) {
                checkBox.setChecked(true);
                done.put("done", true);
            }
            if (!checkBox.isChecked()) {
                checkBox.setChecked(false);
                done.put("done", false);
            }

            db.collection("customer2").document(id1).collection("To Do").document(id2)
                    .set(done, SetOptions.merge())
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(CustomerProfile.this, id2, Toast.LENGTH_SHORT).show();

                        }

                    });
        }
    });
}

This is a nested Class in my adapter Class.

private OnItemClickListener listener;

listener is declared in parent class.

class ToDoHolder extends RecyclerView.ViewHolder {

    CheckBox checkBoxComplete;

    public ToDoHolder(@NonNull View itemView) {
        super(itemView);

        checkBoxComplete = itemView.findViewById(R.id.checkBox_complete);

        checkBoxComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION && listener != null) {
                    listener.onItemClick(getSnapshots().getSnapshot(position), position);
                }
            }
        });
    }
}
public interface OnItemClickListener {
    void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
    this.listener = listener;

}

}




Register shiny checkboxInput value on DT

I am able to embed checkbox in each cell of a DT column from reading this post.

Imagine I have a dataframe with a logical column named "value" containing some TRUE values, and I want the checkbox in "value_check" column to appear as checked for those that are TRUE upon app start, like shown below: How would I do so?

enter image description here

library(shiny)
library(DT)

df <- data.frame(item = c("a", "b", "c"), value = c(TRUE, NA, NA))

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
  }
  inputs
}

## obtaining checkbox value
shinyValue = function(id, len) { 
  unlist(lapply(seq_len(len), function(i) { 
    value = input[[paste0(id, i)]] 
    if (is.null(value)) FALSE else value 
  })) 
} 

server <- function(input, output, session) {
  output$tbl <- renderDT(server = FALSE, escape = FALSE, editable = TRUE, options = list(
    dom = 't', paging = FALSE, ordering = FALSE,
    preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
    drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
  ), {
    df$value_check <- shinyInput(checkboxInput, nrow(df), "check")
    df
    }
  )
}

ui <- fluidPage(
  DTOutput("tbl")
)

shinyApp(ui, server)




Why is my gridview populating the incorrect data in my rows?

I am building a bookstore using GridViews and data from my database. There are checkboxes and each row has a quantity textbox. I am validating to make sure the at least one checkbox is checked and that the selected row has a quantity input before hitting submit. When the user hits submit, the data selected should be populated into another gridview.

The issue i am having is that when i select two different books and hit submit, the books populated on the gridview is just repeating only one book twice.

*Also the lblError text is still showing when i set the visibility to false when I submit.

Here's a snippet of the submit button call:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    double saleCount = 0;

    Processor p = new Processor();
    Book objBook = new Book();

    foreach (GridViewRow row in gvBooks.Rows)
    {
        CheckBox chkbx = (CheckBox)row.Cells[0].FindControl("cbBook");
        string title = row.Cells[1].Text;
        string authors = row.Cells[2].Text;
        string isbn = row.Cells[3].Text;
        DropDownList gvType = (DropDownList)row.Cells[4].FindControl("ddBookType");
        DropDownList gvMethod = (DropDownList)row.Cells[5].FindControl("ddMethod");
        TextBox qty = (TextBox)row.Cells[6].FindControl("txtQty");

        String strType = Convert.ToString(gvType.Text);
        String strMethod = Convert.ToString(gvMethod.Text);

        if (chkbx.Checked && !(string.IsNullOrEmpty(qty.Text)))
        {
            panelHeader.Visible = false;
            panelStudentInfo.Visible = false;
            panelCampus.Visible = false;
            panelCatalog.Visible = false;
            panelStudentInfo2.Visible = true;
            panelCampus2.Visible = true;
            panelCatalog2.Visible = true;
            gvBooks.Visible = false;
            gvOrder.Visible = true;
            panelButtons.Visible = false;

            txtStudentID2.Text = txtStudentID.Text;
            txtStudentName2.Text = txtStudentName.Text;
            txtStudentAddr2.Text = txtStudentAddr.Text;
            txtPhoneNo2.Text = txtPhoneNo.Text;
            ddCampus2.Text = ddCampuses.Text;

            lblError.Visible = false;

            int quantity = Convert.ToInt32(qty.Text);
            objBook.Title = title;
            objBook.Authors = authors;
            objBook.ISBN = isbn;
            objBook.BookType = strType;
            objBook.Method = strMethod;
            objBook.Quantity = quantity;

            objBook.Price = p.Calculate(isbn, strType, strMethod);
            objBook.TotalCost = objBook.Price * objBook.Quantity;
            orderList.Add(objBook);

            saleCount += objBook.Quantity;

            orderTotal = objBook.TotalCost + orderTotal;

            p.UpdateDB(isbn, quantity, strMethod, objBook.TotalCost);
        }
        else
        {
            lblError.Text = "* Please select a book & enter a quantity";
            lblError.Visible = true;
        }

        gvOrder.DataSource = orderList;
        gvOrder.DataBind();

        gvOrder.Columns[0].FooterText = "Totals";
        gvOrder.Columns[5].FooterText = saleCount.ToString();
        gvOrder.Columns[6].FooterText = orderTotal.ToString("C2");
    }
}




tkinter checkbox grid scrolling

in my code i have a script for creating a grid of checkboxes, but now it for certain sizes it is bigger than my second monitor, so i want to be able to scroll to other checkboxes, is there any way to do this?

code:

master = Tk()
numberx = 20
numbery = 20
mylist = []
xgrid = 0;ygrid = 0
for i in range(10000):
    mylist.append(Checkbutton(master, text="  "))
    mylist[i].grid(row=ygrid+1, sticky=W, column=xgrid+1)
    mylist[i].configure(bg='light gray')
    xgrid += 1
    if xgrid == numberx:
        ygrid += 1
        xgrid = 0
    if ygrid == numbery:
        break
master.mainloop()




Angular : Issue with checkboxes and multiple select row in PrimeNg DataTable

The combination of these two elements works except for one action: a click in a ckeckbox to select the row doesn't work. However I can click in the checkbox to unselect the row and I can click in the header checkbox to select/unselect all rows. How can I resolve this issue?




Angular material datatable checkbox keep value in array when Select all or select single item and remove if unselect

When user select master checkbox all values must be push to array. Value must splice from array when user unselect specific checkbox and push again to array if select again. Here is my sample code in stackblitz. Thank you in advance.




Why is the ag-grid checkbox behaving like this

I am using ag-grid checkbox selection with angular 6 to show some data in the popup.So it makes sense that the row gets selected on clicking the checkbox .However in my case , simply clicking on a column value is also causing the checkbox to be selected .The following is a screenshot of my problem.Image of my issue

The html code that i am using for my ag-grid is given below

<ag-grid-angular
    style="width:400px;height:274px" 
    class="ag-theme-blue"
    [rowData]="obj"
    [columnDefs]="ColumnDefs"
    [enableSorting]="true"
    [enableFilter]="true"
    [rowSelection]="row"
    (rowSelected)="onRowSelected($event)"

    [rowMultiSelectWithClick]="true"
    (gridReady)="onGridReady($event)"


    [enableColResize]="true"


    >

    </ag-grid-angular>

my grid definition is give below , which i have initialized in ngOnInit function.

this.ColumnDefs=[ {"checkboxSelection":true,"headerName":"Intf","field":"outboundName",sortingOrder: ['asc','desc', 'null'],width:90,cellStyle:{'text-align': "left"}},
{"headerName":"Comp","field":"success_no",sortingOrder: ['asc','desc', 'null'],width:75,cellStyle:{'text-align': "left"}},
{"headerName":"Fail","field":"fail_no",sortingOrder: ['asc','desc', 'null'],width:75,cellStyle:{'text-align': "left"}},
{"headerName":"Exec","field":"running_no",sortingOrder: ['asc','desc', 'null'],width:75,cellStyle:{'text-align': "left"}},

{"headerName":"Total","field":"total",sortingOrder: ['asc','desc', 'null'],width:75,cellStyle:{'text-align': "left"}}]

So please help me in understanding what's happening?




Save multiple checkbox[] check state on page refresh using local storage in php

I have problem to show user checkbox check state after page is refreshed. I tried using local storage but it checks all the checkboxes please help! I have use ajax to load different pages to select the row by checkbox This is input value

<input type="checkbox" id="checkselect" data-name="checkselect[]" class="get_value" value="<?php echo $row['car_booking_id'];?>" onchange="CheckedChange(this)">

And this is my javascript

<script>
 function CheckedChange(obj){  
           var id =  []; 
           id=obj.value;       // id.push($(obj).val());               
           id = id.toString();
           //alert(id);  
           if($(obj).is(":checked"))  
                { 
                     $.ajax({  
                          url:"close_booking_check_state.php",  
                          method:"POST",  
                          data:{id:id},  
                          success:function(data){  
                               $('#result').html(data);  
                          }  
                     }); 
                } 

          else {
                       $.ajax({  
                          url:"close_booking_check_state_delete.php",  
                          method:"POST",  
                          data:{id:id},  
                          success:function(data){  
                               $('#result2').html(data);  
                          }  
                     });          
               }
     }
</script>
<script>

  $(function() {
    // Clicking on an <input:checkbox> should check any children checkboxes automatically
    $('input:checkbox').change( fnTest );
    display();
  });

  function fnTest(e) {
     var checked = [];
  $('input:checkbox:checked').each(function() {
      localStorage.setItem("prevChecked",check);
      var test1=checked.push( $(this).data('name'));
      alert("t",test1);
  });
  //alert("You have selected:\n\n - " + checked.join("\n - ") );
 // localStorage.setItem("prevChecked",checked.join('|'));
  }

  function display(){
  var test=localStorage.getItem("prevChecked");
  alert("r",test);
  //var results = test.split('|');
 // for (var r=0, len=results.length; r<len; r++ ) {
    $('input[data-name="'+test+'"]').prop('checked', true);
  //}
}

</script>




Wordpress CSS gravity form: inline the checkbox

The link to my wordpress page: https://controlehandicap.fr/align/ AS you can see, i try to inline the text, but when i change the % of the width, it collapse the 2 boxes

@media only screen and (min-width: 641px)
.gform_wrapper ul.gform_fields:not(.top_label) .gfield_label {
    float: left;
    width: 29%;
    padding-right: 16px;
    margin-bottom: 16px;
}

Does someone have an idea?




Kivy listitem button with checkbox right side

At the moment when I press a button in a list item button, another list item button widget appear (AttendancelistButton) with a checkbox for each item.

The problem is that the checkbox is in the center of the button. I would like to have the checkbox at the right side for each item button.

class AttendanceListButton(ListItemButton, CheckBox):
   pass

My kv file:

<AttendanceListButton@CheckBox>:
   size_hint: (0.7, 0.7) 

Thank you in advance




jeudi 21 février 2019

Checkbox reveal which items are selected on page

on my page a user can select multiple items. I use a checkbox and iterate over all the items of a user. Now I want to show the user the total price of all the items he selected on that page. So to say the total price of the shopping cart.

How can I access the ids of my items on the same page that the user clicks on them? I know that in the controller I can access them by

Item.find(params[:items])

Thanks a lot in advance :)




ReactJs - checkbox issue on checkall

I got this error in react.js when clicking the check all checkbox and I will deselect the item with "lot_no" and boom, the clicked item gone.

I have 2 states: checked and data where checked contain all item checked by the person, and data is the all items being shown.

I am comparing the checked state to my data, if checked state includes item from data state, the checkbox should be checked otherwise unchecked

Please check my codes and demo as well.

https://stackblitz.com/edit/react-4v7wb6 enter image description here

My example data is this :

const data = [
  {
    document_id: 10095,
    detail_info: []
  },
  {
    document_id: 12221,
    detail_info: []
  },
  {
    document_id: 12226,
    detail_info: [
      {
        id: 738,
        lot_no: "B12345"
      },
      {
        id: 739,
        lot_no: "C12345"
      }
    ]
  },
  {
    document_id: 12229,
    detail_info: [
      {
        id: 740,
        lot_no: "D12345"
      },
      {
        id: 741,
        lot_no: "E12345"
      }
    ]
  }
];
export default data;

Code:

class App extends Component {
  constructor() {
    super();
    this.state = {
      checked:[],
      data: data
    };
  }

  checkBoxClick(item, index, e) {
    let checked = this.state.checked;
    const getIndex = this.state.checked
      .map(e => {
        return e.document_id;
      }).indexOf(item.document_id)

    let index1 = index[0];
    let index2 = index[1];
    if (e.target.checked) {
      if (getIndex === -1) {
        if (index2 === null) {
          checked.push({
            document_id: item.document_id,
            detail_info: []
          });
        } else {
          checked.push({
            document_id: item.document_id,
            detail_info: [item.detail_info[index2]]
          });
        }
        this.setState({ checked: checked });
      } else {
        checked[getIndex].detail_info.push(item.detail_info[index2]);
        this.setState({ checked: checked });
      }
    }

    // uncheck
    else {
      let clickedIndex = checked[getIndex].detail_info.indexOf(
        item.detail_info[index2]
      );

      if (getIndex !== -1) {
        if (index2 === null) {
          checked.splice(getIndex, 1);

        } else {

          // if no more child is checked, remove the parent from checked state
          if (checked[getIndex].detail_info.length===1){
            checked.splice(getIndex, 1);

          } else{

          checked[getIndex].detail_info.splice(clickedIndex, 1);

          }

        }
        this.setState({ checked: checked });

      }

    }
  }
  checkAll(e) {
     let {checked} = this.state
        if (e.target.checked){
            this.state.data.map((item,idx)=>{
                if (item.detail_info.length !==0 ){
                    checked.push({'document_id': item.document_id,
                    'detail_info': item.detail_info
                    })
                } else {
                    checked.push({'document_id': item.document_id,
                    'detail_info': [],
                    })
                }
                this.setState({checked:checked})

            })

        }
        else {
            this.state.data.map((item,idx)=>{
                    this.setState({checked:[]})

            })
        }
  }

  render() {
    return (
      <table>
        <thead>
          <tr>
            <th style=>
              <input type="checkbox" onChange={this.checkAll.bind(this)} /> All
            </th>
            <th>ID. </th>
            <th>Lot No.</th>
          </tr>
        </thead>
        {this.state.data.map((item, idx) => {
          const checkIfExist = obj => obj.document_id === item.document_id;
          let isChecked = this.state.checked.some(checkIfExist);
          return (
            <tbody key={idx}>
              {item.detail_info.length === 0 ? (
                <tr>
                  <td>
                    <input
                    checked={isChecked}
                      type="checkbox"
                      onChange={this.checkBoxClick.bind(this, item, [
                        idx,
                        null
                      ])}
                    />
                  </td>
                  <td>{item.document_id}</td>
                </tr>
              ) : (
                item.detail_info.map((a, b) => {
                  let isCheckedLot = false;
                  this.state.checked.map((c, d) => {
                    if (c.detail_info.length !== 0) {
                      return c.detail_info.map((e, f) => {
                        if (e.id === a.id) {
                          return (isCheckedLot = true);
                        }
                      });
                    }
                  });
                  return (
                    <tr key={b}>
                      <td>
                        <input
                          checked={isCheckedLot}
                          type="checkbox"
                          onChange={this.checkBoxClick.bind(this, item, [
                            idx,
                            b
                          ])}
                        />
                      </td>
                      <td>{item.document_id}</td>
                      <td>{a.lot_no}</td>
                    </tr>
                  );
                })
              )}
            </tbody>
          );
        })}
      </table>
    );
  }
}




How to make it mandatory to check the form's checkbox?

I have a form configured with PHP and I'm lost, I do not know how to make it mandatory to check the checkbox that I put in the terms and conditions. I have put the ID but I do not know how to put it in the PHP file. I do not know if I should add something to the javascript file. I show you the three files so they can tell me how to correct the errors, rather I should add to the PHP file. I have added the PHP code along with the Javascript since I do not know how to add it in any other way.

The form when I give to send shows me the following:

There was an error sending the form. Please try again later

I have several errors in the console when sending the form:

POST https://agrochema.000webhostapp.com/includes/contact.php net::ERR_NAME_NOT_RESOLVED

    send @ jquery-1.12.4.js:17
    ajax @ jquery-1.12.4.js:17
    (anonymous) @ form-script.js:21
    dispatch @ jquery-1.12.4.js:16
    r.handle @ jquery-1.12.4.js:16


-- XHR failed loading: POST "https://agrochema.000webhostapp.com/includes/contact.php"

s

    end @ jquery-1.12.4.js:17
    ajax @ jquery-1.12.4.js:17
    (anonymous) @ form-script.js:21
    dispatch @ jquery-1.12.4.js:16
    r.handle @ jquery-1.12.4.js:16

Thank you

// Archivo PHP 

<?php

//require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/PHPMailerAutoload.php');

$mail = new PHPMailer();


//$mail->SMTPDebug = 3;                               // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'tls://smtp.gmail.com:587';             // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'example@gmail.com';                // SMTP username
$mail->Password = 'Password';                         // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$message = "";
$status = "false";

$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    if( $_POST['form_name'] != '' AND $_POST['form_email'] != '' ) {

        $name = $_POST['form_name'];
        $email = $_POST['form_email'];
        $message = $_POST['form_message'];

        $botcheck = $_POST['form_botcheck'];

        $toemail = 'miguelestabaenlaparra@gmail.com';                // Your Email Address
        $toname = 'Unlock Design';                         // Your Name

        if( $botcheck == '' ) {

            $mail->SetFrom( $email , $name );
            $mail->AddReplyTo( $email , $name );
            $mail->AddAddress( $toemail , $toname );

            $name = isset($name) ? "Name: $name<br><br>" : '';
            $email = isset($email) ? "Email: $email<br><br>" : '';
            $message = isset($message) ? "Message: $message<br><br>" : '';

            $referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

            $body = $name.' '.$email.' '.$message.' '.$referrer;

            $mail->MsgHTML( $body );
                        $mail->SMTPOptions = array(
                        'ssl' => array(
                                'verify_peer' => false,
                                'verify_peer_name' => false,
                                'allow_self_signed' => true
                        ));
            $sendEmail = $mail->Send();

            if( $sendEmail == true ):
                $responseArray = array('type' => 'success', 'message' => $okMessage);
            else:
                $responseArray = array('type' => 'danger', 'message' => $errorMessage);
            endif;
        } else {
            $responseArray = array('type' => 'danger', 'message' => $errorMessage);
        }
    } else {
        $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    }
} else {
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

//$status_array = array( 'message' => $message, 'status' => $status);
//echo json_encode($status_array);

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    
    header('Content-Type: application/json');
    
    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>


// ARCHIVO JAVASCRIPT 

// CONTACT FORM 2 SCRIPT
  // ===========================
  $(function () {
      $('#contact_form2').validator();
      $('#contact_form2').on('submit', function (e) {
          if (!e.isDefaultPrevented()) {
            var url = "includes/contact2.php";
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                  var messageAlert = 'alert-' + data.type;
                  var messageText = data.message;

                  var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                  if (messageAlert && messageText) {
                      $('#contact_form2').find('.messages').html(alertBox).fadeIn('slow');
                      $('#contact_form2')[0].reset();
                      setTimeout(function(){ $('.messages').fadeOut('slow') }, 6000);
                  }
                }
            });
            return false;
          }
      })
  });
<DOCTYPE html>
<body>
    <section class="ulockd-contact-page">
      <div class="container">
        
        <div class="row">
          <div class="col-md-12">
            <div class="ulockd-contact-form ulockd-style-two">
              <form id="contact_form" name="contact_form" class="contact-form" action="includes/contact.php" method="post"
                novalidate="novalidate">
                <div class="messages"></div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <input id="form_name" name="form_name" class="form-control ulockd-form-fg required" placeholder="Nombre"
                        required="required" data-error="Nombre requerido." type="text">
                      <div class="help-block with-errors"></div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <input id="form_email" name="form_email" class="form-control ulockd-form-fg required email"
                        placeholder="Email" required="required" data-error="Email requerido." type="email">
                      <div class="help-block with-errors"></div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <input id="form_phone" name="form_phone" class="form-control ulockd-form-fg required" placeholder="Teléfono"
                        required="required" data-error="Numero de telefono requerido." type="text">
                      <div class="help-block with-errors"></div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <input id="form_subject" name="form_subject" class="form-control ulockd-form-fg required"
                        placeholder="Tema" required="required" data-error="Tema requerido." type="text">
                      <div class="help-block with-errors"></div>
                    </div>
                  </div>
                  <div class="col-md-12">
                    <div class="form-group">
                      <textarea id="form_message" name="form_message" class="form-control ulockd-form-tb required" rows="8"
                        placeholder="Su mensaje" required="required" data-error="Mensaje requerido."></textarea>
                      <div class="help-block with-errors"></div>
                    </div>
                    <input type="checkbox" name="aceptar_terminos" id="aceptar_terminos" value="aceptar_terminos" /> He leído y acepto los <a href="terminos.html" target="_blank">terminos y condiciones</a>
                    <div class="form-group ulockd-contact-btn">
                      <input id="form_botcheck" name="form_botcheck" class="form-control" value="" type="hidden">
                      <button type="submit" class="btn btn-default btn-lg ulockd-btn-thm" data-loading-text="Getting Few Sec...">ENVIAR</button>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          
        </div>
      </div>
    </section>
</body>
</html>



Fill combobox with multiple datasets from the same database column at the same time

I have a combobox that is filled from a database conditionally by checking off one of 10 checkboxes. Each of the 10 checkboxes contains the code below, which selects a portion of column based on a value in column2.

private void Check1_CheckedChanged(object sender, EventArgs e)

    {
        if (Check1.CheckState == CheckState.Checked)
        {
            // SQL Server connection
            SqlConnection conn = new SqlConnection(@"Server = Server; Database = DB; Integrated Security = True");
            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);
                combo1.DisplayMember = "Column1";
                combo1.ValueMember = "ID";
                combo1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                //Exception Message
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }

        if (Check1.CheckState == CheckState.Unchecked)
        {
            combo1.DataSource = null;
        }

Therefore, it is rather trivial to fill the combobox with each separate condition. What I want to do that I'm not sure of the approach, however, is that when more than one checkbox is checked, the combobox will display the data from every checked checkbox at once (all this data will be from the same column). Moreover, when a single checkbox is then unchecked, I only want it to remove its own dataset from the combobox and not everything.

Is this possible?




Text and Input are not on the same line

I am trying to create an "on an off switch" for a project where I can get a questionnaire group of elements. When you run the following code, you will see a div appear on the screen in a group of elements. The text is above the checkbox, I need them to be side by side. Any ideas?

var bigDiv = document.createElement("div")
var fem = document.createElement("P");
var t = document.createTextNode("FooText");
var femI = document.createElement("INPUT");
bigDiv.style.display = 'block';
fem.appendChild(t);
bigDiv.appendChild(fem);
femI.setAttribute("type", "checkbox");
bigDiv.appendChild(femI);
bigDiv.setAttribute("id", "demChoosing")
document.body.appendChild(bigDiv);

P.S - the key words 'fem' and 'demChoosing' don't mean anything




how to correct check checkbox and display if is checked

i use this code to show some text (Checked) when click on 1 or more checkboxes. I use the on because the checkboxes are dynamically created.

It seems that only IE Edge can not deal with it. I have to click twice on a checkbox to show the Checked text. In all other browsers it works immediately. Really don't know what is wrong with the code

<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />

<div class="cb-buttons" style="display:none">Checked</div>

<script>

$(document).on('click','.rafcheckbox',function() {  
  var $checkboxes = $('.rafcheckbox').change(function() {

    var anyChecked = $checkboxes.filter(':checked').length != 0;
    $(".cb-buttons").toggle(anyChecked);
  });
});

</script>




Yii2 form checkbox template

I set the form parameters:

<?
$form = ActiveForm::begin([
    'id' => 'activeForm',
    'action' => 'javascript://',
]);

$checkboxTemplate = '<div class="checkbox">{labelTitle}{beginLabel}{input}<span class="slider round"></span>{endLabel}{error}{hint}</div>';
echo $form->field($aclForm, tbl_RbacActions::IS_DEVELOPMENT)
    ->checkbox([
        'labelOptions' => ['class' => 'switch'],
        'template' => $checkboxTemplate
]);
?>

As a result, it still turns a standard form with standart classes:

<form id="Index-form" class="row col-12 no-gutters" action="javascript://" method="post">
    <input type="hidden" name="_csrf-frontend" value="Lo7lVHTJ9wcN5rdfjK-b7AgW8L4OHEaqI9IsVofZPOl3yKkFBJqAQz-i-y7H3-mdMUmY-H1RcMRBhkU01-F2oA==">
    <div class="form-group field-aclform-is_development required">
        <input type="hidden" name="AclForm[is_development]" value="0">
        <label class="switch">
            <input type="checkbox" id="aclform-is_development" name="AclForm[is_development]" value="1" template="{input}{beginLabel}{labelTitle}{endLabel}{error}"> Is Development</label>
        <div class="help-block"></div>
    </div>
</form>

Why is it adding the template as the input attribute?




How to check a checkbox without unchecking?

I am trying to make a script which somehow will check a checkbox (but not uncheck it if it is already checked). Is there a button / shortcut which will check a checkbox? (Clicking will uncheck it if it is checked, so will tab + space) Is there a way of only checking it (does nothing if it is already checked)

I hope this is clear enough, I need a way of checking a checkbox which won't uncheck it if it is already checked.




Rails Checkbox redesign sometimes sends wrong ids to controller

A user can select multiple products on my page (called vacancies) and then upgrade them. I use a checkbox:

<input type="checkbox"  class="hidden" name="vacancies[]" id="post_vacancy_ids_<%= vacancy.id %>" value="<%=vacancy.id %>">

<label class="category-choice" for="post_vacancy_ids_<%= vacancy.id %>">
  <%= vacancy.title %>
  <i class="fa fa-check"></i>
</label>

I redesign the checkbox, by hiding it and then giving the label a class ("category-choice").

This works fine but, it is buggy: When I select and deselect the items randomly and then hit upgrade, it sometimes send the right ids to the controller and sometimes the wrong ones. In other words, by clicking the redesigned checkbox, it sometimes works, it sometimes doesnt. Any idea why?

Just in case it matters, I have a javascript that changes the color of the checkbox label when clicked:

$(document).ready(function(){
  $(".category-choice").click(function(){
    $(this).toggleClass("active");
  });
});




Wordpress Contact form checkbox option limit

I would like to set the limit of selected options in the form. I have 50 options (checkboxes) and I want to set a limit of 3 selected.

Can you help?

Url: https://zuchlinski.com.pl/formularz-na-testy/




mercredi 20 février 2019

Codeigniter Checkbox

Can you guys tell me what i'm doing wrong here in my code? I tried to post the data inside these checkboxes to database

here is the view.php

(more code)
<div class="form-group">
          <label class="control-label col-md-3">Infection</label>
          <div class="col-md-9">
            <input type="checkbox" name="infectionType[]" value="vap"> VAP
            <input type="checkbox" name="infectionType[]" value="hap"> HAP
            <input type="checkbox" name="infectionType[]" value="isk"> ISK
            <input type="checkbox" name="infectionType[]" value="iad"> IAD
          </div>
        </div>

and this is my controller.php

public function insert_surveilance(){
    $data=array(
        (more code)
        'vap' => $this->input->post('vap'),
        'hap' => $this->input->post('hap'),
        'isk' => $this->input->post('isk'),
        'iad' => $this->input->post('iad'),
        (more code)
    );
    $data[]=
        $insert = $this->surveilance_model->insert_surveilance($data);
        echo json_encode(array("status"=>TRUE));
}

then this is my model.php

public function insert_surveilance($data){
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

this is the save function ... function save(){

    var url;
    if(save_method == 'add'){
      url="<?php echo site_url('surveilance/insert_surveilance')?>";
    } else {
      url="<?php echo site_url('surveilance/edit_surveilance')?>";
    }
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
           //if success close modal and reload ajax table
           $('#modal_form').modal('hide');
          location.reload();// for reload a page
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Failed adding data');
        }
    });
  }




Re-set checkboxes to true (dealing with blanks)- Google Apps Script

I found the snippet below here: Re-set checkboxes to false - Google Apps Script

I'm interested in editing this to set false checkboxes to true, specifically adding to it to skip blank cells. Can't find anything helpful on skipping blanks.

function resetCheckBoxesAllSheets() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]

var dataRange = sheet.getRange('A4:Z100');
var values = dataRange.getValues();
for (var i = 0; i < values.length; i++) {
  for (var j = 0; j < values[i].length; j++) {
    if (values[i][j] == true) {
      values[i][j] = false;
    }
  }
}
dataRange.setValues(values);


}
}