vendredi 31 août 2018

Rails 4 / Filterrific gem - Problem with boolean field

In my application, I have a field called tested which is a boolean field.

What I want to achieve is a simple checkbox where users can check or uncheck & filter based on tested.

In My model I have:

filterrific :default_filter_params => { :sorted_by => 'created_at_desc' },
              :available_filters => %w[
                sorted_by
                search_query
                with_created_at_gte
                with_tested
              ]
scope :with_tested, lambda { |flag|
    return nil  if 0 == flag # checkbox unchecked
    where(tested: true)
}

/// Other scopes

and In my view/form I have:

= f.check_box :with_tested

In my model I have also tried different approaches with no luck:

scope :with_tested, lambda { |value|
  where('posts.tested = ?', value)
}

// and 

scope :with_tested, lambda { |query|
  return nil  if 0 == query # checkbox unchecked
  where('posts.tested == ?', query)
}

// and

scope :with_tested, lambda { |flag|
    return nil  if 0 == flag # checkbox unchecked
    where(tested: [flag])
}

When I try to filter based on tested, I can see that my filter is trying to filter (I see the filter spin), but my records are not filtered correctly.

I'm not sure what I have done wrong. Any suggestion and help is appreciated!

All other parts of the filter work fine

PS: I haven't added with_tested in my controller as I got to know I don't need it


Versions:

Ruby on Rails: 4.2.4

Filterrific: 2.1.2




Sharedpreferences save checkbox cheked

I try to follow this example Shared Preferences Example to create 2 checkbox inside this example. I tried different ways but it's not saving any changes. I just wan't to safe the checkboxes if clicked and have the last selected value. I'm new with Java and hope someone can explain me how to solves this with this example.

package example.com.max.lschennn;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
CheckBox check1;
CheckBox check2;

public static final String mypreference = "mypref";
public static final String Name = "name";
public static final String Email = "email";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    check1 = (CheckBox) findViewById(R.id.checkBox1);
    check2 = (CheckBox) findViewById(R.id.checkBox2);
    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }

}

public void Save(View view) {
    String n = name.getText().toString();
    String e = email.getText().toString();
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(Name, n);
    editor.putString(Email, e);
    editor.putBoolean(String.valueOf(check1), true); // Storing boolean - true/false
    editor.putBoolean(String.valueOf(check2), true); // Storing boolean - true/false
    editor.commit();
}

public void clear(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    name.setText("");
    email.setText("");

}

public void Get(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);

    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);

    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }
}

}




MS PowerPoint CheckBox remains linked when slide is duplicated

Hoping you can help me as I have searched a lot of forums and did not find the same question, never mind the answer I need :) I have a power point pack which I have put together. It is built to be a template for my team to use repeatedly and is set up using slide masters to control the layout. Each layout slide in the slide master includes two checkboxes to identify either a pass or a fail. My problem is that when you insert a new slide (by either duplicating an existing slide or adding a slide from the slide master layout), and change the checkbox value it also changes on the other slide. Is there a way either using some quick VBA or otherwise to stop this from happening and break the link between the two slides. Any help would be really appreciated.




How to get values of dynamically generated labels of multiple checkboxes in Angular 4 ?

I need to get the values of labels for check boxes if the checkbox is selected.

How can i pass label values on checked ?




jeudi 30 août 2018

How to select checkboxes based on text content?

I have a table with multiple checkboxes. In JavaScript/JQuery I want to select all of them but a couple based on the text content in that table data. So, it should select all checkboxes except if the text content is equal to '899', etc. This is what I have currently:

`

$('#select-all').click(function (event) {
            if (this.checked) {
                var items = document.getElementsByClassName('col-store_number');
                for (var i = 0; i < items.length; i++) {
                    if (items[i].textContent === 899) {
                        items[i].checked = false;
                    } else {
                        items[i].checked = true;
                    }
                }
           }

    });

` When I check the select all box it doesn't select anything, so its likely making them all false instead of just the 899 one. I did a console.log(items[i].textContent); and it did return the right values, so I'm getting the right text content.




Store services and activity with periodicity related in each other

HTML

<form method='post' id='userform' action='arrayvalue.php'>



       <input type='checkbox' name='servicevar[]' value='Gst'>Gst<br> <br>


        <input type='checkbox' name='activityvar[]' value='Return'>Return<br>
         <input type='checkbox' name='pervar[]' value='Monthly'>Monthly<br>
         <input type='checkbox' name='pervar[]' value='Yearly'>Yearly<br>



        <input type='checkbox' name='activityvar[]' value='Filling'>Filling<br>
          <input type='checkbox' name='pervar[]'value='Monthly'>Monthly<br>
          <input type='checkbox' name='pervar[]' value='Yearly'>Yearly<br>
        <br>




        <input type='checkbox' name='arr[2][service]' value='Incometax'>Incometax<br> <br>


        <input type='checkbox' name='arr[2][activity][]' value='Return'>Return<br>
         <input type='checkbox' name='arr[2][per][]' value='Monthly'>Monthly<br>
         <input type='checkbox' name='arr[2][per][]' value='Yearly'>Yearly<br>



        <input type='checkbox' name='activityvar[]' value='Filling'>Filling<br>
          <input type='checkbox' name='pervar[]'value='Monthly'>Monthly<br>
          <input type='checkbox' name='pervar[]' value='Yearly'>Yearly<br>



        <input type='checkbox' name='activityvar[]' value='Return'>Revised<br>
         <input type='checkbox' name='pervar[]' value='Monthly'>Monthly<br>
         <input type='checkbox' name='pervar[]' value='Yearly'>Yearly<br>
        <br>

   <input type='submit' name="submit" class='buttons'>
</form>

The output of this code is:-

  • Gst
    • Return
      • Monthly
      • Yearly
    • Filling
      • Monthly
      • Yearly
  • Incometax
    • Return
      • Monthly
      • Yearly
    • Filling
      • Monthly
      • Yearly
    • Revised
      • Monthly
      • Yearly

I store all this values in mapping table,

I have serviceactivitymap Table where I store service with related activity,

I have activitypermap Table where I store activity related to periodicity.

     foreach ($_POST['arr'] as $input) {


            $servicevalue = $input['service'];
                $query2 = mysql_query("insert into mapclientservice(client_id,service_id)values('$firmid','$servicevalue')",$connection);



          foreach ($input['activity'] as $activity) {

            $servicevalue = $input['service'];

             $query3 = mysql_query("insert into mapserviceactivity(service_id,activity_id)values('$servicess','$activity')",$connection);


             foreach ($input['timeperiod'] as $period) {

                $query4 = mysql_query("insert into mapactivityperodicity(activity_id,perodicity_id)values('$activity','$period')",$connection);

             }

        }

    }

This is used for store services activity and periodicity. But when I store activity and periodicity then there is problem,value of periodicity not store correct.

All the checked periodicity stored with all activity, How to store it with proper activity with periodicity




Indent wrapped text on dynamically created checkbox

I have a dynamically created checkbox from code behind that has a long label on my webform asp.net project. When the text wraps to a new line the new line of text starts directly under the checkbox itself. How can I dynamically set the checkbox so the new line is automatically indented if needed. Not all dynamically created checkboxes have a long label.

Here is my code that creates the checkbox:

MyObject obj = SetNewObject("Supervisor"); 

CheckBox objCheck6 = new CheckBox();
objCheck6.ID = obj.GetFieldValue("Name");
objCheck6.Text = GetControlTitle("Supervisor");  
objCheck6.Checked = obj.GetFieldValue("Value").ToLower() == "true";
tableCell1.Controls.Add(objCheck6);

I have tried a couple things that have not worked. I tried the following, one at a time and each seemed to have zero effect on the checkbox or checkbox's text at all:

objCheck6.Style.Add("margin-left", "20px");

objCheck6.LabelAttributes.Add("margin-left", "20px");

objCheck6.TextAlign = TextAlign.Right;

objCheck6.TextAlign = TextAlign.Left;

A point in the right direction would be much appreciated. Thanks!




Only select the elements rendered on the page

Currently, the checkbox used selects all the items in list. Is there any way to only select the items that are currently rendered on the page instead of selecting all of them?

 <mat-checkbox (change)="$event ? masterToggle() : null"
      [checked]="selection.hasValue() && isAllSelected()"
      [indeterminate]="selection.hasValue() && !isAllSelected()">
 </mat-checkbox>




Storing multiple services and related activity with related periodicity

PHP

<form action="page5_form.php" method="post" name= "test">
  <ul>
    <li>
      <input name='arr[<?php echo $i?>][service]' type='checkbox' data-id='Incometax'value="<?php echo $service['service_id']?>"/><?php echo $service['servicename']?>

      <ol>
           <li>
               <?php foreach ($activities as $activity) : ?>

          <input type='checkbox' name='arr[<?php echo $i?>][activity][]' value="<?php echo $activity['id']?>" /><?php echo $activity['nameofactivity'];?>

          </li>
          <li>
               <?php foreach ($pers as $per) : ?>

          <input type='checkbox' name='arr[<?php echo $i?>][timeperiod][]' value="<?php echo $per['periodicity_id'];?>" /><?php echo $per['per_time'];?>

           </li>
           <br>
      <?php endforeach;?>
        <br>
            <?php endforeach;?>
            <br>



      </ol>

    </li>


    </ul>     


     <?php 
$i++;
    endforeach;?>


      <input name="number" type="hidden" value="<?php echo $next; ?>">

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


</form>

Output of my php code is :-

  • GST
    • Return
      • Monthly
      • Yearly
    • Revised
      • Monthly
      • Yearly
      • Quartly
  • Incomtax
    • Application
      • Monthly
      • yearly
    • Return
      • Monthly
      • Yearly

In this output

  1. Incometax and Gst are services.
  2. Return,revised are the activities of service 1 GST and application,Return are the activities of service 2 Incometax.
  3. Monthly,yearly,quartely are the period time of activity.

When I stored this services,My code for storage is

foreach($_POST['arr'] as $input)
 {
  $service = $input['service'];
  echo $service;
  echo "<br>";
  foreach($input['activity'] as $act)
  {
    $query2 = "insert into serviceactmap(client_id,service_id,activity_id)values('$firmid','$servicevalue','$activityvalue')";


    foreach($input['timeperiod'] as $per)
    {



    $query3 = "insert into mapactivityperodicity(client_id,activity_id,perodicity_id)values('$firmid','$activityvalue','$period')";

    }
  }
 } 

  1. I store services and activity in Serviceactivitymap table and activity and periodicity in activitypermap table
  2. When I store in activitypermap table, when I check 1st activity and 1,2 periodicity and 2nd activity and 1 periodicity then it store in db like 1st activity in activity id but 1,2,2 periodicity in per_id.
  3. When I select periodicity in any activity then all the values of periodicity repeated for all activity

Thank u




How to make default checkbox checked in angular 6?

lanuage.component.html

<form method="post" enctype="multipart/form-data">
   <mat-checkbox class="versionstyle" name="languageenabled"[(ngModel)]="this.languageObj.languageenabled">Enabled</mat-checkbox>
</form>

I want to make checkbox is checked by default in angular6 , i search in google and apply so many solution but it not works, kindly help me




mercredi 29 août 2018

I have tow BaseAdapter which contain checkboxes, how to check the checkbox of Adapter2 based on the values from the Adapter1

I am having two BaseAdapter Adapter1 and Adapter2, after checking the checkbox from adapter1 it is saved in the Arraylist and which is passed to Adapter2. I want to check the checkbox of Adapter2 which are selected in the Adapter1.Both Adapter will have the same values.

i have tried but it is giving java.lang.IndexOutOfBoundsException: Index: as the passed values from the Adapter1.

can any one please help in this case please. here is the two adapter Adapter1 is

public class RouterSpinnerAdapter extends BaseAdapter implements Filterable{
Context context;
LayoutInflater layoutInflater;
ArrayList<RouterSelectModel> routermodeldata;
ArrayList<RouterSelectModel> rowterselectedmodeldata;
ArrayList<RouterSelectModel>orig;
boolean[] rowtercheckBoxState;
boolean flag;
public RouterSpinnerAdapter(Context context, ArrayList<RouterSelectModel>routermodeldata, boolean flag){
    this.context=context;
    this.routermodeldata=routermodeldata;
    this.flag=flag;
    rowtercheckBoxState = new boolean[routermodeldata.size()];
    rowterselectedmodeldata=new ArrayList<>();

}
@Override
public int getCount() {
    return routermodeldata.size();
}

@Override
public Object getItem(int position) {
    return routermodeldata.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder=null;

    if (convertView==null){
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView =layoutInflater.inflate(R.layout.rowter_spinner_row, null);
        viewHolder = new ViewHolder();
        viewHolder.ch_select_rowter =(CheckBox) convertView.findViewById(R.id.ch_select_rowter);
        viewHolder.t_rowtername=(TextView)convertView.findViewById(R.id.t_rowtername);

        convertView.setTag(viewHolder);

    }else{
        viewHolder = (ViewHolder) convertView.getTag();
    }
    final RouterSelectModel model=(RouterSelectModel)routermodeldata.get(position);

    viewHolder.t_rowtername.setText(model.getRoutername());
    viewHolder.ch_select_rowter.setChecked(rowtercheckBoxState[position]);

    viewHolder.ch_select_rowter.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                if(((CheckBox)v).isChecked()){
                    rowtercheckBoxState[position]=true;
                    // selectedManagerHashMap.put(model.getManagername(),model.getManagername());
                   // saveToCustom(model.getDominaname(),sessionManager.getUserID());
                    rowterselectedmodeldata.add(model);
                }else
                {
                    rowtercheckBoxState[position]=false;
                    // selectedManagerHashMap.remove(model.getManagername());
                    //removeFromCustom(model.getDominaname(),sessionManager.getUserID());
                    rowterselectedmodeldata.remove(model);
                }
            }catch (ArrayIndexOutOfBoundsException e){

            }
        }

    });

    return convertView;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            final FilterResults oReturn = new FilterResults();
            final ArrayList<RouterSelectModel> results = new ArrayList<RouterSelectModel>();
            if (orig == null)
                orig = routermodeldata;
            if (charSequence != null) {
                if (orig != null && orig.size() > 0) {
                    for (final RouterSelectModel g : orig) {
                        if (g.getRoutername().toLowerCase().contains(charSequence.toString()))
                            results.add(g);
                    }
                }
                oReturn.values = results;
            }
            return oReturn;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            routermodeldata = (ArrayList<RouterSelectModel>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}
 public void selectAllRowter(boolean flag){
if (flag==true){
    for (int i = 0; i <rowtercheckBoxState.length ; i++) {

        rowtercheckBoxState[i]=flag;
        rowterselectedmodeldata.add(routermodeldata.get(i));
        notifyDataSetChanged();
    }
}if (flag==false){
    for (int i = 0; i <rowtercheckBoxState.length ; i++) {

        rowtercheckBoxState[i]=flag;
        rowterselectedmodeldata.remove(routermodeldata.get(i));
        notifyDataSetChanged();
    }
}


 }
 public ArrayList<RouterSelectModel> getseletedItems(){
    return rowterselectedmodeldata;
 }
static class ViewHolder{

    TextView t_rowtername;
    CheckBox ch_select_rowter;
}

 }

Adapter2 is

     public class Fun2RouterSpinnerAdapter extends BaseAdapter implements Filterable{
Context context;
LayoutInflater layoutInflater;
ArrayList<Fun2RouterSpinnerModel> fun2routermodeldata;
ArrayList<Fun2RouterSpinnerModel> fun2rowterselectedmodeldata;
ArrayList<Fun2RouterSpinnerModel>orig;
boolean[] fun2rowtercheckBoxState;
boolean flag;
ArrayList<RouterSelectModel> routerlistfrom1;
public Fun2RouterSpinnerAdapter(Context context, ArrayList<Fun2RouterSpinnerModel>routermodeldata,ArrayList<RouterSelectModel> routerlistfrom1 ,boolean flag){
    this.context=context;
    this.fun2routermodeldata=routermodeldata;
    this.flag=flag;
    fun2rowtercheckBoxState = new boolean[routermodeldata.size()];
    fun2rowterselectedmodeldata=new ArrayList<>();
    this.routerlistfrom1=routerlistfrom1;

}
@Override
public int getCount() {
    return fun2routermodeldata.size();
}

@Override
public Object getItem(int position) {
    return fun2routermodeldata.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder=null;

    if (convertView==null){
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView =layoutInflater.inflate(R.layout.fun2_rowter_spinner_row, null);
        viewHolder = new ViewHolder();
        viewHolder.ch_select_rowter2 =(CheckBox) convertView.findViewById(R.id.ch_select_rowter2);
        viewHolder.t_rowtername2=(TextView)convertView.findViewById(R.id.t_rowtername2);

        convertView.setTag(viewHolder);

    }else{
        viewHolder = (ViewHolder) convertView.getTag();
    }
    final Fun2RouterSpinnerModel model=(Fun2RouterSpinnerModel)fun2routermodeldata.get(position);

    viewHolder.t_rowtername2.setText(model.getRouter2name());
    viewHolder.ch_select_rowter2.setChecked(fun2rowtercheckBoxState[position]);




    viewHolder.ch_select_rowter2.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                if(((CheckBox)v).isChecked()){
                    fun2rowtercheckBoxState[position]=true;
                    // selectedManagerHashMap.put(model.getManagername(),model.getManagername());
                    // saveToCustom(model.getDominaname(),sessionManager.getUserID());
                    fun2rowterselectedmodeldata.add(model);
                }else
                {
                    fun2rowtercheckBoxState[position]=false;
                    // selectedManagerHashMap.remove(model.getManagername());
                    //removeFromCustom(model.getDominaname(),sessionManager.getUserID());
                    fun2rowterselectedmodeldata.remove(model);
                }
            }catch (ArrayIndexOutOfBoundsException e){

            }
        }

    });
     checkSelected(true,routernamefrom1))
    return convertView;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            final FilterResults oReturn = new FilterResults();
            final ArrayList<Fun2RouterSpinnerModel> results = new ArrayList<Fun2RouterSpinnerModel>();
            if (orig == null)
                orig = fun2routermodeldata;
            if (charSequence != null) {
                if (orig != null && orig.size() > 0) {
                    for (final Fun2RouterSpinnerModel g : orig) {
                        if (g.getRouter2name().toLowerCase().contains(charSequence.toString()))
                            results.add(g);
                    }
                }
                oReturn.values = results;
            }
            return oReturn;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            fun2routermodeldata = (ArrayList<Fun2RouterSpinnerModel>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}
public void fun2selectAllRowter(boolean flag){
    if (flag==true){
        for (int i = 0; i <fun2rowtercheckBoxState.length ; i++) {

            fun2rowtercheckBoxState[i]=flag;
            fun2rowterselectedmodeldata.add(fun2routermodeldata.get(i));
            notifyDataSetChanged();
        }
    }if (flag==false){
        for (int i = 0; i <fun2rowtercheckBoxState.length ; i++) {

            fun2rowtercheckBoxState[i]=flag;
            fun2rowterselectedmodeldata.remove(fun2routermodeldata.get(i));
            notifyDataSetChanged();
        }
    }


}
public ArrayList<Fun2RouterSpinnerModel> getRoterseletedItems(){
    return fun2rowterselectedmodeldata;
}
public boolean checkSelected(boolean flag,String routernamefrom1){

    for (int i = 0; i <fun2routermodeldata.size() ; i++) {
        if(routernamefrom1.equalsIgnoreCase(fun2routermodeldata.get(i).getRouter2name())){
            fun2rowtercheckBoxState[i]=flag;
            return true;
        }
    }

    return false;
}
static class ViewHolder{

    TextView t_rowtername2;
    CheckBox ch_select_rowter2;
}
  }




if -else loop Error Java netbeans

I have a project that requires Java-Mysql connectivity. Here I require the use of if-else blocks within the try and catch statements.

But it shows errors wherever I use the if-else loop. The error shown is :

Cannot find Symbol

(the checkbox & radio box no.s are correct)

PART 1 PART 2




How to control checkbox "checked" value with unknown amount of checkboxes

So I have a screen where I render unknown amount of checkboxes depending on the list size. How can I control "checked" value of these boxes?
I am using react-native-elements for checkboxes.

Render method for checkboxes:

    _showChoices = (list) => {
        return list.map((item, i) => {
            return (
                <CheckBox
                title={item.choice_name}
                checked={}
                size={25}
                onIconPress={() => {}}
                onPress={() => {}}
                key={item.choice_id}
                />
            )
        })
    }

If you need any more info please comment.

Thanks!




Javascript function called on checkbox change

Stuck at calling a simple JS function. Developer tools at chrome, console tab, thows

(index):591 Uncaught ReferenceError: checkbox is not defined at myFunction ((index):591) at HTMLInputElement.onclick

Code is

<span>Notificaciones</span>
    <input type="checkbox" id="myCheck" onclick="myFunction()">         
    <script type="text/javascript">
        function myFunction() {
              var checkBox = document.getElementById("myCheck");
              if(checkbox.checked){
                alert("suscribe");
              }  else{
                  alert("descuscribe");
              };
            };
    </script>




mysql in query for checkbox values in database

I have stored values of checkbox in database in one field comma separated . like animals column has dogs;cats;elephants . This is in a text field.

How can i use in filter for this in mysql. i.e. select * from animaltable where animals in(cats) ;




When I check Checkbox Then Only one value display instead of all values

PHP

<?php 

$periods = "select * from perodicity";
$periods = $conn->query($periods) or die ($conn>error.__LINE__);
$peris = [];

while ($row = $periods->fetch_assoc()) {
    $peris[] = $row;
}






//for service 1
$all_activities = "select * from activity join displayserviceactivitymap on activity.activity_id = displayserviceactivitymap.activity_id right  join services on services.service_id = displayserviceactivitymap.service_id";


$all_activities = $conn->query($all_activities) or die ($conn>error.__LINE__);
$activities = [];

while ($row = $all_activities->fetch_assoc()) {
    $activities[] = $row;
}



$repeated = 'repeated';

foreach ($activities as $act) {


  if($act['servicename'] != $repeated){










?>


 <form action="page5_form.php" method="post" name= "test">
  <ul>
    <li>
      <input name='service' type='checkbox' data-id='Incometax'value="<?php echo $service['service_id']?>"/><?php echo $act['servicename']?>
        <?php  $repeated = $act['servicename'];}?>

      <ol>
          <li>
              <?php if($act['activity_id'] != '')

               echo '<input type="checkbox" name="arr['.$act['service_id'].'][activity][]" value="'.$act['activity_id'].'" id="'.$act['activity_id'].'">'.$act['nameofactivity'].'<br>';


              ?>
          <!-- <input type='checkbox' name='activity' value="<?php echo $activity['id']?>" />Revised Return Filling<br> -->


          </li>

           <li>
              <?php foreach ($peris as $per) : ?>

          <input type='checkbox' name='periodicity' value="<?php echo $per['periodicity_id'];?>" /><?php echo $per['per_time'];?>

              <?php endforeach ?>

           </li>
           <br>
        <br>
            <br>



      </ol>

    </li>

    </ul>     

    <?php }?>



      <input name="number" type="hidden" value="<?php echo $next; ?>">

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


</form>

PHP code Output :

  • Incometax
    • Return
    • Revised
    • Filling
  • GST
    • Revised
    • Filling

Here Incometax and Gst are services And other are activity related to that services.

I use javascript code for display and hide activity related to Services But when I click on Incometax then only one activity Return display,same for GST when I click on GST then only one revised display.

I want to display all activity related to that services which service is clicked.

My Javascript Code

let _flags={
  capture:false,
  once:false,
  passive:true
};


document.addEventListener( 'DOMContentLoaded',function( evt ){

  let _form = document.forms.test;
  let _class= 'visible';

  Array.prototype.slice.call( _form.querySelectorAll( 'input[ type="checkbox" ]' ) ).forEach( function( el, i ){
    if( el.dataset.id ) el.addEventListener( 'click', function( e ){

      /* Hide all `OL` elements & uncheck  */
      Array.prototype.slice.call( _form.querySelectorAll( 'li ol' ) ).forEach( function( n ){
        if( n.classList.contains( _class ) ) {
          /* Remove the class from child OL element that contains other input elements ( activities ) */
          n.classList.remove( _class );

          /* Uncheck the other service checkbox */
          n.parentNode.querySelector( 'input[ type="checkbox" ]' ).checked=true;

          /* uncheck all child activity checkboxes */
          Array.prototype.slice.call( n.querySelectorAll( 'input[ type="checkbox" ]' ) ).forEach( function(chk){
            chk.checked ;
          } );
        }
      } );

      /* Display relevant activity checkboxes */
      if( e.target.checked ) e.target.parentNode.querySelector( 'ol' ).classList.toggle( _class )


    }, _flags );
  });
}, _flags );

Thank You




mardi 28 août 2018

Hide and display activity when click on service checkbox

PHP code

<?php 
//for service 1
$all_activities = "select * from activity join displayserviceactivitymap on activity.activity_id = displayserviceactivitymap.activity_id right  join services on services.service_id = displayserviceactivitymap.service_id";    

$all_activities = $conn->query($all_activities) or die ($conn>error.__LINE__);
$activities = [];

while ($row = $all_activities->fetch_assoc()) {
    $activities[] = $row;
}
$repeated = 'repeated';

foreach ($activities as $act) {
  if($act['servicename'] != $repeated){

    echo '<br><input type="checkbox" name="arr['.$act['service_id'].'][service]" value="'.$act['service_id'].'" id="'.$act['service_id'].'">'.$act['service_id'].$act['servicename'].'<br>';
    $repeated = $act['servicename'];
  }

  if($act['activity_id'] != '')

  echo '<input type="checkbox" name="arr['.$act['service_id'].'][activity][]" value="'.$act['activity_id'].'" id="'.$act['activity_id'].'">'.$act['nameofactivity'].'<br>';
}

?>

Output of This code is

  • Incometax
    • Return
    • Filling
    • Billing
    • Tax Invoice
  • GST
    • Compnay
    • Format
    • GSTR
  • TDS
    • Return
    • ICRT
    • Accomplish

In this Output Incometax,GST,TDS are services. I want To display related activity when check service checkbox and hide activity when uncheck checkbox.

For example :-

When I click on Incometax service1 checkbox then activity related to service 1 return,filling,billing,tax invoice display.

When I click on GST service2 checkbox then activity related to service 2 display.

Same for all. Thank you.




Echo checked if value 1

This is my checkbox

<?php echo "<input type='checkbox' name='pcu' ".fieldvalue('1').==1 ? 'checked' : '' " value='1' />" ?>

If fieldvalue is 1 the box should be checked.

How to echo "checked=checked" if fieldvalue value is 1 and don't checked if fieldvalue is 0.




python checkbox multiple select

now, how i get multiple check in the same time? i cant select 2 or 3 or 4 checkbox in the same time,it only allows me 1 select for time

def check_appointments():
    print(var.get())

def checkbox():
    contacto = Contacto()
    arreglo = contacto.buscar(1)
    m=2
    n=1

    for c in arreglo:
        m=m+1
        n=n+1
        for r in range(n,m):
            for co in range(1, 9):
                if co==5:
                    cell = Entry(master, width=10,justify='center',font=("Calibri",11),disabledbackground="cadetblue",disabledforeground="black")
                    cell.grid(padx=1, pady=1, row=r, column=co)
                    t=add_date(c[4],1)
                    cell.insert(END,t)
                else: 
                    cell = Entry(master, width=15,justify='center',font=("Calibri",11),disabledbackground="cadetblue",disabledforeground="black")                   
                    cell.insert(END,c[co-1])

                cell.grid(padx=1, pady=1, row=r, column=co)

                cell.config (state = DISABLED )
                cb = Checkbutton(master, command=check_appointments, variable=var, onvalue=c[0],offvalue="0")
                cb.grid( row=r, column=0)                           
                cb.deselect()
master=Tk()
var = StringVar()
cajaB = StringVar()
checkbox()
master.mainloop()

check image




Change Checkbox Size in Angular Material Selection List

Is it possible to change the size of the checkbox in an Angular Material Selection List? I've tried changing the size of the mat-pseudo-checkbox in CSS but that results in the checkmark not being placed properly:

mat-pseudo-checkbox {
  height: 10px;
  width: 10px;
}

Checkmark improperly placed

Is there another selector that I need to adjust to correct this?




JS always selected 1 of 2 checkboxes

I have 2 checkboxes in my page. First id is "status_1", second id is "status_2"

I want to make that both of them must be selected on page load and always keep one selected, when trying to deselect both.

So for example if "status_1" is selected, "status_2" is not selected and user is trying do deselect "status_1" too, "status_2" select automatically.




Checkbox tick is not getting deselect when i come back to same screen

I have one table view to select the items needs to pass to cart page by using checkbox. Now when i select any date i.e when i select any 3 items and i move that date to cart page.And when i come back first items check box only getting removed. 2nd,3rd item check box image is still as tick mark is there. But its not selected, only image is showing. I tried all way in view will disapperar , viewwill appear But still only first items of table view check box is getting remove 2nd, 3rd items check box is still having checkbox.How can i solve that ?

@IBAction func checkBoxClicked(_ sender: Any) {
        guard let button = sender as? UIButton else {
            return
        }

        self.putCheckBox(tag: button.tag)
    }

func putCheckBox(tag: Int){
        let index = IndexPath(item: tag, section: 0)
        let cell = self.tableView.cellForRow(at: index) as! SubCatTableCell
        if let ct = self.subCatProducts?[index.row]{
            ct.customCheckBox = !ct.customCheckBox
            if ct.customCheckBox {
                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
                ct.customCheckBox = true
                if ct.customCount == 0{
                    ct.customCount += 1
                    cell.noOfQtyLbl.text = "\(ct.customCount)"
                }
                let val = prefs.value(forKey: Constants.Keys.CategoryInCart) as? String
                if ct.categoryName != val{
                    if val != nil{
                        self.showAlertWithSingleButton(message: "Products addeed", okAction: {
                            if ct.customCheckBox{
                                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
                            } else {
                                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "Unchecked"), for: .normal)
                            }
                            ct.customCheckBox = false
                            self.getSubCat()
                            self.collectionViewCellClicekd = true
                        }, cancelAction: {
                            if ct.customCheckBox{
                                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
                            } else {
                                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "Unchecked"), for: .normal)
                            }
                            ct.customCheckBox = false
                            self.collectionViewCellClicekd = true
                            self.getSubCat()
                        })
                    }
                }

            }else{
                ct.customCount = 0
                cell.noOfQtyLbl.text = "\(ct.customCount)"
                cell.tickButnOutlet.setImage(#imageLiteral(resourceName: "Unchecked"), for: .normal)

            }
        }
    }

override func viewWillAppear(_ animated: Bool) {


        self.getSubCat() // api call for loading the date


    }

Please let me know how can i solve this issue !!

Thanks in advance !




Checkbox List Not Updating

I created a widget list of checkboxes as shown and I am using it in the Build method as

Column(
children: mList;
)

The problem is that the checkbox does not change value on click. It's value and state remain the same. Although the click is registered(checked it). What am I doing wrong?

List<int> selectedList = [];
List<Widget> = mList;
createMenuWidget(Course courses) {
  for (int b = 0; b < courses.length; b++) {
    Map cmap = courses[b];
    mList.add(CheckboxListTile(
      onChanged: (bool value){
        setState(() {
          if(value){
            selectedList.add(cmap[course_id]);
          }else{
            selectedList.remove(cmap[course_id]);
          }
        });
      },
      value: selectedList.contains(cmap[course_id]),
      title: new Text(cmap[course_name]),
    ));
  }
} 




Foundation 6 CSS Checkbox Styling

Currently trying to make custom CSS Checkbox's with existing CSS code.

    .nk-btn-color-dark-5 {
    background-color: #293139;
    border-color: #101215;
    border-style: solid;
}

.nk-btn-color-dark-5:hover, .nk-btn-color-dark-5.hover {
    background-color: #3b4550;
    border-color: #4a5665;
}

.nk-btn-color-dark-5:active, .nk-btn-color-dark-5.active{
    background-color: #4a5665;
    border-color: #59687a;
}

.nk-btn-color-dark-5.nk-btn-outline {
    color: #293139;
}

.nk-btn-color-dark-5.nk-btn-outline:hover, .nk-btn-color-dark-5.nk-btn-outline.hover {
    color: #14171b;
}

.nk-btn-color-dark-5.nk-btn-outline:active{
    color: black;
}
.nk-btn-hover-color-main-7.nk-btn-color-white:hover, .nk-btn-hover-color-main-7.nk-btn-color-white.hover, .nk-btn-hover-color-main-7.nk-btn-color-white:active, .nk-btn-hover-color-main-7.nk-btn-color-white.active {
    color: #fff;
}

.nk-btn-hover-color-main-7:hover, .nk-btn-hover-color-main-7.hover {
    background-color: #FFD700;
    border-color: #a5102c;
}

.nk-btn-hover-color-main-7:active, .nk-btn-hover-main-7.active {
    background-color: #FFD700;
    border-color: #a5102c;
}
                    <input id="checkbox1" type="checkbox" name="prod" value="1">
                                        <label class="nk-btn nk-btn-rounded nk-btn-color-dark-5 nk-btn-hover-color-main-7" for="checkbox1">Add to Cart</label>

Current CSS for said button. And HTML, I am unable to figure out how to make it work. I've tried as much as i know, Using this as a guidance. https://codepen.io/anon/pen/LJVgQm

Any help would be appreciated. Thanks




Hide and Display activity checkbox when click on services checkbox

PHP

<?php 




//for service 1
$all_activities = "select * from activity join displayserviceactivitymap on activity.activity_id = displayserviceactivitymap.activity_id right  join services on services.service_id = displayserviceactivitymap.service_id";


$all_activities = $conn->query($all_activities) or die ($conn>error.__LINE__);
$activities = [];

while ($row = $all_activities->fetch_assoc()) {
    $activities[] = $row;
}



$repeated = 'repeated';

foreach ($activities as $act) {


  if($act['servicename'] != $repeated){



    echo '<br><input type="checkbox" name="arr['.$act['service_id'].'][service]" value="'.$act['service_id'].'" id="'.$act['service_id'].'">'.$act['service_id'].$act['servicename'].'<br>';
    $repeated = $act['servicename'];
  }



  if($act['activity_id'] != '')

  echo '<input type="checkbox" name="arr['.$act['service_id'].'][activity][]" value="'.$act['activity_id'].'" id="'.$act['activity_id'].'">'.$act['nameofactivity'].'<br>';


}




?>

Output of My code is

  • Incometax

    • Return
    • filling
  • GST

    • Form
    • Return
    • GSTR
  • TDS
    • Application
    • Refund

Here Incometax,GST,TDS are services and others are related activity of the services. I want to display activity when I check checkbox and hide when I uncheck checkbox. I use javascript code but not work properly.




Python tkinter Checkboxes

I trying to work checkboxes, but am having trouble getting the selected values back (ideally as a list of strings).

I need the list of check boxes to be variable. In this case, the column titles for items in my dataset. If a certain column exists, i need the list of options to be all values after that point.

For example, my dataframe could have columns:

Col1  Col2  Col3  Col4  Col5

If Col2 exists, The list of options for the tkinter checkboxes should be:

Col3  Col4  Col5 

Then if Col3 and Col5 are selected with checkboxes, i need the output to be:

choices = ["Col3", "Col5"]

This is my current attempt:

import tkinter as tk
from tkinter import *
import pandas as pd

df1 = pd.DataFrame(columns=['Col1','Col2','Col3','Col4','Col5'])

l1 = list(df1.columns.values)
target_element = "Col2"
try:
    target_index = l1.index(target_element)
except ValueError:
    target_index = None
    l2 = l1[target_index + 1 :]
    my_list = list(l2)

class CheckbuttonList(tk.LabelFrame):
    def __init__(self, master, text=None, list_of_cb=None):
        super().__init__(master)

        self['text'] = text
        self.list_of_cb = list_of_cb
        self.cb_values = dict()
        self.check_buttons = dict()


    if self.list_of_cb:
        for item in list_of_cb:
            self.cb_values[item] = tk.BooleanVar()
            self.check_buttons[item] = tk.Checkbutton(self, text=item, variable=self.check_buttons)
            self.check_buttons[item].config(onvalue=True, offvalue=False, variable= self.cb_values[item])
            self.check_buttons[item].pack(anchor= W)

if __name__ == '__main__':

root = tk.Tk()

choices = {item:IntVar() for item in my_list} #create dict of check_boxes

my_cbs = CheckbuttonList(root, "SELECT VARIABLE", check_boxes)
my_cbs.pack()

root.mainloop()

print(choices.get())

From this point I have been running into several problems. the most recent being: TypeError: get expected at least 1 arguments, got 0

If anyone knows how to get this working or possibly a better solution to the problem, I would greatly appreciate any help!




How to clear textbox after unchecking checkbox without textbox disappearing (JavaScript)

I am new to HTML, CSS, and JavaScript, so please bear with me.

I am trying to create a form which has an element that uses geolocation to get the current location of a user when he/she checks a checkbox, and it inputs the coordinates inside a textbox that I've set up. This works fine, but when I uncheck the checkbox, the coordinates disappear along with the textbox. How do I clear just the coordinates without making the textbox disappear as well?

Below is my code:

  function getLocation(myCheck) {

          var x = document.getElementById("place");

          if (myCheck.checked) {
             if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
             }
             else {
                x.innerHTML = "Geolocation disabled or unavailable.";
             }
              
             function showPosition(position) {
                x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
              }
            }

          else {
             x.innerHTML = "";
          }
         } 
 
          <h4> Coordinates: <label id="place"><input type="text"></label><label>Use current location? <input id="myCheck" onclick="getLocation(this)" type="checkbox"></label> 
          </h4>

    



Add multiple combined PHP form data from multiple foreign MSSQL tables to one primary table

I got for this example 7 checkboxes:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>


<tr style="height: 21px;">
<td style="width: 25%; height: 21px;"><strong>Technologie</strong></td>
<td style="width: 25%; height: 21px;"></td>
<td style="width: 25%; height: 21px;"></td>
<td style="width: 25%; height: 21px;"></td>
</tr>
<tr style="height: 21px;">
<td style="width: 25%; height: 21px;">Tec1</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
<td style="width: 25%; height: 21px;">Tec2</td>
<td style="width: 25%; height: 21px;"><input name="Technoloie[]" type="checkbox" value="1" /></td>
</tr>
<tr style="height: 21px;">
<td style="width: 25%; height: 21px;">Tec3</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
<td style="width: 25%; height: 21px;"Tec4</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
</tr>
<tr style="height: 21px;">
<td style="width: 25%; height: 21px;">Tec5</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
<td style="width: 25%; height: 21px;">Tec6</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
</tr>
<tr style="height: 21px;">
<td style="width: 25%; height: 21px;"></td>
<td style="width: 25%; height: 21px;">Tec7</td>
<td style="width: 25%; height: 21px;">  <input name="Technoloie[]" type="checkbox" value="1" /> </td>
<td style="width: 25%; height: 21px;"></td>
</tr>
</tbody>
</table>

Here is the SQL Table for this Checkbox:

+--------+------+------+------+------+------+------+------+
| Tec_ID | Tec1 | Tec2 | Tec3 | Tec4 | Tec5 | Tec6 | Tec7 |
+--------+------+------+------+------+------+------+------+
|      1 |    1 |    0 |    0 |    0 |    1 |    0 |    0 |
|      2 |    1 |    0 |    0 |    0 |    0 |    1 |    0 |
|      3 |    1 |    0 |    0 |    0 |    0 |    0 |    1 |
|      4 |    1 |    1 |    1 |    0 |    1 |    0 |    0 |
|      5 |    1 |    1 |    1 |    0 |    0 |    1 |    0 |
|      6 |    1 |    1 |    1 |    0 |    0 |    0 |    1 |
|      7 |    0 |    0 |    0 |    1 |    0 |    0 |    0 |
|      8 |    0 |    1 |    1 |    0 |    1 |    0 |    0 |
|      9 |    0 |    1 |    1 |    0 |    0 |    1 |    0 |
|     10 |    0 |    0 |    0 |    0 |    0 |    0 |    0 |
+--------+------+------+------+------+------+------+------+

You see already if I check Tec1 and Tec5, I want to get Tec_ID 1, so I need a combined checkbox select to get the right ID and I want to Insert this Primary Key as an foreign key into a other table to handle with the id in further functions.

But atm I have no idea, how I can handle this in MSSQL and PHP Code? Can someone help?




Checkbox column not updating when checked, C# wpf

Here is the code:

public partial class UserForm : UserControl
    {

        public UserForm(IList <Element> list)
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add(" ",typeof(bool));
            dt.Columns.Add("Iteration");
            dt.Columns.Add("View name");
            dt.Columns.Add("Type");

            for (int i = 0; i < list.Count; i++)
            {
                DataRow r = dt.NewRow();

                r[1] = i.ToString();
                r[2] = list[i].Name;
                r[3] = "some element type";

                dt.Rows.Add(r);
            }

            MainGrid.ItemsSource = dt.DefaultView;
            MainGrid.MouseLeftButtonUp += new MouseButtonEventHandler(CellClick);
        }

        private void CellClick(object sender, EventArgs e)
        {
            //Do stuff
        }
    }

So the problem that I'm having is that I can't seem to get multiple checkboxes to be checked. As soon as I try to check a second checkbox the previously checked box becomes unchecked.

The mouse button event was a failed attempt to try to get checkedboxes to remain checked but failed.




Insert replace with codeigniter and multiple checkbox

I am working on a project, where I am making an access based on the user group, but I have a problem when doing multiple insert. the question is how can I enter a value into the database from the checkbox with the insert replace

VIEW

<tr>
    <td class='mail-select'>
        <i class='fa fa-angle-right m-r-15 text-muted'></i>
        <a href='email-read.html' class='email-name'>".$s->name."</a>
        <input name='id_menu[]' value='".$s->id."' type='hidden'>
    </td>
    <td>
        <div class='checkbox checkbox-primary m-r-15'>
            <input name='read[]' value='Y' id='R-".$s->id."' type='checkbox'>
            <label for='R-".$s->id."'></label>
        </div>
    </td>
    <td>
        <div class='checkbox checkbox-primary m-r-15'>
            <input name='create[]' value='Y' id='C-".$s->id."' type='checkbox'>
            <label for='C-".$s->id."'></label>
        </div>
    </td>
    <td>
        <div class='checkbox checkbox-primary m-r-15'>
            <input name='update[]' value='Y' id='U-".$s->id."' type='checkbox'>
            <label for='U-".$s->id."'></label>
        </div>
    </td>
    <td>
        <div class='checkbox checkbox-primary m-r-15'>
            <input name='delete[]' value='Y' id='D-".$s->id."' type='checkbox'>
            <label for='D-".$s->id."'></label>
        </div>
    </td>
</tr>

CONTROLLER

public function addRole()
{
    $group  = $this->input->post('group');
    $num    = $this->input->post('num');
    $id_menu= $this->input->post('id_menu[]');
    $read   = $this->input->post('read[]'); 
    $create = $this->input->post('create[]');   
    $update = $this->input->post('update[]');   
    $delete = $this->input->post('delete[]');   

        for ($i=0;$i<$num;$i++){
         $data = array(
            'group_id' => $group, 
            'menu_id'  => $id_menu[$i],
            'index'    => $read[$i],
            'add'      => $create[$i],
            'edit'     => $update[$i],
            'delete'   => $delete[$i],

             );
            $role =  $this->db->insert_batch('box_role', $data);
        }
    redirect("auth/role", 'refresh');
}




lundi 27 août 2018

How to fix blink issue Create Checkbox using image in Xamarin Forms?

This is the CheckBox.xaml

<?xml version="1.0" encoding="UTF-8"?>  
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"   
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
    x:Class="CheckBoxSample.Controls.CheckBox">  
    <ContentView.Content>  
        <StackLayout Orientation="Horizontal"  
                     x:Name="mainContainer"  
                     HorizontalOptions="FillAndExpand"  
                     VerticalOptions="FillAndExpand"  
                     Padding="0"  
                     Spacing="5">  
            <AbsoluteLayout HorizontalOptions="Center"  
                            VerticalOptions="Center"  
                            WidthRequest="20"  
                            HeightRequest="20"  
                            x:Name="imageContainer">  
                <Image Source="{Binding CheckedBackgroundImageSource}"  
                       x:Name="checkedBackground"  
                       Aspect="AspectFit"  
                       AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"  
                       AbsoluteLayout.LayoutFlags="All"  
                       Opacity="0"  
                       InputTransparent="True"/>  
                <Image Source="{Binding BorderImageSource}"  
                       x:Name="borderImage"  
                       Aspect="AspectFit"  
                       AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"  
                       AbsoluteLayout.LayoutFlags="All"  
                       InputTransparent="True"/>  
                <Image Source="{Binding CheckmarkImageSource}"  
                       x:Name="checkedImage"  
                       Aspect="AspectFit"  
                       AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"  
                       AbsoluteLayout.LayoutFlags="All"  
                       Opacity="0"  
                       InputTransparent="True"/>  
            </AbsoluteLayout>  
            <Label x:Name="controlLabel"  
                   HorizontalOptions="FillAndExpand"  
                   VerticalOptions="FillAndExpand"  
                   HorizontalTextAlignment="Start"  
                   VerticalTextAlignment="Center"  
                   Text="{Binding Title}"  
                   Style="{Binding LabelStyle}"  
                   InputTransparent="True"/>  
        </StackLayout>  
    </ContentView.Content>  
</ContentView>

This is CheckBox.Xaml.cs .

    using System;  
using System.Collections.Generic;  
using Xamarin.Forms;  
using Xamarin.Forms.Xaml;  

namespace CheckBoxSample.Controls  
{ /// <summary>  
  /// Custom checkbox control  
  /// </summary>  
    [XamlCompilation(XamlCompilationOptions.Compile)]  

    public partial class CheckBox : ContentView  
    {  
        public CheckBox()  
        {  
            InitializeComponent();  
            controlLabel.BindingContext = this;  
            checkedBackground.BindingContext = this;  
            checkedImage.BindingContext = this;  
            borderImage.BindingContext = this;  
            mainContainer.GestureRecognizers.Add(new TapGestureRecognizer()  
            {  
                Command = new Command(tapped)  
            });  
        }  

        public static readonly BindableProperty BorderImageSourceProperty = BindableProperty.Create(nameof(BorderImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
        public static readonly BindableProperty CheckedBackgroundImageSourceProperty = BindableProperty.Create(nameof(CheckedBackgroundImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
        public static readonly BindableProperty CheckmarkImageSourceProperty = BindableProperty.Create(nameof(CheckmarkImageSource), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
        public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay, propertyChanged: checkedPropertyChanged);  
        public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(CheckBox), "", BindingMode.OneWay);  
        public static readonly BindableProperty CheckedChangedCommandProperty = BindableProperty.Create(nameof(CheckedChangedCommand), typeof(Command), typeof(CheckBox), null, BindingMode.OneWay);  
        public static readonly BindableProperty LabelStyleProperty = BindableProperty.Create(nameof(LabelStyle), typeof(Style), typeof(CheckBox), null, BindingMode.OneWay);  

        public string BorderImageSource  
        {  
            get { return (string)GetValue(BorderImageSourceProperty); }  
            set { SetValue(BorderImageSourceProperty, value); }  
        }  

        public string CheckedBackgroundImageSource  
        {  
            get { return (string)GetValue(CheckedBackgroundImageSourceProperty); }  
            set { SetValue(CheckedBackgroundImageSourceProperty, value); }  
        }  

        public string CheckmarkImageSource  
        {  
            get { return (string)GetValue(CheckmarkImageSourceProperty); }  
            set { SetValue(CheckmarkImageSourceProperty, value); }  
        }  

        public bool IsChecked  
        {  
            get { return (bool)GetValue(IsCheckedProperty); }  
            set { SetValue(IsCheckedProperty, value); }  
        }  

        public string Title  
        {  
            get { return (string)GetValue(TitleProperty); }  
            set { SetValue(TitleProperty, value); }  
        }  

        public Command CheckedChangedCommand  
        {  
            get { return (Command)GetValue(CheckedChangedCommandProperty); }  
            set { SetValue(CheckedChangedCommandProperty, value); }  
        }  

        public Style LabelStyle  
        {  
            get { return (Style)GetValue(LabelStyleProperty); }  
            set { SetValue(LabelStyleProperty, value); }  
        }  

        public Label ControlLabel  
        {  
            get { return controlLabel; }  
        }  

        static void checkedPropertyChanged(BindableObject bindable, object oldValue, object newValue)  
        {  
            ((CheckBox)bindable).ApplyCheckedState();  

        }  

        /// <summary>  
        /// Handle chackox tapped action  
        /// </summary>  
        void tapped()  
        {  
            IsChecked = !IsChecked;  
            ApplyCheckedState();  
        }  

        /// <summary>  
        /// Reflect the checked event change on the UI  
        /// with a small animation  
        /// </summary>  
        /// <param name="isChecked"></param>  
        ///   
        void ApplyCheckedState()  
        {  
            Animation storyboard = new Animation();  
            Animation fadeAnim = null;  
            Animation checkBounceAnim = null;  
            Animation checkFadeAnim = null;  
            double fadeStartVal = 0;  
            double fadeEndVal = 1;  
            double scaleStartVal = 0;  
            double scaleEndVal = 1;  
            Easing checkEasing = Easing.CubicIn;  

            if (IsChecked)  
            {  
                checkedImage.Scale = 0;  
                fadeStartVal = 0;  
                fadeEndVal = 1;  
                scaleStartVal = 0;  
                scaleEndVal = 1;  
                checkEasing = Easing.CubicIn;  
            }  
            else  
            {  
                fadeStartVal = 1;  
                fadeEndVal = 0;  
                scaleStartVal = 1;  
                scaleEndVal = 0;  
                checkEasing = Easing.CubicOut;  
            }  
            fadeAnim = new Animation(  
                    callback: d => checkedBackground.Opacity = d,  
                    start: fadeStartVal,  
                    end: fadeEndVal,  
                    easing: Easing.CubicOut  
                    );  
            checkFadeAnim = new Animation(  
                callback: d => checkedImage.Opacity = d,  
                start: fadeStartVal,  
                end: fadeEndVal,  
                easing: checkEasing  
                );  
            checkBounceAnim = new Animation(  
                callback: d => checkedImage.Scale = d,  
                start: scaleStartVal,  
                end: scaleEndVal,  
                easing: checkEasing  
                );  

            storyboard.Add(0, 0.6, fadeAnim);  
            storyboard.Add(0, 0.6, checkFadeAnim);  
            storyboard.Add(0.4, 1, checkBounceAnim);  
            storyboard.Commit(this, "checkAnimation", length: 600);  

            if (CheckedChangedCommand != null && CheckedChangedCommand.CanExecute(this))  
                CheckedChangedCommand.Execute(this);  
        }  
    }  
}  

Use custom checkbox in Xamarin.Forms

declare namespace of CheckBox.

xmlns:ctrls="clr-namespace:CheckBoxSample.Controls"

CheckBox like below

<ctrls:CheckBox x:Name="cbIndia" Title="India" IsChecked="True" BorderImageSource="checkborder" CheckedBackgroundImageSource="checkcheckedbg" CheckmarkImageSource="checkcheckmark" /> 

Set the values for the CheckBox properties are

  • Title: India
  • IsChecked: True
  • BorderImageSource: checkborder.png
  • CheckBackgroundImageSource: checkcheckedbg.png
  • CheckmarkImageSource: checkcheckmark.png

Demo Screen for Android.

enter image description here

Demo Screen for IOS.

enter image description here




javascript disable checkbox when another checkbox is checked with same name

I'm trying to make a little quiz in my project. The idea is when one checkbox is clicked, the other option should be disabled. I'm have tried with radio control, but it doesn't work, because I have more than one question with same checkbox name.

Here is my current code

<form name=f1 method=post action="">
    <label>soal 1</label><br>
<input type=checkbox name=domi[] onclick="domi1(this.checked)" >A<br>
<input type=checkbox name=influ[] onclick="influ1(this.checked)">B<br><br>

    <label>soal 2</label><br>
<input type=checkbox name=domi[] onclick="influ2(this.checked)" >A<br>
<input type=checkbox name=influ[] onclick="stedi1(this.checked)">B<br><br>

<button type="submit">simpan</button>
</form>

Javascript code disabled the controls

 <SCRIPT LANGUAGE="JavaScript">
    function domi1(status)
    {
    status=!status; 
    document.f1.influ1.disabled = status;
    }

    function influ1(status)
    {
    status=!status; 
    document.f1.domi1.disabled = status;
    }
    </script>




One checkbox checked at a time - not radio buttons

First, before you recommend radio buttons, I want to use checkboxes because they can be unchecked. I have 2 custom checkboxes #c1 & #c2; I want one open at a time (so if c1 was open, clicking c2 will uncheck c1); and I want both to be able to be unchecked. Any ideas would be greatly appreciated!

Here's what I've tried:`

let c1 = document.getElementById('c1');
let c2 = document.getElementById('c2');

function oneAtATime() {
  if (c1.checked) {
    c2.checked = false;
  } else if (c2.checked) {
    c1.checked = false;
  }
}
c1.addEventListener('change', oneAtATime);
c2.addEventListener('change', oneAtATime);
<input id="c1" type="checkbox" name="checkbox" class="check">
<label for="c1">
        <h2>example</h2>
    </label>
<input id="c1" type="checkbox" name="checkbox" class="check">
<label for="c1">
        <h2>example</h2>
    </label>



How would I Pull Values of 1000+ Checkboxes in Excel?

I am needing to pull the value of a checkbox (Form Control version) and insert it into a cell. I am aware of the method of Right-Clicking on a checkbox - Format Control - Control Tab - Cell Link, but for the spreadsheet I'm needing to do this for has 1000+ checkboxes. So performing that process would be an immense ordeal!

Is there a value a checkbox adheres to within an excel function? In other words, what variable would that checkbox respond to if I were to call that checkbox into a function?

i.e: =IF(CheckBox3 = TRUE, "Complete", " ") (I'm referring to the CheckBox3 text)

Or is there an alternative method to obtaining this information? Any help or suggestions would be much appreciated! (Photo of checkbox example)




Strange onclick behavior for checkboxes. Trying to write onto browser console when a checkbox item is selected

Basically if I click on a checkbox, I want the name of the checkbox to be displayed on the console.

Here is the relevant javascript function and HTML.

javascript:

var list = [];

function test(){
      var checkBoxes = document.querySelectorAll('input[type=checkbox]')
    for(var i = 0; i < checkBoxes.length; i++) {
      checkBoxes[i].addEventListener('change',function(){
        if(this.checked){
          console.log(this.value)
          }
      });
  }
}

HTML:

<label><input type = "checkbox" onclick= "test()" name ="one" value ="one">test<br></label>
<label><input type = "checkbox" onclick= "test()" name ="two" value ="two" > test 1<br></label>
<label><input type = "checkbox" onclick= "test()" name ="three" value ="three" >test 2<br></label>
<label><input type = "checkbox" onclick= "test()" name ="four" value ="four" >test 3<br></label>
<label><input type = "checkbox" onclick= "test()" name ="five" value ="five" >test 4<br></label>
<label><input type = "checkbox" onclick= "test()" name ="six" value ="six" >Test 5<br></label>

If I click on the checkbox it is supposed to show in the console the name of the checked box.

However, something really strange happens and I don’t understand why it is. I have a vague inkling as to why it's happening but it's not quite clear.

When I click on the first check box for example. I click on the checkbox named "one". The console displays:
one (as required)

But if I click on the next check box (for example I clicked on the checkbox named "four"). In the console it displays:
four
four

And the next checkbox clicked (if it's the one named "five") The console shows:
five
five
five

and so on....(incrementally repeating the checkbox name displayed on the console each time I click on another checkbox)

Why is it repeating ? When I click on the checkbox there should be technically one onclick event. How come it's counting all the other ones and repeating the console.log(this.value) bit?

Thanks in advance for any who may be able to give some idea as to why this is happening.




How to increase the size of the CheckBox in ToolStripMenuItem?

To display the context menu in Excel filter of GridGroupingControl, ToolStripMenuItem is used in a ContextMenuStripper. When items are checked, a CheckBox is drawn in the ToolStripItem. When the resolution of the system is changed to 200 DPI, the size of the CheckBox remains the same. I have referred to the below links, that to enable a checkbox, CheckedState property is set.

How can we increase the size of the CheckBox? Please share your ideas.

Image

Reference Links: Link

Thanks and Regards,

Sindhu




angular-data-table selected items filter

Hi I'm using swimlane/angular-data-table and I'm having problems trying to implement a way to show only selected rows, here's a codepen.

The problem is:

I click the button to show only selected items, then I deselect the first one, which correctly disappears, but the new first item checkbox is unchecked, despite its input tag has the attribute checked="checked"

Looking at the unchecked checkbox styles applied, I see there's no :checked pseudo-class before the :before, which is the way this data-table library applies the check to checkboxes.

To me, it looks like a bug inside the library itself, which has been archived; anyway, if this is the case, I could still fix it in my personal fork.

Otherwise, what am I doing wrong?

Thank you in advance




md checkbox change dynamically issue

I have a md-checkbox inside a table cell, this checkbox is used to do a filter.

My issue in here is that when I clear the filters I can't fully clean my checkbox, I can change the value to false and remove the check from the box, however it won't work properly because the next click that user made will move the checkbox again to the false value instead moving it to the true state.

This is my code:

if (document.querySelectorAll(tableID + ' .findInput').length > 0) {
  var $clearButton = $('<button type="button" id="clearButton" class="btn btn-sm btn-default no-margin-bottom">')
      .text(translates.clear)
      .click(function () {
        var inputs = $(tableID + '_wrapper .findInput');
        for (var i = 0; i < inputs.length; i++) {
          $(inputs[i]).val('');
          var event;
          if (inputs[i].tagName === 'MD-SELECT') {
            event = document.createEvent('Event');
            event.initEvent('change', false, true);
            inputs[i].dispatchEvent(event);
          } else if (inputs[i].tagName === 'MD-CHECKBOX') { // issue in here

            event = document.createEvent('Event');
            event.initEvent('change', false, true);
            inputs[i].dispatchEvent(event);
            $(inputs[i])[0].children[0].firstChild.childNodes[0].checked = false;
            inputs[i].className = 'findInput findInputContainer mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked';

          } else {
            event = document.createEvent('Event');
            event.initEvent('input', false, true);
            inputs[i].dispatchEvent(event);

            event = document.createEvent('Event');
            event.initEvent('change', false, true);
            inputs[i].dispatchEvent(event);
          }
        }
        table.columns().every(function () {
          this.search('');
        });
        $searchButton.click();
      });
  $(tableID + ' thead tr:eq(1) th:last-child').append($clearButton); 
}

At the moment I'm changing the value to false and the removing the check class from the md-checkbox so it will look like it's unchecked, however there is still something that I might need to change.




VBA Excel Launching Word Doc can't create clickable checkboxes

I have an Excel Document, where I am looping through the cells to generate a word document with clickable check boxes. I am taking 1 cell value as the header, the next column cell value as the value that needs a check box next to it. Basically it is a list of tasks I want to cut and paste in email to ensure they have been completed. I am using late binding to generate the word document from Excel and am wondering if that has something to do with my issues. I have tried all different examples of creating the checkboxes and usually get an Object Required error message.

Dim wrdApp As Object

Set wrdApp = CreateObject("Word.Application")

Set wrdDoc = wrdApp.Documents.Add

Set objSelection = wrdApp.Selection

For Row = 2 to lRow

   objSelection.TypeText Chr(13) & Cells(Row, 1).Value & Chr(13)

   'Here is where I would like to write a checkbox so it is to the left of the column 2 value

   objSelection.TypeText Cells(Row, 2).Value)

Next Row

I have never written from Excel to Word before, it seems like I should be able to have a simple one line of code of writing the checkbox in place but maybe I am wrong.

I recorded a macro of adding a check box and when I try this code:

 Selection.FormFields.Add Range:=Selection.Range, Type:=wdFieldFormCheckBox  

I get Wrong number of arguments or invalid property assignment.

When I try going along these lines:

   wrdDoc.Selection.FormFields.Add Range:=InsertAfter, Type:=wdFieldFormCheckBox   

I get Object doesn't support this property or method.

Trying something like this

Selection.FormFields.Add Range:=Selection.Range, Type:=wdFieldFormCheckBox    

I get Wrong Number of Arguments or invalid property assignment.

Any help is appreciated. Thanks!




how to validate checkbox and radio button in jquery

I am unable to validate the checkbox and radio button. Actually i just need to insert validation for user at least select one thing weather checkbox or radio. see my code. that's not working for me.

<script>
  $(".submit").click(function(){
       var checkBoxCount = $(".jobwork:checkbox:checked").length;
      if($(".jobwork:checkbox:checked").length < 1 || ($("input[name=jobwork]:checked").length <= 0)){
          alert("Please select atlease one jobwork");
          return false;

      };

  })




How to save checkbox state checked in gridview while shorting the datagridview windows form c#..?

How to save checkbox state checked in gridview while shorting the datagridview from click on header or and from textbox textchange event. in winfows form c#.please help...thanks in advance.this is first pageload

i checked 2 lab tests

i have shorted by click on header of any column or by text search i lost the checked lab test




dimanche 26 août 2018

Why does input[type=checkbox] not allowing CSS?

I am trying to find direct CSS to apply for checkbox. But I could only find the hacks for styling checkbox or radio button. Unlike input[type=button] or [type=text],.. why would checkbox or radio button not allowing the native css styles?




How to add third state to checkbox?

Hi I am developing web application in angular. I am displaying checkbox with three states. I am distinguishing states usng css classes. The three states are cross-marked,check marked and blank. Below is the implementation part.

<div *ngIf="node.data.checked==true && node.data.allow==true">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate" [checked]="node.data.checked">
        <span class="checkmark"></span>
        
    </label>
</div>

<div *ngIf="node.data.checked==true && node.data.allow==false">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate" [checked]="node.data.checked">
        <span class="checkmark xmark"></span>
        

    </label>
</div>

<div *ngIf="node.data.checked==false">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate">
        <span class="checkmark"></span>
        

    </label>
</div>

I am attaching UI image above. Tri state checbox

Device model1 contains cross marked,device model2 contains check marked and devicemodel4 contains blank. These are three states. Now when user clicks on any one of the checkboxe's state should change in the below path.

blank --> checked --> cross --> blank

Above is circular path. For example, if the checkbox is checked then when the user clicks on it then checkbox should become cross and if the user clicks it again then blank and if the user clicks it again then again checked and so on. Displaying part i have done. Can someone help me to make this work as i said above? Any help would be appreciated. Thank you.




Customer custom attribute checkbox in backend magento 1.9

I added my customer attribute, and I want to display these fields as checkboxes in account information tab. I created checkbox in the frontend easily but the backend is not. Please help me. Thanks.




checkbox in bucle for python 3.7

i'm creating check box in a grid. so that grid is progresive while i put a ID it show my the data from sqlite3, something like "facebook"

def consultar():

    label_buscar=Label(pes1, text="Buscar:").grid( row=0, column=0, padx=20, pady=30, ipadx=0, ipady=1)
    entry=Entry(pes1, width=15,justify='center',textvariable=cajaB)
    entry.grid( row=0, column=1)
    entry.bind("<KeyRelease>",buscar)
    Label(pes1, text="Ok").grid( row=1, column=0)
    Label(pes1, text="Rut",width=15).grid( row=1, column=1,)
    Label(pes1, text="Nombre",width=25).grid( row=1, column=2)
    Label(pes1, text="Telefono",width=15).grid( row=1, column=3)
    Label(pes1, text="Evolucion",width=25).grid( row=1, column=4)
    Label(pes1, text="Fecha", width=10).grid( row=1, column=5)
    Label(pes1, text="Hora", width=8).grid( row=1, column=6)
    Label(pes1, text="Carpeta", width=3).grid( row=1, column=7)
    Label(pes1, text="Fichero", width=3).grid( row=1, column=8)

def search(key)

   for cell in pes1.grid_slaves():
      if int(cell.grid_info()["row"]) >= 2:
        cell.grid_forget()

   contacto = Contacto()
   arreglo = contacto.buscar(cajaB.get())
   m=2
   n=1

   for c in arreglo:
       m=m+1
       n=n+1
       for r in range(n,m):
          for co in range(1, 9):

            cell = Entry(pes1, width=15,justify='center',font=("Calibri",10),disabledbackground="white",disabledforeground="black")
            cell.grid(padx=1, pady=1, row=r, column=co)
            cell.insert(END,c[co-1])
            cell.config (state = DISABLED )
            var = StringVar()
            cb = Checkbutton(pes1, command=checkbox, variable=var)
            cb.grid( row=r, column=0)                   

so i need what when someone click on a checkbox, that take a data from grid and call a funtion with that data take before.

see the image -->> image

i need do that coz when checkbox is on, check in my database if that data exits or not and when checkbox if off nothing happen

you can see in the image, when as i enter an id, show me how many people who have that id




Error: incorrect number of dimension Shiny

I am new to Shiny.

When I run the following code I get the message "incorrect number of dimension".

I would like to place a checkboxgroupinput next to every rows of NameGen table, which is a result of a selectInput. Then, if one row is checked, this will go in a new table in the mainPanel.

ui.r

library(shiny)

fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select","Type",c("C","R","V"),selected=NULL),
      uiOutput("choose_row")
    ),
    mainPanel(
      tableOutput("result")
    )
  )
)

server.r

library(shiny)

function(input,output){
  data1<-reactive({
    setwd("/Users/me/Desktop/DirectoryAlR")
    AlData<-read.delim2("AlR.csv",sep=";",stringsAsFactors = FALSE)
    NameGen<-NULL
    for(i in 1:nrow(AlData)){
      if(AlData[i,7]==input$select){
        NameGen[i]<-AlData[i,1]
      }else{
        NameGen[i]<-NA
      }
    }
    NameGen<-NameGen[!is.na(NameGen)]
    return(NameGen)
    })

  output$choose_row<-renderUI({
    rn<-rownames(data1())
    checkboxGroupInput("box","",rn,selected=NULL)
  })


  result<-reactive({
    data2<-data1()
    data2[input$box,,drop=FALSE]
  })


  output$result<-renderTable(result())
}




Jquery: How to hold checkbox check / uncheck state in hidden field

i have a html table which i has many checkboxes. when user click on header checkbox then all child checkbox will be checked and unchecked based on header checkbox checked state.

user can uncheck and check any child checkbox too. i want to store child checkbox value in hidden field separated by comma. when child checkbox is selected then checkbox value will be store in hiiden field but if that checkbox value is in hiiden field then will not be store in hidden field.

when user uncheck anyone then that checkbox value will be removed from hidden field.

I tried this way but not successful. so guide me how to achieve it. my code as follows

<table id="tbl" border="10">
<thead>
<tr>
<td><input type="checkbox" id = "chckHead" /></td>
<td>First Row</td>
<td>Second Row</td>
<td>Third Row</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class = "chcktbl" value="101"/>
</td>
<td>1</td>
<td>1</td>
<td>1</td>
 </tr>
<tr>
<td>
<input type="checkbox" class = "chcktbl"  value="102"/>
</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>
<input type="checkbox" class = "chcktbl"  value="103"/>
</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
</tbody>
</table>
<input id="hidden" type="hidden" name="hidden">

$(document).ready(function(){
  $('#chckHead').click(function () {
    $(".chcktbl").prop('checked', $(this).prop("checked"));
  });  

  $(".chcktbl").change(function() {
  var values = [];
  $('.chcktbl').each(function (index, obj) {
  alert('pop');
    if (this.checked === true) {
      values.push($(this).val());
    }
  });
  });
  alert(values.toString());

});




RPA Express (Workfusion) Web Element seting a checkbox

I am new to RPA Express (Workfusion) and I can't figure out how to set a checkbox to true using Web Element - set by xpath. What needs to be pun into a variable to set a checkbox to CHECKED status?

I can't use Click Mouse function as it would toggle the status while my goal is to ensure that a checkbox is set to TRUE always.




samedi 25 août 2018

concrete5 How to handle checkbox in single page controller?

I have a checkbox in a single page:

echo $form->checkbox('policy', 1, '0');
echo t("I have read and agree to the") . ' <a href="' . \URL::to('/', 'terms') . '" target="_blank">' . t('Terms and Conditions') . '</a>';

I set its value with JS:

$('#policy').on('change', function() {
    $(this).val(this.checked ? 1 : 0);
    $(this).attr('checked', this.checked ? true : false);
}).trigger('change');

but the controller doesn't read its value.

I tried both of these:

$data = $this->post();

$policy = $data['policy'];
$policy = isset($data['policy']) ? 1 : 0;

The first one reads nothing, the second one always reads 0.

I know the save() function reads checkbox values but I don't save anything, my single page controller simply needs to check the form inputs and then route to another page.

How can I handle the checkbox in a single page controller without saving?




Binding CheckBox multiple conditions for data trigger in WPF?

I have a problem with binding CheckBox to multiple conditions for data trigger. I'm trying to change the background of DataGridRow with two conditions.

First - CheckBox IsChecked.

Second - DataGridCell value is 1.

Here is my code

<CheckBox x:Name="chkTehnickaPodrska" Content="Oboj tikete kojima je istekla teh. podrška" Margin="5" IsChecked="True"/>

<Style.Triggers>
      <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=chkTehnickaPodrska}" Value="True"/>
            <Condition Binding="{Binding [Istekla tehnička podrška]}" Value="1"/>
          </MultiDataTrigger.Conditions>
          <Setter Property="Background" Value="Red"/>
      </MultiDataTrigger>
</Style.Triggers>




vendredi 24 août 2018

How to get the checkbox value in javascript or jquery?

I already tried all the possible ways, but I still didn't get it working. I have a modal window with a checkbox and submit button. What I need to do is onclick add button, a modal will opens and in that checkbox will be displays already stored value. "What is my concept is for example: In a page, if I have a device and I need to enter all the specifications about the device. So, I need to enter the second device on the page, I have provided an add button to add the specification. This is my concept" So I have done a lot of new modal in this method. Now what I am trying to do is, In case I missed a parameter in insertion in the first time of inserting the device. So I need to insert it for the specific device. Thinks I need to know! 1. I didn't know how to checkbox check or uncheck should be based on a database value. 2. For example, I have used a master data, for including it to a device while inserting the first time. "So I have used a foreach method and fetch the data through checkbox" You may see the example below hoI i used it!

<div class="form-body pal">
        <div class="col-md-6">
                <div class="form-group"><label class="control-label">{attribute_name module=engg attribute=properties}<span class='require'>*</span></label>
                        <div class="input-icon right">
                {foreach name=list item=item key=key from=$test_paralist}
                                <input type="checkbox" name="aequip_para_name[]" id="aequip_para_name" value="{$item.object_id}" class="form-        control">&nbsp;&nbsp;"{$item.parameter}<br>
                                {/foreach}
                        </div>
                </div> 
        </div>                                                        
</div>
  1. I need to insert the missed data for a device in the checkbox method. what's my requirement is. "First i have already inserted some data in the database, how its to validate is while inserting second time new value to the device, the already enter checkbox data should not shown that is by while onclick add button. Only the remaining master data need to be shown.

I used the ajax concept for fetch the data for javascript.

$(document).ready(function() {
    $("#test_parameter_add").click(function(){
                x_get_equip_test_filtered_parameter($("#test_parameter_add").   val(),get_equip_test_filtered_parameter);
    });
});

Please help me to write the below function method, the checkbox value to validate and shows only the new value not the already entered value.

function get_equip_test_filtered_parameter(result) {

}
My Ajax concept is working fine. i need javascript or jquery methods. please help as soon as possible

Thanks is advance!!!




I Passed Text successfully into my SQLite db but my app is crashing when i try to pass selected checkbox values to SQLite db

i have a functional DBhelper class extended to SQLiteOpenhelper which successfully created and populates my database. However when i try to populate the database with checked box values my app crashes. I believe its something wrong with my piece of code which says controller.insert_checkbox(checked), because when i comment it out my code runs and shows the toast that follows on the screen. Here is my code;

public class LocationCategoryChkbxNew extends AppCompatActivity {

Button button2;
CheckBox chkbox15;

int checked = 0;
ResturantsDbHelper controller;

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

    controller = new ResturantsDbHelper(this);
    button2 = (Button)findViewById(R.id.button2);
    getSupportActionBar().setTitle("Your Foodometer:  Hungry ..");

    chkbox15=(CheckBox)findViewById(R.id.checkBox15);
    chkbox15.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                checked = 1;
                }else {
                checked = 0;
            }
        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            controller.insert_checkbox(checked);
            Toast.makeText(getApplicationContext(), "Saved '"+ checked + "' in DB", Toast.LENGTH_SHORT).show();

            Intent myIntent = new Intent(LocationCategoryChkbxNew.this,
                               ResturantCategoryChkboxNew.class);
                       startActivity(myIntent);
        }
    });

}

And here is my DBHelper class public class ResturantsDbHelper extends SQLiteOpenHelper { private static final String TAG ="DatabaseHelper";

// FIRST DB - Name of the resturant database file. if you change the DB Schema you must increment the database version
private static final String DATABASE_NAME1 = "Resturants.db";
//Resturant Database version
private static final int DATABASE_VERSION1 = 1;

//import LocationCategoryChkbx class
//private LocationCategoryChkbx;

public ResturantsDbHelper(Context context){
    super(context, DATABASE_NAME1,null, DATABASE_VERSION1);
}

//watching the spacing, you cannot leave spaces after the comma and quote at the end of each statement below
@Override
public void onCreate(SQLiteDatabase db) {
    String SQL_CREATE_RESTURANTS_TABLE = "CREATE TABLE " + ResturantEntry.TABLE_NAME + "("
            + ResturantEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + ResturantEntry.COLUMN_NAME + " TEXT NOT NULL,"
            + ResturantEntry.COLUMN_TYPE + " TEXT NOT NULL,"
            + ResturantEntry.COLUMN_ADDRESS + " TEXT NOT NULL,"
            + ResturantEntry.COLUMN_LOCATION + " TEXT NOT NULL,"
            + ResturantEntry.COLUMN_GPSCOORDINATES + " INTEGER NOT NULL,"
            + ResturantEntry.COLUMN_TELEPHONE + " INTEGER NOT NULL,"
            + ResturantEntry.COLUMN_OPENINGHOURS + " INTEGER NOT NULL,"
            + ResturantEntry.COLUMN_CLOSINGHOURS + " INTEGER NOT NULL,"
           + ResturantEntry.COLUMN_CHECKBOX + " TEXT);";

    db.execSQL(SQL_CREATE_RESTURANTS_TABLE);


}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL(String.format("DROP IF TABLE EXISTS %s", TABLE_NAME));
    onCreate(db);
       }

//We create a method for adding data to the database, we will call it “Insert_data” //public boolean insert_data(String s, String trim, String item, String trim1, String s1, String trim2, String s2, String trim3){ public void insert_data (String mResturantName, String mAddress, String mRestTypeSpinner, String mLocationSpinner, String mGPS_coordinates, String mTelephone, String mOpeningHour, String mClosingHour){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(ResturantContract.ResturantEntry.COLUMN_NAME, mResturantName ); contentValues.put(ResturantContract.ResturantEntry.COLUMN_TYPE, mAddress); contentValues.put(ResturantContract.ResturantEntry.COLUMN_ADDRESS, mRestTypeSpinner); contentValues.put(ResturantContract.ResturantEntry.COLUMN_LOCATION, mLocationSpinner); contentValues.put(ResturantContract.ResturantEntry.COLUMN_GPSCOORDINATES, mGPS_coordinates); contentValues.put(ResturantContract.ResturantEntry.COLUMN_TELEPHONE, mTelephone); contentValues.put(ResturantContract.ResturantEntry.COLUMN_OPENINGHOURS, mOpeningHour); contentValues.put(ResturantContract.ResturantEntry.COLUMN_CLOSINGHOURS, mClosingHour);

this.getWritableDatabase().insertOrThrow(ResturantContract.ResturantEntry.TABLE_NAME,"",contentValues);

}

public Cursor getResturantList(){

    SQLiteDatabase database=this.getWritableDatabase();
    Cursor resturantdata;
    resturantdata = database.rawQuery("SELECT * FROM " + TABLE_NAME,null);

    return resturantdata;


}


public void insert_checkbox(int checked) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(ResturantContract.ResturantEntry.COLUMN_CHECKBOX, checked );

    this.getWritableDatabase().insertOrThrow(ResturantContract.ResturantEntry.TABLE_NAME,"",contentValues);


}

}

I will appreciate any help, I have been battling this for 2 days now




How to set the delete button that is not active until at least one checkbox is selected?

How do I insert v-bind: disabled = "disabled" as an attribute in this code and change delete button to delete all items instead of one by one?

Here is the code:

  <b-btn @click.prevent="onDelete(data.item, data.index)"
           variant="danger">Delete
  </b-btn>




How do you send the row of a checkbox to a slot in a column of checkboxes in a QTableWidget (PyQt4)?

This is what I have now. When any checkbox is clicked, self.checkbox_change get executed but the row and checkbox parameters is always that of the last checkbox. I got the slots example from QCheckBox state change PyQt4 but it seems there might be an issue with the lambda x: slot() or slot = partial() functions.

Essentially what I am trying to accomplish is to update multiple checkboxes based on metadata item.setData(Qt.UserRole, QVariant(QString(record[0]))) stored in the same row. The plan is to update all the checkboxes on any checkbox change.

#!/usr/bin/env python

from functools import partial
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import ui_mainwindow


class MainWindow(QMainWindow, ui_mainwindow.Ui_MainWindow):
    def __init__(self, parent):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.contacts = [
            ('test1', 'Test1'),
            ('test2', 'Test2'),
            ('test3', 'Test3'),
            ('test4', 'Test4'),
            ('test5', 'Test5'),
            ('test6', 'Test6'),
        ]
        self.init_tablewidget()

    def init_tablewidget(self):
        self.tableWidget.clear()
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(10)
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(1, 60)
        self.tableWidget.setAlternatingRowColors(True)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.tableWidget.setCornerButtonEnabled(False)
        self.checkboxes = []

        for row, record in enumerate(self.contacts):
            item = QTableWidgetItem(record[1])
            item.setData(Qt.UserRole, QVariant(QString(record[0])))
            item.setTextAlignment(Qt.AlignLeft)
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(row, 0, item)

            widget = QWidget()
            checkbox = QCheckBox()
            checkbox.setCheckState(Qt.Checked)
            self.checkboxes.append(checkbox)
            layout = QHBoxLayout(widget)
            layout.addWidget(checkbox)
            layout.setAlignment(Qt.AlignCenter)
            layout.setContentsMargins(0, 0, 0, 0)
            widget.setLayout(layout)
            self.tableWidget.setCellWidget(row, 1, widget)

            # Got the slot connection code from:
            # https://stackoverflow.com/questions/38437347/qcheckbox-state-change-pyqt4

            slot = partial(self.checkbox_change, checkbox, row)
            checkbox.stateChanged.connect(lambda x: slot())

        horizontalHeader = self.tableWidget.horizontalHeader()
        horizontalHeader.setStretchLastSection(True)

        item = QTableWidgetItem('Company')
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem('Send')
        self.tableWidget.setHorizontalHeaderItem(1, item)

    def checkbox_change(self, checkbox, row):
        print 'change', id(checkbox), row


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create('vista'))
    form = MainWindow(None)
    form.showNormal()
    sys.exit(app.exec_())

Here is the designer generated ui_mainwindow.py file:

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(789, 694)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.tableWidget = QtGui.QTableWidget(self.centralwidget)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.verticalLayout.addWidget(self.tableWidget)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.sendPushButton = QtGui.QPushButton(self.centralwidget)
        self.sendPushButton.setObjectName(_fromUtf8("sendPushButton"))
        self.horizontalLayout.addWidget(self.sendPushButton)
        self.quitPushButton = QtGui.QPushButton(self.centralwidget)
        self.quitPushButton.setObjectName(_fromUtf8("quitPushButton"))
        self.horizontalLayout.addWidget(self.quitPushButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 789, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        MainWindow.setMenuBar(self.menubar)
        self.action_Exit = QtGui.QAction(MainWindow)
        self.action_Exit.setObjectName(_fromUtf8("action_Exit"))
        self.menuFile.addAction(self.action_Exit)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.quitPushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.close)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.tableWidget, self.sendPushButton)
        MainWindow.setTabOrder(self.sendPushButton, self.quitPushButton)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.sendPushButton.setText(_translate("MainWindow", "Send Emails", None))
        self.quitPushButton.setText(_translate("MainWindow", "Quit", None))
        self.menuFile.setTitle(_translate("MainWindow", "&File", None))
        self.action_Exit.setText(_translate("MainWindow", "E&xit", None))
        self.action_Exit.setShortcut(_translate("MainWindow", "Ctrl+Q", None))