mercredi 31 octobre 2018

svg shapes alue replacing on checkbox checking and vise versa

Question:I want the checkbox values into svg ellipsis, when i check on checkbox more than one, then both of them value replace in that svg ellipsis. WHen i checked the checkbox, the value against that checkbox show in that svg shape and replace.




Pass and retrieve boolean value from multiple activities using sharedPreference

i'm trying to pass and retrieve checkbox data from multiple activities in android studio to one activity which is the RuleBasedActivity.java using sharedPreference. Then in RuleBasedActivity i'm using the if else statement to display the result in another activity which is HeartDiseaseResult.java based on checkbox tick by user. In RuleBasedActivity, i try to code a simple if else condition test if it is successful to display the result; the result should be either low risk possibility of heart disease, high risk, unlikely or other. For example if user tick checkbox leftArm || bothArms, it should display High Risk of Heart Diseasetrue and if user tick checkbox NoneOther || radioMale || sweating || jaw it will display Low Risk of Heart Diseasetrue but, unfortunately, it display all the 4 result , please, hope to get some help here.

TwoDActitivty1.java

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

        buttonHome = (Button) findViewById(R.id.buttonHome);
        buttonBackBody = (Button) findViewById(R.id.buttonBackBody);
        buttonNext = (Button) findViewById(R.id.buttonNext);

        head = (Button) findViewById(R.id.head);
        neck = (Button) findViewById(R.id.neck);
        shoulder = (Button) findViewById(R.id.shoulder);
        chest = (Button) findViewById(R.id.chest);
        abdominal = (Button) findViewById(R.id.abdominal);
        arm = (Button) findViewById(R.id.arm);
        pulse = (Button) findViewById(R.id.pulse);

        buttonHome.setOnClickListener(this);
        buttonBackBody.setOnClickListener(this);
        buttonNext.setOnClickListener(this);


        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog();
            }
        });

        neck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog1();
            }
        });

        shoulder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog2();
            }
        });

        chest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog3();
            }
        });


        arm.setOnClickListener(
                new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog6();
            }
        });
    }

    private void showUpdateDialog() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_head, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Did the pain / discomfort spread to:");

        final CheckBox dizziness = (CheckBox) dialogView.findViewById(R.id.dizziness);
        final CheckBox lightheadedness = (CheckBox) dialogView.findViewById(R.id.lightheadedness);
        final CheckBox fatigue = (CheckBox) dialogView.findViewById(R.id.fatigue);
        final CheckBox sleepDisturbance = (CheckBox) dialogView.findViewById(R.id.sleepDisturbance);
        final CheckBox stress = (CheckBox) dialogView.findViewById(R.id.stress);
        final CheckBox nausea = (CheckBox) dialogView.findViewById(R.id.nausea);
        final CheckBox vomiting = (CheckBox) dialogView.findViewById(R.id.vomiting);
        final CheckBox shortnessOfBreath = (CheckBox) dialogView.findViewById(R.id.shortnessOfBreath);
        final CheckBox NoneHead = (CheckBox) dialogView.findViewById(R.id.NoneHead);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (dizziness.isChecked()) {
                    editor.putBoolean("dizziness", true);
                }

                if (lightheadedness.isChecked()) {
                    editor.putBoolean("lightheadedness", true);
                }

                if (fatigue.isChecked()) {
                    editor.putBoolean("fatigue", true);
                }

                if (sleepDisturbance.isChecked()) {
                    editor.putBoolean("sleepDisturbance", true);
                }

                if (stress.isChecked()) {
                    editor.putBoolean("stress", true);
                }

                if (nausea.isChecked()) {
                    editor.putBoolean("nausea", true);
                }

                if (vomiting.isChecked()) {
                    editor.putBoolean("vomiting", true);
                }

                if (shortnessOfBreath.isChecked()) {
                    editor.putBoolean("shortnessOfBreath", true);
                }

                if (NoneHead.isChecked()) {
                    editor.putBoolean("NoneHead", true);
                }
                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    private void showUpdateDialog1() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_neck, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Please select the best one");
        dialogBuilder.setMessage("Where does the pain / discomfort spread:");

        final CheckBox throatOrNeck = (CheckBox) dialogView.findViewById(R.id.throatOrNeck);
        final CheckBox jaw = (CheckBox) dialogView.findViewById(R.id.jaw);
        final CheckBox backOfHeadAndNeck = (CheckBox) dialogView.findViewById(R.id.backOfHeadAndNeck);
        final CheckBox NoneNeck = (CheckBox) dialogView.findViewById(R.id.NoneNeck);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (throatOrNeck.isChecked()) {
                    editor.putBoolean("throatOrNeck", true);
                }

                if (jaw.isChecked()) {
                    editor.putBoolean("jaw", true);
                }

                if (backOfHeadAndNeck.isChecked()) {
                    editor.putBoolean("backOfHeadAndNeck", true);
                }

                if (NoneNeck.isChecked()) {
                    editor.putBoolean("NoneNeck", true);
                }

                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    private void showUpdateDialog2() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_shoulder, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Please select the best one");
        dialogBuilder.setMessage("Where does the pain / discomfort spread:");

        final CheckBox leftShoulder = (CheckBox) dialogView.findViewById(R.id.leftShoulder);
        final CheckBox bothShoulder = (CheckBox) dialogView.findViewById(R.id.bothShoulder);
        final CheckBox NoneShoulder = (CheckBox) dialogView.findViewById(R.id.NoneShoulder);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (leftShoulder.isChecked()) {
                    editor.putBoolean("leftShoulder", true);
                }

                if (bothShoulder.isChecked()) {
                    editor.putBoolean("bothShoulder", true);
                }

                if (NoneShoulder.isChecked()) {
                    editor.putBoolean("NoneShoulder", true);
                }

                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

    }

    private void showUpdateDialog3() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_chest, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Please select the best one");
        dialogBuilder.setMessage("Which of these best describes Chest pain / discomfort that you feel:");

        final CheckBox chest1 = (CheckBox) dialogView.findViewById(R.id.chest1);
        final CheckBox chest2 = (CheckBox) dialogView.findViewById(R.id.chest2);
        final CheckBox chest3 = (CheckBox) dialogView.findViewById(R.id.chest3);
        final CheckBox chest4 = (CheckBox) dialogView.findViewById(R.id.chest4);
        final CheckBox chest5 = (CheckBox) dialogView.findViewById(R.id.chest5);
        final CheckBox chest6 = (CheckBox) dialogView.findViewById(R.id.chest6);
        final CheckBox chest7 = (CheckBox) dialogView.findViewById(R.id.chest7);
        final CheckBox NoneChest = (CheckBox) dialogView.findViewById(R.id.NoneChest);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (chest1.isChecked()) {
                    editor.putBoolean("chest1", true);
                }

                if (chest2.isChecked()) {
                    editor.putBoolean("chest2", true);
                }

                if (chest3.isChecked()) {
                    editor.putBoolean("chest3", true);
                }

                if (chest4.isChecked()) {
                    editor.putBoolean("chest4", true);
                }

                if (chest5.isChecked()) {
                    editor.putBoolean("chest5", true);
                }

                if (chest6.isChecked()) {
                    editor.putBoolean("chest6", true);
                }

                if (chest7.isChecked()) {
                    editor.putBoolean("chest7", true);
                }

                if (NoneChest.isChecked()) {
                    editor.putBoolean("NoneChest", true);
                }

                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }
        private void showUpdateDialog6() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_arm, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Please select the best one");
        dialogBuilder.setMessage("Where does the pain / discomfort spread:");

        final CheckBox leftArm = (CheckBox) dialogView.findViewById(R.id.leftArm);
        final CheckBox bothArms = (CheckBox) dialogView.findViewById(R.id.bothArms);
        final CheckBox NoneArm = (CheckBox) dialogView.findViewById(R.id.NoneArm);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (leftArm.isChecked()) {
                    editor.putBoolean("leftArm", true);
                }

                if (bothArms.isChecked()) {
                    editor.putBoolean("bothArms", true);
                }

                if (NoneArm.isChecked()) {
                    editor.putBoolean("NoneArm", true);
                }

                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

    }
}

TwoDActivity2.java

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


        buttonHome = (Button) findViewById(R.id.buttonHome);
        buttonFrontBody = (Button) findViewById(R.id.buttonFrontBody);
        backNeck = (Button) findViewById(R.id.backNeck);
        skin = (Button) findViewById(R.id.skin);

        buttonHome.setOnClickListener(this);
        buttonFrontBody.setOnClickListener(this);

        backNeck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog();
            }
        });

        skin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showUpdateDialog1();
            }
        });

    }

    private void showUpdateDialog() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_backneck, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Does the pain / discomfort spread:");

        final CheckBox backNeck = (CheckBox) dialogView.findViewById(R.id.backNeck);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (backNeck.isChecked()) {
                    editor.putBoolean("backNeck", true);
                }
                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    private void showUpdateDialog1() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.checkbox_skin, null);

        dialogBuilder.setView(dialogView);

        dialogBuilder.setTitle("Other sign?");

        final CheckBox sweating = (CheckBox) dialogView.findViewById(R.id.sweating);
        final Button save = (Button) dialogView.findViewById(R.id.save);
        final Button cancel = (Button) dialogView.findViewById(R.id.cancel);

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("symptom_list", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (sweating.isChecked()) {
                    editor.putBoolean("sweating", true);
                }
                editor.apply();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }
}

ReleBasedActivity.java

    boolean highRiskOfHeartDisease, lowRiskOfHeartDisease, unlikelyNoHeartDisease, other;
    private Button diagnose;


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

        final SharedPreferences sharedPreferences = getSharedPreferences("symptom_list", Context.MODE_PRIVATE);

        //from other activity(first page)
        final Boolean radioMale = sharedPreferences.getBoolean("radioMale", false);
        final Boolean radioFemaleNotMonopause = sharedPreferences.getBoolean("radioFemaleNotMonopause", false);
        final Boolean radioFemaleMonopause = sharedPreferences.getBoolean("radioFemaleMonopause", false);
        final Boolean BP = sharedPreferences.getBoolean("BP", false);
        final Boolean notActive = sharedPreferences.getBoolean("notActive", false);
        final Boolean diabetic = sharedPreferences.getBoolean("diabetic", false);
        final Boolean smoke = sharedPreferences.getBoolean("smoke", false);
        final Boolean familyHistory = sharedPreferences.getBoolean("familyHistory", false);
        final Boolean hadHeartAttackBefore = sharedPreferences.getBoolean("hadHeartAttackBefore", false);
        final Boolean NoneOther = sharedPreferences.getBoolean("NoneOther", false);


        //TwoDActivity1
        //checkbox from head button
        final Boolean dizziness = sharedPreferences.getBoolean("dizziness", false);
        final Boolean lightheadedness = sharedPreferences.getBoolean("lightheadedness", false);
        final Boolean fatigue = sharedPreferences.getBoolean("fatigue", false);
        final Boolean sleepDisturbance = sharedPreferences.getBoolean("sleepDisturbance", false);
        final Boolean stress = sharedPreferences.getBoolean("stress", false);
        final Boolean nausea = sharedPreferences.getBoolean("nausea", false);
        final Boolean vomiting = sharedPreferences.getBoolean("vomiting", false);
        final Boolean shortnessOfBreath = sharedPreferences.getBoolean("shortnessOfBreath", false);
        final Boolean NoneHead = sharedPreferences.getBoolean("NoneHead", false);

        //checkbox from neck button
        final Boolean throatOrNeck = sharedPreferences.getBoolean("throatOrNeck", false);
        final Boolean jaw = sharedPreferences.getBoolean("jaw", false);
        final Boolean backOfHeadAndNeck = sharedPreferences.getBoolean("backOfHeadAndNeck", false);
        final Boolean NoneNeck = sharedPreferences.getBoolean("NoneNeck", false);

        //checkbox from shoulder button
        final Boolean leftShoulder = sharedPreferences.getBoolean("leftShoulder", false);
        final Boolean bothShoulder = sharedPreferences.getBoolean("bothShoulder", false);
        final Boolean NoneShoulder = sharedPreferences.getBoolean("NoneShoulder", false);

        //checkbox from chest button
        final Boolean chest1 = sharedPreferences.getBoolean("chest1", false);
        final Boolean chest2 = sharedPreferences.getBoolean("chest2", false);
        final Boolean chest3 = sharedPreferences.getBoolean("chest3", false);
        final Boolean chest4 = sharedPreferences.getBoolean("chest4", false);
        final Boolean chest5 = sharedPreferences.getBoolean("chest5", false);
        final Boolean chest6 = sharedPreferences.getBoolean("chest6", false);
        final Boolean chest7 = sharedPreferences.getBoolean("chest7", false);
        final Boolean NoneChest = sharedPreferences.getBoolean("NoneChest", false);

        //checkbox from arm button
        final Boolean leftArm = sharedPreferences.getBoolean("leftArm", false);
        final Boolean bothArms = sharedPreferences.getBoolean("bothArms", false);
        final Boolean NoneArm = sharedPreferences.getBoolean("NoneArm", false);


        //TwoDActivity2
        //checkbox from backNeck
        final Boolean backNeck = sharedPreferences.getBoolean("backNeck", false);

        //checkbox from skin
        final Boolean sweating = sharedPreferences.getBoolean("sweating", false);


        diagnose = (Button) findViewById(R.id.diagnose);

        diagnose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                highRiskOfHeartDisease = true;
                lowRiskOfHeartDisease = true;
                unlikelyNoHeartDisease = true;
                other = true;

                if (leftArm || bothArms) {
                    highRiskOfHeartDisease = true;
                }
                else if (lightheadedness || leftShoulder) {
                    unlikelyNoHeartDisease = true;
                }
                else if (chest1) {
                    other = true;
                }
                else if (NoneOther || radioMale || sweating || jaw) {
                    lowRiskOfHeartDisease = true;
                }


                Intent intentBundle = new Intent(getBaseContext(), HeartSymptomActivity.class);
                Bundle bundle = new Bundle();
                bundle.putBoolean("highRisk", highRiskOfHeartDisease);
                bundle.putBoolean("lowRisk", lowRiskOfHeartDisease);
                bundle.putBoolean("unlikely", unlikelyNoHeartDisease);
                bundle.putBoolean("other", other);
                intentBundle.putExtras(bundle);
                startActivity(intentBundle);
            }
        });



    }
}

HeartSymptomResult.java

    boolean highRisk, lowRisk, unlikely, other;
    private Button clear;


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

        addData();

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycleView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        TextAdapter textAdapter = new TextAdapter();
        recyclerView.setAdapter(textAdapter);

        List<String> stringList = new ArrayList<>();

        if (highRisk) {
            stringList.add("High Risk of Heart Disease" + highRisk);
        }

        if (lowRisk) {
            stringList.add("Low Risk of Heart Disease" + lowRisk);
        }

        if (unlikely) {
            stringList.add("Maybe no sign Heart Disease" + unlikely);
        }

        if (other) {
            stringList.add("Try test" + other);
        }

        List<String> list = new ArrayList<>();
        list.addAll(stringList);

        textAdapter.setmItems(list);
    }
    private void addData() {
        //intent Bundle
        Intent intentExtras = getIntent();
        Bundle extrasBundle = intentExtras.getExtras();

        if (extrasBundle != null) {
            highRisk = extrasBundle.getBoolean("highRisk");
            lowRisk = extrasBundle.getBoolean("lowRisk");
            unlikely = extrasBundle.getBoolean("unlikely");
            other = extrasBundle.getBoolean("other");
        }

    }


}




Ng-select multiple="true"with checkbox (blur) event fired when I click on checkbox

I was trying to implement (blur) with ng-select multiple with checkboxes,so the everytime I change my model I will not be making api calls .API calls will be made only when ng-select is out of focus. Api will be called on (blur) . But when I click on checkbox which is defined inside ng-select only using ng-template it is triggering the blur event. I want to emit only on blur.

<div  style="width: 100%"  tabindex="0" >

                             <ng-select #mySelect  class="custom" [style]="{'height':'10px', 'width':'100%','border':'2px'}"

                                [items]="lookup.investorKnowledgeSource.asArray"
                                [multiple]="true"
                                [closeOnSelect]="false"
                                [(ngModel)]="it.source"
                                 placeholder="Select Source Of Knowledge Product"
                                [clearable]="false"
                                (ngModelChange)="onChangeKnowledgeSource($event,it)"
                                (blur)="change.emit()"

                               >
                           <ng-template   ng-multi-label-tmp >
                              <span><b>()Selected</b></span>
                          </ng-template>

                            <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
                                <input id="item-" type="checkbox"  [ngModel]="item$.selected"  [disabled]="item.disabled"/> 
                            </ng-template>
                          </ng-select>

                      </div>




Disable click event on mvc kendo grid containing checkbox

I have column holding the checkbox on a MVC kendo grid. When I click on the column but not on the checkbox, the checkbox position is slipping (moving towards right) and the click event is not delegating to checkbox.

I tried Change event and DataBound to suppress the click even on column but couldn't do it.

Any suggestions to disable the click event on this Kendo Grid checkbox-column or to delegate the column's click event to checkbox!

Below is the code snippet that I have used to build the checkbox column,

columns.Bound(p => p.IsSelected).Title("Select").Width(11).ClientTemplate("<input type='checkbox' #= (IsSelected) ? checked='checked' : '' #  id=chk#=(Id)#  class='exclchkbx' />").HtmlAttributes(new { style = "text-align: center;" }).Width(10).HeaderHtmlAttributes(new { style = "text-align:center;" });



Output of my grid column

enter image description here

Dislocated checkbox after clicking the checkbox column (but not on checkbox)

enter image description here

Appreciated in advance!




Long click listener not working for checkbox and radiobutton since setEnabled() is false

I have a checkbox and a radiobutton which has to be in the disabled state, so I give setEnabled(false). But I want longclicklistener to work which is not happening.

This is the piece of code for checkbox, which will be similar to the radiobutton's in my case:

mCheckbox.setEnabled( false );
mCheckbox.setOnLongClickListener( new View.OnLongClickListener() {
            @Override
            public boolean onLongClick( View v ) {
                if( longClickListener != null ) {   //Call didn't even come here while debugging.
                    longClickListener.onLongClick( mCheckbox );
                    return true;
                }
                return false;
            }
        } );

Any help is greatly appreciated.Thanks in advance.




Android Checkbox error by checking the Checkbox

 <CheckBox
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id="@+id/metriccheckbox"
     android:onClick="onCheckboxClicked"
     android:focusable="false"
     android:checked="true" />

enter image description here

If i restart the activity, it Shows normal.How can i fix this?




VBA UserForm--Select Multiple Checkboxes and display only the information related to the checkboxes selected

I'm building an interactive UserForm for work. I am using checkboxes for the users to select multiple services ordered by clients and I would only like to display the information for the specific checkboxes selected. All other information would be hidden from view.

I probably need an If and Else statement, but I need help with the code.

Can anyone help?




Angular 6 - In MCQ, [(ngModel)] show the good answer

I'm working on a MCQ in Angular 6. I have a problem with my checkboxs which show the good answer straight away because of this line: [(ngModel)]="answer.good". But the problem is that without this line i can't determine if the answers are good or bad.

answer.component.html :

<div class="" *ngFor="let answer of answers">
    <div class="answer">
        <label class="container"> 

            <input type="checkbox" 
                [(ngModel)]="answer.good" />
            
            <span class="checkmark"></span>

        </label>
    </div>
</div>

Does someone has a solution ?




mardi 30 octobre 2018

Show the content based on unique selection or with different combination of checkboxes (ej. more than 2)

I need to show the corresponding image according to the checkbox controls selection, it works at the moment of selecting a box and showing its respective content, but if I remove the selection from some of them it doesn't work anymore.

   $(".checkboxmark").change(function(){    
      var val=''; 
     if($(this).is(':checked')) {

    $.each($('.checkboxmark:checked'), function(i) {
        val += '#' + $(this).attr('id');        
    });

    switch (val) {
        case '#nationals#usa_canada#latinoamerica':
            $(".div5").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        case '#nationals':
            $(".div1").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        case '#usa_canada':
            $(".div2").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        case '#latinoamerica':
            $(".div3").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        case '#nationals#usa_canada':
            $(".div6").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        case '#nationals#latinoamerica':
            $(".div7").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
         case '#usa_canada#latinoamerica':
            $(".div8").fadeIn(400).siblings('.imgMap').fadeOut(200);
            break;
        default:
            $(".div4").fadeIn(400);
            break;
    }
 } 
}); 

Example:

If I check any unique box, or any combination of boxes shows me correctly the result of the individual selection or the according combination, but if I uncheck or remove any selection there stops working and it doesn't show me the supposed active selection, or the default selection when nothing are selected.

I have my working fiddle in this url: https://jsfiddle.net/alonsoct/9koqe4fr/

Thank you for your help!




Dynamic checkbox filter angular js manipulate the filtered items

I want to maipulate the filtered items which we get in checkbox filter. For example if i select Red-- It should show

Value:10(5+5) Apple,Strawberry

Kindly help?

'use strict'

angular.module('fruit', []);

function FruitCtrl($scope) {
    $scope.fruit = [
        {'name': 'Apple', 'colour': 'Red','value':5},
         {'name': 'Strawberry', 'colour': 'Red','value':5},
        {'name': 'Orange', 'colour': 'Orange','value':5},
        {'name': 'Orange1', 'colour': 'Orange','value':5},
        {'name': 'Banana', 'colour': 'Yellow','value':5},
          {'name': 'Banana1', 'colour': 'Yellow','value':5}];
    
    $scope.colourIncludes = [];
    
    $scope.includeColour = function(colour) {
        var i = $.inArray(colour, $scope.colourIncludes);
        if (i > -1) {
            $scope.colourIncludes.splice(i, 1);
        } else {
            $scope.colourIncludes.push(colour);
        }
    }
    
    $scope.colourFilter = function(fruit) {
        if ($scope.colourIncludes.length > 0) {
            if ($.inArray(fruit.colour, $scope.colourIncludes) < 0)
                return;
        }
        
        return fruit;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="fruit">
    <div ng-controller="FruitCtrl">
        
        <input type="checkbox" ng-click="includeColour('Red')"/> Red</br/>
        <input type="checkbox" ng-click="includeColour('Orange')"/> Orange</br/>
        <input type="checkbox" ng-click="includeColour('Yellow')"/> Yellow</br/>
        
        <ul>
            <li ng-repeat="f in fruit | filter:colourFilter">
                
            </li>
        </ul>

        Filter dump: 
    </div>
</div>
Is there any way to do this? If there let me know..

Thanks in advance




custom checkbox and label align on checkout magento2

I have created a custom checkbox in checkout. checkbox and label is not aligned My code for checkbox is

addressFieldset['custom_checkbox'] = [
        'component' => 'Vendor_Module/js/single-checkbox',
        'config' => [
            'customScope' => $dataScope,
            'template' => 'ui/form/field',
            'prefer' => 'checkbox'
        ],
        'dataScope' => $dataScope . '.custom_checkbox',
        'deps' => $deps,
        'label' => __('checkbox label'),
        'provider' => 'checkoutProvider',
        'visible' => true,
        'checked' => true,
        'initialValue' => false,
        'sortOrder' => 60,
        'valueMap' => [
            'true' => true,
            'false' => false
        ]
    ];


[![enter image description here][1]][1]

I want to lign it like enter image description here

enter image description here




Yii2: Show field/checkbox after checkbox is selected

I have an ActiveForm in my _form view:

<?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'isInternal')->checkbox() ?> <?php ActiveForm::end(); ?>

('isInternal' is a boolean)

If the checkbox is selected I want to show another checkbox:

$form->field($model, 'activateReminder')->checkbox();

Is there a possibility? Maybe with JavaScript like this?

 <?= $form->field($model, 'isInternal')->checkbox(['onclick' =>
 'showInternDetails()']) ?> 

<script>
 function showInternDetails() {
 $model->isInternal = 1;
 } 
</script>

<?php 
if($model->isInternal == true)
{
$form->field($model, 'activateReminder')->checkbox();
}
?>




QML CheckBox set text size

Is there a way to set size of text used in checkbox?

I have following code:

CheckBox {
    text: qsTr("Use Delays")
    checked: false
    anchors.horizontalCenter: parent.horizontalCenter
    onCheckedChanged:
    {
        middle.useDelays = checked
    }

}

Thanks a lot!




Show/Hide checkbox based on onLoad properties

I have a check box:

   <tr><td class="form-row" colspan="2" style="font-weight:bold; font-size:10px; color: #006699;"> <a href="javascript:void(0);"></a>
        <label> Display Value</label>
            <input type="checkbox" name="Display"  id="Display" />
    </td></tr>

Based on the onload function, i need to show/hide the checkbox completely.

        window.onload = function (e) {
        var dateOfToday = getCurrentDay();
        var presentDate = document.getElementById("presentDate");
       if (presentDate) {
            presentDate.value = dateOfToday;
        }
        var datetiMe = "<%= session.getAttribute("PresetValEndDate")%>";
        var setPVInput = formatDate(datetiMe);

        if (setPVInput > dateOfToday || setPVInput == dateOfToday){
            document.getElementById("myFieldset").disabled = false;
            //hidecheckbox

        }
        else(setPVInput < dateOfToday)
        {
            document.getElementById("myFieldset").disabled = true;
            //show checkbox

        }
    }

I tried the following but it didn't work.

 document.getElementById("Display").disabled = false;

Any help is appreciated. Thank you.




Office UI Fabric, Checkbox component, override default ID

How can I override the default ID for Checkbox component from Office UI Fabric package, I tried passing it as a prop to <Checkbox /> but it still renders with default ID which goes something like checkbox-XX where XX represents random integer number.

Here is how it currently looks:

<Checkbox label={obj.Title} onChange={(e) => this.handleOnChange(e as React.FormEvent<HTMLInputElement>)} className="checkbox-email-recipient unchecked" id={obj.Title} />

Note that I tried using Title as the ID for Checkbox.

How can I override this default ID ?




How To implement User checkbox checked and show multiple TextBox

I Have A CheckBox And Multipe TextBox

    @Html.CheckBox("myCheck", new { @onclick = "myFunction()" })

I have Script

<script>
 function myFunction() {
 // Get the checkbox
 var checkBox = document.getElementById("myCheck");

 // Get the output TextBox
 var text = document.getElementById("t1");
 var text = document.getElementById("t2");
 var text = document.getElementById("t3");

 // If the checkbox is checked, display the output TextBox
 if (checkBox.checked == true){
 text.style.display = "block";
 } else {
 text.style.display = "none";
 }
 }
</script>

if user click on the checkbox as well as all the text box shows if user click unchecked checkbox then hide all TextBox

@Html.TextBox("t1",null,new{@class="form-control", hidden})
@Html.TextBox("t2",null,new{@class="form-control", hidden})
@Html.TextBox("t3",null,new{@class="form-control", @rows="10", hidden})

How do i implement please help me i am new in mvc




lundi 29 octobre 2018

Properly change Font Style simultaneously

enter image description here

How do I properly change the Font Style of the text without using a lot of if / else if conditions when checking multiple checkboxes?

PS. I know what to use when having multiple styles in one text but I d not want a long if/else conditions to achieve it.




Write and Read Checkbox status to/of file with php

I am trying to save the status of my checkbox whether it is true or false (checked/unchecked) to a file. I managed to write the checkbox value to a file but I have no idea if this is even the right way to do it and I also don't know how to load it again. I want that my checkbox status of the last time is "remembered" by reloading the page. Using local storage isn't a option for me sadly.....

here my code:

<form action="database.php" method="post">
<input type="hidden" name="check2" value="0" /> 
<input type="checkbox" name="check2" value="1" /> 

<input type="submit"  value="senden" />
</form>



<?php

$handle = fopen("saver.json", "a");

$fh = fopen( 'saver.json', 'w' );
fclose($fh);  
  
 foreach($_POST as $value) {
  fwrite ($handle, $value);

 }
 
 fclose($handle);

?>

so this first deletes the old saved value and then writes a 1 or a 0 in the file. Am I on a good way or do I think too simple?

All help is highly apprecciated ! Thanks a lot




How to write correct XPath or CSS?

My HTML is:

  <div tabindex="-1" role="gridcell" comp-id="376" col-id="0" class="ag-cell ag-cell-not-inline-editing ag-cell-with-height ag-cell-focus ag-cell-range-selected ag-cell-range-selected-1" style="width: 77px; left: 0px;">
    <span ref="eCellWrapper" class="ag-cell-wrapper">
      <span class="ag-selection-checkbox">
        <span class="ag-icon ag-icon-checkbox-checked"></span>
        <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
        <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
      </span>
      <span ref="eCellValue" class="ag-cell-value"></span>
    </span>
  </div>
  <span ref="eCellWrapper" class="ag-cell-wrapper">
    <span class="ag-selection-checkbox">
      <span class="ag-icon ag-icon-checkbox-checked"></span>
      <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
      <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
    </span>
    <span ref="eCellValue" class="ag-cell-value"></span>
  </span>
  <span class="ag-icon ag-icon-checkbox-checked"></span>
  <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
  <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
  <span class="ag-selection-checkbox">
    <span class="ag-icon ag-icon-checkbox-checked"></span>
    <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
    <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
  </span>
  <span ref="eCellValue" class="ag-cell-value"></span>
  <span ref="eCellWrapper" class="ag-cell-wrapper">
    <span class="ag-selection-checkbox">
      <span class="ag-icon ag-icon-checkbox-checked"></span>
      <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
      <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
    </span><span ref="eCellValue" class="ag-cell-value"></span>
  </span>

How to write correct identifier for clicking checkbox.I have row with informations, that row has checkbox I need to click to that checkbox.

This is my XPath?

var checkbox= element(by.css('div.ag-body-container>div[row id="0"]>div[col-id="0"]'));
browser.wait(ExpectedConditions.elementToBeClickable(checkbox), 5000);
checkbox.click();

It is pass, but it did not click right checkbox.It is just highlighted whole row.

My HTML:

  <div tabindex="-1" role="gridcell" comp-id="376" col-id="0" class="ag-cell ag-cell-not-inline-editing ag-cell-with-height ag-cell-focus ag-cell-range-selected ag-cell-range-selected-1" style="width: 77px; left: 0px;"><span ref="eCellWrapper" class="ag-cell-wrapper"><span class="ag-selection-checkbox"><span class="ag-icon ag-icon-checkbox-checked"></span><span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span><span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span></span><span ref="eCellValue" class="ag-cell-value"></span></span></div>
  <span ref="eCellWrapper" class="ag-cell-wrapper">
    <span class="ag-selection-checkbox">
      <span class="ag-icon ag-icon-checkbox-checked"></span>
      <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
      <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
    </span>
    <span ref="eCellValue" class="ag-cell-value"></span>
  </span>
  <span class="ag-icon ag-icon-checkbox-checked"></span>

  <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
  <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
  <span class="ag-selection-checkbox">
    <span class="ag-icon ag-icon-checkbox-checked"></span>
    <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
    <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
  </span>
  <span ref="eCellValue" class="ag-cell-value"></span>
  <span ref="eCellWrapper" class="ag-cell-wrapper">
    <span class="ag-selection-checkbox">
      <span class="ag-icon ag-icon-checkbox-checked"></span>
      <span class="ag-icon ag-icon-checkbox-unchecked ag-hidden"></span>
      <span class="ag-icon ag-icon-checkbox-indeterminate ag-hidden"></span>
    </span>
    <span ref="eCellValue" class="ag-cell-value"></span>
  </span>




Set a checkbox as 'checked' when an if condition is fulfilled in php

I want to mark a checkbox as 'checked' automatically when an if condition is fulfilled. Here is an example of the if condition-

if($wp_session['tdwa_verification_checks'] < 2){

}

And the checkbox is-

<input class="input-text a-save" type="checkbox" id="chkboxclicked" name="tdwa-foreign-citizen" value="1">

I am trying with this but its not working.

if($wp_session['tdwa_verification_checks'] < 2){

    echo '<input class="input-text a-save" type="checkbox" id="chkboxclicked" name="tdwa-foreign-citizen" value="1" checked>'; 

}

I would appreciate if anyone can give me a clue. Thanks :)




checkbox on off is not working on chrome extension?

My default checkbox is checked, when i click the to uncheck it, is not working, just set the button off but is not working and after i close the popup and when i see again the buton is still on so is checked, how i can fix this problem? do i have some error on this script?

popup.html

<html>
    <head>>

    <link rel='stylesheet' href="css/popup.css"/>
    <script type="text/javascript" src="js/popup.js"></script>
    </head>
    <body>
    <div style="padding: 10px;">
    <div style="float:left;"> Players </div>
    <div class="flipswitch">
    <input type="checkbox" name="flipswitch" class="flipswitch-cb cbox" id="fs"  checked>
    <label class="flipswitch-label" for="fs">
        <div class="flipswitch-inner"></div>
        <div class="flipswitch-switch"></div>
    </label>
    </div>
    </div>
    </body>
</html>

popup.js

window.onload = function() {
    if (window.location.href.match('chrome-extension://')) {
        load();
    }
}

$("body").on("change", ".cbox", function() {
    var status = "";
    $(".cbox").each(function() {
        status = status + ($(this).is(":checked")) + ",";
    });

    save_option(status);
});

function save_option(option) {
    var save = {};
    save[option] = null;
    chrome.storage.sync.set({
        option : option
    }, function() {
        console.log(option + "saved");
    });
}

function load() {
    chrome.storage.sync.get(null, function(obj) {
        console.log(obj);
        if (obj.hasOwnProperty("option")) {
            tab = obj.option.split(",");

            console.log(tab);
            var l = 0;
            $(".cbox").each(function() {
                $(".cbox:eq(" + l + ")").attr("checked", parseBoolean(tab[l]));
                l++;
            });
        } else {
        save_option("true");
        }
    });

}

function parseBoolean(str) {
    return /true/i.test(str);
}

manifest.json

"name":"test",
"description":"test",
"version":"1.1.1",
"manifest_version":2,
"icons": { 
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
},
"browser_action": {
    "default_title": "name",
    "default_popup": "popup.html",
    "default_icon": "icons/icon128.png"
},
"background": {
    "scripts": ["js/background.js"],
    "persistent": true
},
"content_scripts": [
    {
    "js": ["js/content.js", "js/jquery.js"],
    "matches": ["<all_urls>"],
    "run_at": "document_end",

    "all_frames": true  
  }
],
"applications": {
"gecko": {
    "id": "{3b5e61ae-bda1-46c5-89bb-5085cc5ee9c}",
    "strict_min_version": "57.0"
        }
    }, 
"content_security_policy": "script-src 'self'",
"permissions": [
    "webRequestBlocking",
    "unlimitedStorage",
    "webNavigation",
    "<all_urls>",
    "webRequest",
    "activeTab",
    "downloads",
    "topSites",
    "storage",
    "cookies",
    "tabs"
   ]
}




Three state checkbox with angular 2

I want to do an input box with three states: checked, unchecked and crossed(a.k.a failed) Currently, I was able to do check/uncheck and change calculations accordingly

 <input type="checkbox" [ngStyle]="{content: expression}" *ngIf="milestone?.description" [checked]="milestone?.status == 'checked'"
                    (change)="checkMilestone(milestone,initiative, $event, '')">

However, I have trouble adding crossed (X) checkbox. Does anyone have idea how it should be done? Should I have states something like this:

  states = [
{ id: 0, status: 'checked'},
{ id: 1, status: 'unchecked'},
{ id: 2, status: 'crossed'}

];

and add styles and change them accordingly? I'm not sure how to add three styles instead of two.




Autocheck all checkboxes within dynamic html div

So basically i want to check all the check-boxes within a html div if the "parent checkbox" for that div is checked. I'm new at javascript/php/html. can anyone provide an useful explanatory example?

Here's my code:

    <form>
  <?php
    while(list($k, $v)=each($Aff))
    {
    if ($k == 0)
    {
      array_push($parentAff, substr($v, 0, 2));
      $substring = $v;
      echo ('<div id ="Div'.$v.'">');
    }
    if ((substr($substring, 0, 2) != substr($v, 0, 2)) && (strlen($substring) != 1))
    {
      echo ('</div>');
      echo ('<div id ="'.$v.'">');
      array_push($parentAff, substr($v, 0, 2));
      $counter++;
      $substring = $v;
      echo "<hr>";
    }

    echo ('<input type="checkbox" name="Aff[]" id="'.$v.'" value="'.$v.'" /><label for="text'.$k.'">'.$v.'</label>');


    $substring = $v;

    }

    echo ('</div>');

  ?>
</form>

The number of checkboxes within a div depend on what data comes out of the database to the array Aff[]. the parent checkbox for each div would be the one in the parentAff array wich is identified by the div id.




BaseExpandableListAdapter rewrites new items over the old items

I am using BaseExpandableListAdapter to show titles with children. The children can be a Checkbox or a radiobutton, it depends of the parent of each one, so you can have a group which are radiobuttons or a group which are checkboxes.

The problem is that when I'm scrolling, the items are been override bad, and you can see the old element behind the new one. I have tried to use getChildId and getGroupId with autoincrements uniques ID, to use getCombinedGroupId and getCombinedChildId, I have set the hasStableIds true and false. But it still hapenning.

This is a piece of my Adapter class:

private Context context;
private ArrayList<Mode> parents;
private HashMap<Mode,ArrayList<Mode>> children;
private ArrayList<RadioButton> radioButtonList;
private byte idLang;
private ModeDao modeDao;
private ExpandableListView elOrderDialog;
private TextView title;
private Timer errorTimer;

public NewModesAdapter(Context context, ArrayList<Mode> parents, HashMap<Mode, ArrayList<Mode>> children, byte idLang,ExpandableListView elOrderDialog, TextView title) {
    this.context = context;
    this.parents = parents;
    this.children = children;
    this.idLang = idLang;
    this.modeDao = new ModeDao(context);
    this.elOrderDialog = elOrderDialog;
    this.title = title;
    this.radioButtonList = new ArrayList<>();
    this.errorTimer = new Timer();
}

@Override
public void registerDataSetObserver(DataSetObserver observer) {

}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {

}

@Override
public int getGroupCount() {
    return parents.size();
}

@Override
public int getChildrenCount(int groupPosition) {
    return children.get(parents.get(groupPosition)).size();
}

@Override
public Object getGroup(int groupPosition) {
    return this.parents.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    return this.children.get(this.parents.get(groupPosition))
            .get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
    return this.parents.get(groupPosition).getAutoId();
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return this.children.get(this.parents.get(groupPosition))
            .get(childPosition).getAutoId();
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    Mode currentFilterParent = (Mode) getGroup(groupPosition);
    String headerTitle = currentFilterParent.getTranslationName(idLang);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert inflater != null;
        convertView = inflater.inflate(R.layout.expandable_title, null);
    }

    FrameLayout flTitle = convertView.findViewById(R.id.fl_title);
    flTitle.setBackgroundColor(Color.parseColor(AppData.getColor2(context)));
    final TextView lblListHeader = convertView.findViewById(R.id.ex_tv_title);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setTextColor(Color.parseColor(AppData.getText2(context)));
    lblListHeader.setText(headerTitle);

    flTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //nothing to do
        }
    });

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    CheckBox cbModeItem;
    RadioButton rbModeItem;
    final Mode currentChild = (Mode) getChild(groupPosition, childPosition);
    Mode currentParent = modeDao.getModeById(currentChild.getIdFather());

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert inflater != null;
        convertView = inflater.inflate(R.layout.expandable_mode_item, null);
    }

    if (currentParent.getMultiOption() == 0) {
        rbModeItem = convertView.findViewById(R.id.rb_mode_item);
        rbModeItem.setText(currentChild.getTranslationName(idLang));
        rbModeItem.setTextColor(Color.parseColor(AppData.getText1(context)));
        rbModeItem.setVisibility(View.VISIBLE);
        setRBOnClick(rbModeItem, currentChild);
        radioButtonList.add(rbModeItem);
    } else {
        cbModeItem = convertView.findViewById(R.id.cb_mode_item);
        cbModeItem.setText(currentChild.getTranslationName(idLang));
        cbModeItem.setTextColor(Color.parseColor(AppData.getText1(context)));
        cbModeItem.setVisibility(View.VISIBLE);
        cbModeItem.setChecked(currentChild.isChecked());
        setCBOnClick(cbModeItem,currentChild);
    }

    return convertView;
}

Thank you in advance.




Index of checked/unchecked checkbox in listview

I am trying to modify XML file based on a value (true/false) of checked checkbox in listview, so I need index of a used checkbox. Problem is whenever I check or uncheck a checkbox I get the same result when using ListView.FocusedItem.Index because when clicking on a checkbox item is not selected.

Is it possible to get index of a currently used checkbox in a listview?




Check checkbox on clicking a div, but not on an image

I would like a checkbox to be checked on clicking anywhere on a parent div, but not if the user click on the camera image included in that div. How to "exclude" that div ?

HTML

<label for="checkbox_296501" class="label-for-check">
   <div class="colorChange">
      <div>
         Title          
         <div style="float: right">
            <input type="checkbox" id="checkbox_296501" name="Box[]" value="296501" style="/*display: none*/" >
         </div>
      </div>

      <div style="float: left; padding: 6px 6px 0 0">
         <img class="photo_dispo" src="https://cdn.icon-icons.com/icons2/510/PNG/512/camera_icon-icons.com_50440.png" data-no="296501" style="width: 30px; cursor: zoom-in">
      </div>

      <p style="clear: both; margin-bottom: 0">
         Pellentesque sit amet placerat magna. Vestibulum diam quam, vestibulum vel eros vitae, rhoncus aliquet diam. Sed tortor risus, varius interdum ornare non, sagittis eu neque. Nunc vulputate nunc lorem, at rhoncus nisi eleifend a.
      </p>

      <div>
         <div>
            Left column
         </div>
         <div style="float: right">
            Right column
         </div>
      </div>
   </div>
</label>

Javascript

jQuery(function($) {
   $("input:checkbox").on("change", function() {
      $(this).closest(".colorChange").toggleClass("checked_bg", $(this).prop("checked"));
   });
});

Working example http://jsfiddle.net/uw7gk03p/1/




dimanche 28 octobre 2018

Get column number of checkbox on change

I'm trying to get the table column number of a checkbox when selected

Below is the code I have been trying, but it returns 0. How would be best to do this?

 $(document).on('change', '.select_all_checkbox', function() {
        var columnNo = $(this).index();
        alert(columnNo);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



if checkbox is checked press enter to trigger button click

I have a form which shows 1 question at a time and i have to click next in order to go to the next question. The user have to select one option to move to the other questions. I want to do is if the user selects a option from the checkbox and press enter it will trigger the next button and move to the other questions. i cant possibly do it. what is wrong with my code? jquery code..

$('input[name="trading_for_at_least_6_months"]:checked').keypress(function (event) {
if (event.keyCode === 13) {
    $(".comnext1").click();
}});

I am trying to code is to see if any of the options is checked by checking the input names and if it is, when enter key is pressed trigger next button. I have other next button so i dont want to trigger them too.




Android - How do I save the state of my ImageView boolean value of a ListView Item List?

It's my first time trying to make an App that is basically a checklist that helps me keep track of i.e. collected items. Much like a checklist in a game. I am veeeeery inexperienced with Android so I found some template that I modified for my own need. I'm basically using two .png files (checked and unchecked box) as ImageView which upon clicking change into one another, thus imitating a basic checkbox. Aparently this method worked best for me, even though I thought a normal checkbox object would be easier. When i used regular checkbox objects the status of 'checked' moved throughout the list... And with this ImageView method the checked boxes remained the same as the ones I really checked.

So I figured how to generate a List. Later on I will manually change the list to the Items/Names/etc. as I want that won't be a problem. The App also manages to let me select multiple Items and the items remain checked even after its onPause. The problem I face now is that upon distroying the app on the device and on restarting the app, all the checked Items are now unchecked. That means that the information that the item was check was not stored at all.

I would be so happy if someone can help me with completing the code... I have no idea how to store the information of which Item in List was checked and let alone be reloaded upon onCreate.

Here is activity_main.xml, which is basically the ListView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="15dp"
    android:paddingTop="15dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    tools:context="com.multiselect.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listview"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="2dp"/>

</RelativeLayout>

Next up is the list_view_item.xml where the Name, Subtitle and Checkbox ImageView are declared.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="60dp">

//NAME//
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv_user_name"
    android:gravity="center_vertical"
    android:layout_toEndOf="@+id/iv_check_box"
    android:paddingStart="10dp"
    android:textAppearance="?android:attr/textAppearanceLarge" />

//SUB
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv_user_sub"
    android:layout_alignStart="@+id/tv_user_name"
    android:layout_below="@+id/tv_user_name"
    android:paddingStart="10dp"
    android:textColor="@color/sub"
    android:textAppearance="?android:attr/textAppearanceMedium"
    tools:ignore="RtlSymmetry" />

//Checkbox
<ImageView
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:id="@+id/iv_check_box"
    android:layout_alignParentStart="true"
    android:onClick="onCheckboxClicked"
    android:layout_centerVertical="true"
    android:background="@drawable/check"/>

</RelativeLayout>

So then I have a basic UserModel.java with all the Getters and Setters.

package com.multiselect;

public class UserModel {

    private boolean isSelected;
    private String userName;
    private String userSub;

    //create constructor and getter setter


    public UserModel(boolean isSelected, String userName, String userSub) {
        this.isSelected = isSelected;
        this.userName = userName;
        this.userSub = userSub;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSub() {
        return userSub;
    }

    public void setUserSub(String userSub) {
        this.userSub = userSub;
    }
}

Then I know I need an CustomAdapter.java for what I wanna do. I have a ViewHolder inside together with an updater for the checle items.

    package com.multiselect;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;   
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends BaseAdapter {

    Activity activity;
    List<UserModel> users;
    LayoutInflater inflater;


    //short to create constructer using alt+insert or rightclick - generate - constructor

    public CustomAdapter(Activity activity) {
        this.activity = activity;
    }

    public CustomAdapter(Activity activity, List<UserModel> users) {
        this.activity = activity;
        this.users = users;

        inflater = activity.getLayoutInflater();
    }

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

    @Override
    public Object getItem(int i) {
        return i;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;

        if(view == null){
            view = inflater.inflate(R.layout.list_view_item, viewGroup, false);
            holder = new ViewHolder();

            holder.tvUserName = (TextView)view.findViewById(R.id.tv_user_name);
            holder.tvUserSub = (TextView)view.findViewById(R.id.tv_user_sub);
            holder.ivCheckBox = (ImageView) view.findViewById(R.id.iv_check_box);

            view.setTag(holder);
        }else
            holder = (ViewHolder) view.getTag();

        UserModel model = users.get(i);

        holder.tvUserName.setText(model.getUserName());
        holder.tvUserSub.setText(model.getUserSub());

        if (model.isSelected()) {
                holder.ivCheckBox.setBackgroundResource(R.drawable.checked);
        }
        else
                holder.ivCheckBox.setBackgroundResource(R.drawable.check);

        return view;
    }

    public void updateRecords(List<UserModel> users) {
        this.users = users;

        notifyDataSetChanged();

    }

    class ViewHolder{

        TextView tvUserName;
        TextView tvUserSub;
        ImageView ivCheckBox;


    }
}

...And MainActivity.java:

package com.multiselect;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.content.SharedPreferences;
import android.widget.Toast;

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

public class MainActivity extends Activity {


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

        ListView listView = (ListView) findViewById(R.id.listview);

        final List<UserModel> users = new ArrayList<>();

        for(int i = 0; i<20; i++) {
            users.add(new UserModel(false, "Name "+(i), "Subtitle " + (i)));
        }


        final CustomAdapter adapter = new CustomAdapter(this, users);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                UserModel model = users.get(i);


                if (model.isSelected())
                    model.setSelected(false);

                else
                    model.setSelected(true);

                users.set(i, model);

                //now update adapter
                adapter.updateRecords(users);


            }

        });

    }

}

And now I know I should use SharedPreferences in the MainActivity.java but I don't know how in this specific example... Especially when I try it out with what other people said the app just crashes either as soon as I check something or when I just try to Run the app. I'm literally not good enough for this and I really want to know how something I normally take for granted (that an app remembers whats been don in it) is done programmatically.

I hope that someone can complete my Code so that the app remembers which box was checked and reloads that upon onCreate...




samedi 27 octobre 2018

PyQT Fusion style removes checkboxes in checkable combobox

I created a checkable qcombobox using the following code. Then, I applied the fusion style to make my program look better. However, doing so results in the checkboxes next to the items in my code to no longer be visible. How can I fix that?

class WindowGUI(QMainWindow):
    def __init__(self, gui):
        super().__init__()
        self.initUI(gui)

    def initUI(self, gui):
        self.teacherSelect = TeacherSelect()

        self.setCentralWidget(self.teacherSelect)


class TeacherSelect(QComboBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.initModel()
        self.addTeachers()

    def initModel(self):
        self.number = 1
        self.selecteds = []
        self.teacherDataWids = []

        self.view().pressed.connect(self.select)

    def addTeachers(self):
        self.source = {"id1" : "a", "id2" : "b"}
        self.number = 0
        for teacherID in self.source.keys():
            self.addItem(self.source[teacherID])
            teacherItem = self.model().item(self.number)
            teacherItem.setData(teacherID)
            teacherItem.setCheckState(Qt.Unchecked)
            self.number += 1

    def select(self, index):
        pass

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setStyle("fusion")

    windowGUI = WindowGUI()
    windowGUI.show()    

    sys.exit(app.exec_())




JS: Setting checked to true is not working

Trying to set a Checkbox via addEventListener in JS, I already tried with

element.checked = true;
element.setAttribute('checked', true);
element.setAttribute('checked', "checked");

I can see in the console that my checked is set to true (not sure if the issue is that the boolean value is shown as string "true" or if this is just a chrome representation) but the element is not getting the check mark.

input id="element" class="element" name="element" type="checkbox" value="1" checked="true"

Onload the default checked box is correctly set but when I'm trying to uncheck and set the new one nothing is happening (visually).

Thanks for any help.




Other checkboxes in different rows are checked when a checkbox is checked

I have a grid and each row (300 of them) consists of "string | string | int | string | check." If for example I click on the checkbox in row 7, nothing out of the ordinary happens. But if I click another checkbox on another row, I may get 10 other rows with their checkboxes checked, but these other checkboxes arent executing the code associated with them.

            <DataGridTemplateColumn Width="*" Header="Add">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>                           
                        <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>




vendredi 26 octobre 2018

wpf DataGridTemplateColumn.CellTemplate how to enable/disable checkboxes

I have a DataGrid with DataGridTemplateColumn.CellTemplate defined like this :

<DataGridTemplateColumn>
     <DataGridTemplateColumn.Header>
          <CheckBox ToolTip="Select all items" 
            IsChecked="{Binding IsSelected}" Name="chkSelectAll" Checked="AllItem_Checked"
            Unchecked="UnCheckAll_UnChecked" IsHitTestVisible="{Binding Path=IsSelected}"/>
     </DataGridTemplateColumn.Header>
     <DataGridTemplateColumn.CellTemplate>                                        
        <DataTemplate>
             <CheckBox HorizontalAlignment="Center" Checked="Item_Checked" Unchecked="Item_UnChecked"
                IsChecked="{Binding IsSelected}" IsHitTestVisible="{Binding Path=IsSelected}" />                                        
       </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The grid has a binding with a list of objects.

I want that, for each object of ItemsSource, if IsSelected attribut is TRUE the CHECKBOX BECOME IsReadOnly (can't be checked or uncheck.

I don't know how to perform this; I tried Binding IsHitTestVisible property to IsSelected ItemsSource Objects attribut but it's not working.

I googled about and found some topics about Multidatatriggers but can't understand how it's work.

Can someone help me ? I'm new with WPF.

Thank you.




Check a range of checkboxes on a gridview in asp.net

I have a page with a gridview that has a checkbox column.

I also have a range selector (two drop-down-lists) that contain a start number and an end number - these numbers represent all the rows in the gridview.

I want to be able to "check" all the checkboxes in the gridview based upon the range selected in the two drop-down lists.

I have found methods that check all the boxes but not a range.

Does anybody know of how best to do this?

Thanks




React Checkbox state gives opposite value

Here is my Checkbox component, at this point I'm trying to check if the returned state is correct, that when it's checked, it returns 'true' and the other way around.

For now, when I check it, it returns 'false'. When I uncheck, it says 'true'.

I don't quite understand what I'm doing wrong here, the code seems to make sense to me like this. Is it just my console.log that is throwing me off?

export default class Checkbox extends PureComponent {
  constructor() {
    super();
    this.state = {
      checked: false
    };
  }

  handleCheckClick = () => {
    this.setState(prevState => ({
      checked: !prevState.checked
    }));
    console.log(this.state);
  };

  render() {
    const { answer, value } = this.props;
    return (
      <div className="form">
        <div className="form__answer">
          <FormGroup check>
            <Label check>
              <Input
                type="checkbox"
                name="check"
                checked={this.state.checked}
                onChange={this.handleCheckClick}
                value={value}
              />
              {answer}
              <span className="checkmark" />
            </Label>
          </FormGroup>
        </div>
      </div>
    );
  }
}




jeudi 25 octobre 2018

Angular 5 checkbox checked default but its not triggering the change event [duplicate]

This question already has an answer here:

I have a list of checkboxes and some checkboxes or default checked, when if it's checked I would like to call the change event but it's not working as expected. The code as below

 <tr *ngFor="let permission of permissions[key]; let i = index">
<td></td>
<td>
    <span class="m-switch m-switch--primary">
        <label>
            <input type="checkbox" 
                 name="check-box-"
                 [value]="permission.id" 
                 [checked]="isChecked(permission.id)"
                 (change)="updatePermission($event,permission, key)"
                 attr.id="check-box-">
            <span></span>
        </label>
    </span>
</td>

 public updatePermission(event: any, permission: any, key: any){
        console.log(event);
    }

Anyone please help




How to read a checkbox value of a pdf single page file in python?

i have tried PyPDF2 but there is no class defined to extract checkbox values.

import PyPDF2

pdfFileObj = open('C:\Source Files\Fillable_PDF_Sample_from.pdf', 'rb')

pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

print(pdfReader.numPages)

pageObj = pdfReader.getPage(0)

print(pageObj.extractText())

pdfFileObj.close()




Binding checkboxes directly to a ngModel's list of ids

I have a model which contains a list of ids. I have a set of checkboxes whose values are ids. I want to bind them together directly, but all I've managed to do is to manually hook into the [checked] and (change) attributes which seems like more work than I should be doing. (That is, lower-level interfacing between a model and the component for functionality which is so basic that it seems like it should already be supported out-of-the-box.)

The model:

export class Product {
  id: number;
  name: string;
}
export class MyModel {
  products: number[];
  // plus other unrelated stuff of course
}

Then in my component, I have a series of checkboxes (I'm using mat-checkbox, but that shouldn't matter), where the display value is the product name, and the value is the id.

<mat-checkbox *ngFor="let product of products"
              [value]="product.id"></mat-checkbox>

What I'm trying to do, is to to populate the products array in the model with the collection of selected checkboxes values. Eg if products 1,3,5 are checked, the model's products array would be [1,3,5].

I know I can get this working if I bind [checked] to a function that looks to see if the model's array contains the id, and the (change) event to a function that pushes the value to the array. For example:

<mat-checkbox *ngFor="let product of products"
  [value]="product.id"
  (change)="$event.checked ? model.products.push(product.id) : model.products.splice(model.products.indexOf(product.id),1)"
  [checked]="model.products.includes(product.id)"></mat-checkbox>

But this is pretty nasty, especially that change event. Is it possible to simply bind the component directly to the ngModel itself? Some syntax I'm possibly not aware of?

The list of products




Get input type checkbox values in one array in required format

I am trying to get values from checkboxes in the following format of an array. Maybe this is the simple problem for you guys but I am really stuck here.

This is my input types

<input type="checkbox" id="any" name="chk" value="value1">
<input type="checkbox" id="any1" name="chk" value="value2">
<input type="checkbox" id="any2" name="chk" value="value3">
<input type="checkbox" id="any3" name="chk" value="value4">
<input type="checkbox" id="any4" name="chk" value="value5">

jQuery code

var fuelType =new Array();
  $.each($("input[name='chk']:checked"), function(){
    console.log($(this).val())
    fuelType.push($(this).val());
});
fuelType = fuelType.join(",");
console.log(fuelType);

I am getting following log

["value1,value2,value3",value4",value5"]

Required response

["value1","value2,"value3","value4","value5"]




Checking/Unchecking check box array with jQuery

I have a HTML form with check boxes of seasons, and set of buttons of seasons. I want jQuery to select check boxes when I click on the buttons. For example when I click on the Winter button it should check the Dec,Jan, Feb check boxes. Somehow my code does not seems to work.

$("#btnWinter").click(function() {
  $("#season[0]").prop('checked', true);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Season <label><input type="checkbox" id="season[]" name="season[]" value="January"> January </label>
<label><input type="checkbox" id="season[]" name="season[]" value="February"> February </label>
<label><input type="checkbox" id="season[]" name="season[]" value="March"> March </label>
<label><input type="checkbox" id="season[]" name="season[]" value="April"> April </label>
<label><input type="checkbox" id="season[]" name="season[]" value="May"> May </label>
<label><input type="checkbox" id="season[]" name="season[]" value="June"> June </label><br/>
<label><input type="checkbox" id="season[]" name="season[]" value="July"> July </label>
<label><input type="checkbox" id="season[]" name="season[]" value="August"> August </label>
<label><input type="checkbox" id="season[]" name="season[]" value="September"> September </label>
<label><input type="checkbox" id="season[]" name="season[]" value="October"> October </label>
<label><input type="checkbox" id="season[]" name="season[]" value="November"> November </label>
<label><input type="checkbox" id="season[]" name="season[]" value="December"> December      </label><br/>

<input type="button" id="btnWinter" name="btnWinter" value="Winter" />



Output javascript value in php based on radio buttons

I would like to output javascript value in a php code. It seems easy but the javascript variables must be based on the answers of a form of the document.

For exemple : If first radio button is checked, outputs first value in php code If second radio button is checked, output second value in php code.

<div class="test">
           <div>
            <input type="radio" id="troismois"
                   name="testradio" value="troismois" checked />
            <label for="troismois">3 mois</label>
        </div>

        <div>
            <input type="radio" id="unmois"
                   name="testradio" value="unmois" />
            <label for="unmois">1 mois</label>
        </div>
<script> 
    var checkBox = document.getElementById("huey");

     if (checkBox.checked == true){
   var x = "10";
  } else {
    var x = "20";
  } 
</script>
<?php 
$content = "<script> document.write(x) </script>";

echo $content;
?>

But it's working, I miss something but I don't know what, maybe someone can help me?

Thank you !




Invoke service method if checkbox is pressed

I have few services and I want to call their methods in my controller if proper checkbox is pressed. E.g. if 3 checkboxes are pressed then it should call a specific method from 3 services in one request.

How should I reach that?

There is an example below:

@Controller
@RequestMapping(value={"invoke"})
public class Controller {

@Autowired
private ServiceOne serviceOne;

@Autowired
private ServiceTwo serviceTwo;

@Autowired
private ServiceThree serviceThree;

@RequestMapping(value = "", method = RequestMethod.GET)
public String show(Model model){
    AllJobsForm allJobsForm = new AllJobsForm();
    model.addAttribute("jobsList", allJobsForm.getJobFormList());
    model.addAttribute("jobForm", new JobForm());
    return "show";
}

@RequestMapping(value = "operation", method = RequestMethod.POST)
public String Export(Model model, AllJobsForm allJobsForm) {
    //serviceOne.doSomething();
    //serviceTwo.doSomething();        
    //serviceThree.doSomething();
    return "redirect:/home";
}

And below my form class with names for checkboxes

public class AllJobsForm {

private List<JobForm> jobFormList = new ArrayList<>();

public AllJobsForm() {
    create();
}

private void create(){
    jobFormList.add(new JobForm("serviceOne"));
    jobFormList.add(new JobForm("serviceTwo"));
    jobFormList.add(new JobForm("serviceThree"));
}

public List<JobForm> getJobFormList() {
    return jobFormList;
}

public void setJobFormList(List<JobForm> jobFormList) {
    this.jobFormList = jobFormList;
}

}

And my html pages

<div layout:fragment="content_container">
<form action="#"  class="form-static" th:action="/invoke/operation" method="post">
    <div class="form-static-body">
        <th:block th:replace="templates/jobs"></th:block>
    </div>

    <div class="form-static-footer">
        <div class="container-fluid">
            <div class="form-group">
                <button type="submit" name="submit" value="submit" class="btn btn-primary">doOperation</button>
            </div>
        </div>
    </div>
</form>

and jobs.html file

<div class="panel panel-default">
<div class="panel-heading">
    <strong>Lorem Ipsum...</strong>
</div>
<div class="panel-body">
    <p>
        Lorem Ipsum...
    </p>
    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
            <tr th:each="jobForm : ${jobsList}">
                <input type="checkbox" th:field="*{jobsList}" th:value="${jobForm.jobName}"/>
                <label th:text="${jobForm.jobName}"></label>
            </tr>
            </thead>
        </table>
    </div>
</div>

Any help would be appreciated




set checkboxes to checked in view depending on condition

I have list of objects

        AAA.aListofObjects= (from tdrc in db.objectsDB
                                      where tdrc.objectID == id
                           select tdrc).ToList();

one parameter AAA.aListofObjects.check - holds true or false data.

Inside view I render my list using "for" where I have "If" statement to decide whether to check or not the checkbox

            @for (int i = 0; i < Model.aListofObjects.Count; i++)
    {
if(something equals something then I must render checkbox as checked)
{
 @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check)
}
else 
{
render unchecked checkbox
 @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check)
}

    }

Now how can I make them checked in this situation ? @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check, @checked="checked") does not help.




Checkbox cannot check/uncheck in tab

I am trying to put a checkbox in a tab panel on the left side. But the checkbox cannot check or uncheck. Can anyone help me to solve this ? This is my code and the image on what I am trying to do.

<aside class="sm-side">
<div role="tabpanel">
    <ul class="nav nav-pills brand-pills nav-stacked" role="tablist">
      <li role="presentation" class="brand-nav active" >
        <a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">
           <input type="checkbox" id="eq1" >
           <label for="eq1">Resource 1</label>
        </a>
      </li>
      <li role="presentation" class="brand-nav"><a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Resource 2</a></li>
      <li role="presentation" class="brand-nav"><a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Resource 3</a></li>
      <li role="presentation" class="brand-nav"><a href="#tab4" aria-controls="tab4" role="tab" data-toggle="tab">Resource 4</a></li>
     </ul>
</div>
</aside>
<aside>
  <div role="tabpanel" class="tab-pane active" id="tab1">
    <p>Hello1</p>
  </div>
  <div role="tabpanel" class="tab-pane" id="tab2">
      <p>Hello 2</p>
  </div>
  <div role="tabpanel" class="tab-pane" id="tab3">
       <p>Hello 3</p>
  </div>
  <div role="tabpanel" class="tab-pane" id="tab4">
       <p>Hello 4</p>
  </div>
</aside>

Image of what I am trying to do




mercredi 24 octobre 2018

How to make only one checkbox is checkable

As you the code below, my checkbox is like button. I want to make it only one is checkable. For now, Checkbox button change color when is clicked and all buttons are checkable at the same time.

PS. I want to make my checkbox button only is checkable with same effect now(when user click the button

    <div class="col-4">
     <label class="btn btn-primary btn-block">
      <input type="checkbox" name="Categories" value="1" /> check1 </label>`
</div>

     <div class="col-4">
     <label class="btn btn-primary btn-block">
      <input type="checkbox" name="Categories" value="1" /> check1 </label>
</div>

 $('label.btn').on('click','input', function(){
   e.stopPropagation();

   $(this).attr('checked', !$(this).attr('checked'));
   $(e.target).closest('label').toggleClass('btn-flat');
 });

Please help me to solve this simple question. Thank you




js - if checkbox checked, setAttribute readonly in an other input [duplicate]

This question already has an answer here:

I have a checkbox like this

<input type="checkbox" name="checkbox" id="checkbox1" value="true" >

and an input text like this

<input id="textbox1" type="text" value="abc" disable="false">

If the checkbox is checked, I would like to disable the text box dynamically (without having to refresh the page. And of course if the user uncheck the checkbox, to able the textbox.

How can I do that ?




Bootstrap validator shouldn't submit form if checkbox was unchecked by jquery

I use bootstrap validator and it works perfect except 1 part. I have multiple inputs and checkboxes and 1 main checkbox which is "terms acception". I set up this checkbox if "terms acception" checkbox is checked and any checkboxes are changed just unchecked this checkbox and ask for check it by using same bootstrap validator. Now if I check it once and uncheck it by jquery $( "#term_btn" ).prop( "checked", false ); it submit form, which is worng.

I tried to use button status, input require by value and so on... but validator works only if i type something into input or check and uncheck term button by my own.




mardi 23 octobre 2018

Input-event seems not to be available on a vuetify checkbox?

I want to invoke a methode, when the user selects one of the checkboxes which I am rendering via v-for. They all are bound to one variable via v-model. Though the problem is that the input doesn't even seem to be available on v-checkbox. And the following code doesn't do anything:

<template>
    <v-container>
        <v-layout row>
                <v-flex xs12>
                <v-layout justify-center>
                    <v-form ref="form" lazy-validation>
                        <v-checkbox
                        v-for="(answer, index) in questions[actualIndex].answers"
                        :key="index"
                        :ref="'check'+index"
                        :label="answer.answer"
                        :value="answer.answer"
                        v-model="checkbox"
                        @input="onInput()"
                        ></v-checkbox>
                    </v-form>
                </v-layout>
            </v-flex>
            </v-layout>
    </v-container>
</template 

export default {
data() {
    return {
    checkbox: ''
        }
    },
methods: {
onInput() {
        console.log("WORKS");

    }

  }
}

However if I use the @change or @click events instead, it works perfectly. Any ideas, what I am doing wrong?




Selecting multiple check boxes is not working in Puppeteer headless browser

In the below code,I am using headless browser to https://example.com/careers site and select two checkboxes and exctract the resulted data. But the problem here is only the first checkbox (technologycheckbox) is getting selected but other one (locationcheckbox) is not getting selected. Please help

(async () => {
  const browser = await puppeteer.launch({headless:false});
  const page = await browser.newPage();
  await page.setViewport({ width: 1366, height: 768});
  await page.goto('https://example.com/careers' ,{waitUntil: 'networkidle2'});
  await page.waitFor(4000);

    const technologycheckbox = await page.$('#checkbox2idvalue');
    await page.waitFor(2000);
    page.waitForSelector(locationcheckbox);
    await technologycheckbox.click();
    await page.waitFor(15000);
    const locationcheckbox  = await page.$('#checkbox1idvalue');
    await locationcheckbox.click();
    await page.waitFor(9000);



const result = await page.evaluate(() => {


    let data = []; // Create an empty array that will store our data
    let elements = document.querySelectorAll("div>ul> li >div:nth-child(1)"); // Select all Products
    console.log(elements)

    for (var element of elements){ // Loop through each proudct

        let title = element.textContent;
        let url = element.href; // Select the title


        data.push({title, url}); // Push an object with the data onto our array
    }

    return data; // Return our data array

});

});




On Button Click checkbox checked validation in C#

I have a scenario, where I display data in a Gridview. Now what I want is, There are two buttons as Approve and Reject. I want to validate that atleast one checkbox should be checked before clicking on one of the buttons.

Below is my HTML.

<asp:GridView ID="grdDisplayCMMData" runat="server" AutoGenerateColumns="false" Width="100%" ShowHeaderWhenEmpty="true" CssClass="heavyTable table" EmptyDataText="No records to display"
        AllowPaging="true" PageSize="20" OnPageIndexChanging="grdDisplayCMMData_PageIndexChanging">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="Id" ItemStyle-Width="10%" />
            <asp:BoundField DataField="SAP_ID" HeaderText="Sap Id" ItemStyle-Width="10%" />
            <%--<asp:BoundField DataField="ID_OD" HeaderText="ID to OD" ItemStyle-Width="10%" />--%>
            <asp:BoundField DataField="ID_OD_COUNTCHANGE" HeaderText="ID to OD Change" ItemStyle-Width="10%" />
            <asp:BoundField DataField="ID_OD_CHANGEDDATE" HeaderText="ID to OD Change Date" ItemStyle-Width="10%" />
            <asp:BoundField DataField="RRH_COUNTCHANGE" HeaderText="RRH Count Change" ItemStyle-Width="10%" />
            <asp:BoundField DataField="RRH_CHANGEDDATE" HeaderText="RRH Count Change Date" ItemStyle-Width="10%" />
            <asp:BoundField DataField="TENANCY_COUNTCHANGE" HeaderText="Tenancy Count Change" ItemStyle-Width="10%" />
            <asp:BoundField DataField="TENANCY_CHANGEDDATE" HeaderText="Tenancy Changed Date" ItemStyle-Width="10%" />
            <asp:BoundField DataField="STATUS" HeaderText="Current Status" ItemStyle-Width="20%" />

            <asp:TemplateField HeaderText="Approve/Reject">
                <ItemTemplate>
                    <asp:CheckBox ID="chkApprRejCMM" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>
    <div class="text-center">
        <asp:Button ID="btnApproveCMM" Text="Approve" runat="server" OnClick="btnApproveCMM_Click" CssClass="btn btn-primary" />
        <asp:Button ID="btnRejectCMM" Text="Reject" runat="server" OnClick="btnRejectCMM_Click" CssClass="btn btn-primary" />
    </div>

Also see my OnClick event of Approve.

protected void btnApproveCMM_Click(object sender, EventArgs e)
{
    try
    {
        IPColoFields ObjIPColoFields = new App_Code.IPColoFields();
        List<IPColoBilling.App_Code.UMS.UMSGroupDetails> UMSGroupDetails = (List<IPColoBilling.App_Code.UMS.UMSGroupDetails>)Session["lstUMSGroupDetails"];

        Session["lstUMSGroupDetails"] = UMSGroupDetails;
        string strApprove = "";

        foreach (GridViewRow gvrow in grdDisplayCMMData.Rows)
        {
            var checkbox = gvrow.FindControl("chkApprRejCMM") as CheckBox;

                if (checkbox.Checked)
                {
                    int Id = Convert.ToInt32(grdDisplayCMMData.Rows[gvrow.RowIndex].Cells[0].Text);

                    ObjIPColoFields.Unique_Id = Id;
                    ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
                    ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
                    ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
                    ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
                    ObjIPColoFields.FCA_STATUS = "1";
                    ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
                    strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
                }                                                         
         }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record Approved successfully'); window.location ='IpColoDefault.aspx';", true);
        BindCMMData();
    }
    catch (Exception ex)
    {
        string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
        CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
    }
}

I tried the logic of getting the count of checkbox and if it is less than 0 then prompt an error. But in Checkbox there is no such property of getting the count.

Please suggest any other way