jeudi 31 mai 2018

Material-UI-Next Checkbox not checking in React-Redux

I created a custom checkbox list in React using Material-UI-Next for use at my organization. We want to add a "none of the below" option where the None option clears the checkboxes below but also persists to the DB as an explicit "None of the below" is different than just not having checked any of the checkboxes below, yet.

The checkbox list worked fine and when I explicitly passed {true} or {false} to the "None" checkbox, it was checked or unchecked as desired. I debugged and found that the noneChecked variable has the correct value but the "checked-ness" of the "noneCheck" checkbox isn't always matching the value of the noneChecked variable. :(

Also, we can't check "None" when none of the options below are checked. And we want to be able to do this. Here is my code:

import React, { Component } from 'react';
import { Checkbox, FormGroup, FormControlLabel, FormLabel } from "material-ui";
import compose from 'recompose/compose';
import { withStyles } from 'material-ui/styles';

var _ = require('lodash');

//overwrite component styles
//injected into component
const styles = theme => ({
    root: {
        backgroundColor: 'yellow',
        fontFamily: 'Roboto'
    }

});

//injected into material-ui element. e.g style={style}
const style = {
  color: 'yellow'
};

export class CustomCheckBoxList extends Component
{
    constructor(props){
        console.log("Constructing CheckBoxList: props =", props)
        super(props);
        this.state = {
            options: [],
            noneChecked: null
        }

        this.applyChecked.bind(this);
        this.handleCheckboxChange.bind(this);

    };

    handleCheckboxChange(event, option) {
        let thisOption = {...option}
        let valuesToReturn = []
        let objectUpdates = {};
        if (this.props.values != null)
        {
            valuesToReturn = [...this.props.values]
        }
        let optionChecked = thisOption.isChecked
        let thisOptionWithoutChecked = _.omit(thisOption, ['isChecked'])
        if(optionChecked)
        {
            _.pullAllBy(valuesToReturn, [thisOptionWithoutChecked], 'id')
            objectUpdates[this.props.name] = valuesToReturn;
        }
        else
        {
            this.state.noneChecked = false;
            valuesToReturn.push(thisOptionWithoutChecked)
            objectUpdates[this.props.name] = valuesToReturn;
            objectUpdates[this.props.noneName] = false;
        }
        this.props.valueChanged(objectUpdates);
    }

    handleNoneCheck(event) {
        let objectUpdates = {};
        if(this.state.noneChecked == null || this.state.noneChecked == false)
        {
            this.state.noneChecked = true;
            objectUpdates[this.props.name] = [];
            objectUpdates[this.props.noneName] = true;
        }
        else
        {
            this.state.noneChecked = false;
            objectUpdates[this.props.noneName] = true;

        }
            this.props.valueChanged(objectUpdates);
    }

    applyChecked(option)
    {
        let optionIndex = _.findIndex(this.props.values, ['id', option.id])
        return {...option, isChecked: (optionIndex > -1)}
    }

    getOptionName(option){
        if (this.props.currentLanguage == 'en'){
          return option.nameEng;
        }else if (this.props.currentLanguage == 'fr'){
          return option.nameFra;
        }else{
          return null;
        }
    }//END OF METHOD


    render()
    {
        this.state = {
            options: [],
            noneChecked: null
        }

        if (this.props.options != undefined)
        {
            this.state.options = this.props.options.map(this.applyChecked.bind(this));
        }


        this.state.noneChecked = this.props.noneChecked;
        console.log('this.state.noneChecked= ', this.state.noneChecked);
        var noneChecked = this.state.noneChecked;

        return (
            <div>
                <FormLabel> <b>{this.props.label}</b>  {this.props.secondaryLabel}</FormLabel>
                <FormGroup row={this.props.row}>



                <FormControlLabel control= {
                                    <Checkbox id="noneCheck"
                                    checked = {noneChecked}
                                    onChange={(event) => this.handleNoneCheck(event)}/>
                                }
                                label={this.props.noneLabel} />
                {
                    this.state.options.map((option) =>{
                        let thisOption = {...option}
                        let optionName = this.getOptionName(option);

                        return (
                            <FormControlLabel key={thisOption.id}
                                control= {
                                    <Checkbox checked={thisOption.isChecked}
                                    onChange={(event) => this.handleCheckboxChange(event, option)}/>
                                }
                                label={optionName} />

                        );
                    })
                }
                </FormGroup>

            </div>

        );

    }
}


  export default withStyles(styles)(CustomCheckBoxList);

Any advice?




How to pre select django forms.CheckboxSelectMultiple

I am having a MultipleChoiceField to select language choices from a list of 7 languages.

LANGUAGES = (
   ('en', _('English')),
   ('pl', _('Polish')),
   ('da', _('Danish')),
)

Inside my forms.py, I have

language = forms.MultipleChoiceField(choices=LANGUAGES, widget=forms.CheckboxSelectMultiple)

I am trying to pre select choices when the page is loaded. I have tried

self.fields['language'].widget.attrs.update({'initial': selected_languages})

and

self.fields['language'].initial = selected_languages

inside __init__

my selected_languages has value like ['en', 'fr' ]

I this the right way to pre select fields in django forms? This method is not working for me. Is there any other method? NB: I am using this form inside django admin




checkBox Logic when i clicked the any one check box other is not checked

i have a problem for making a logic in textBox .if i clicked on the any check box other is cannot checked means to say in one time one checkBox is checked how to solve that problem only one check box is checked?

for example i'm from Usa i have more options in checkbox but i'm in usa not other countries so why i'm make a logic only USA is checked other is not checked?




How to have checkbox inside of a listview, to have a listener outside adapter activity?

So, i have menu items being displayed in listview, along with checkboxes, for the user to select which he likes. And i have an overhead cart icon which keeps track of no of checked items, by a function that is written in the adapter view.

My problem:

When i have implemented the cart increment function inside of OnItemClick listener, and then when i check a few items,it doesn't get updated unless i make a click outside of checkbox (anywhere else in the listview). I have tried disabling descendant focusability and modifying focusability as per other SO answers. They haven't solved my issue.

My calling activity

adapter = new MenuAdapter(CreateOrder.this,itemslist); listView.setAdapter(adapter);

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

                      selecteditems = adapter.getSelectedList();
                      Log.e("Selected Items",selecteditems.toString());
                      size = selecteditems.size();
                      qo.setText(String.valueOf(size));
                      Log.e("No of main items ",String.valueOf(size));


        }
    });

My Adapter class

public class MenuAdapter extends BaseAdapter {

Context mContext;
List<MainItem> linkedList;
protected LayoutInflater vi;

private boolean[] checkBoxState = null;
private int[] itemsqty;
private HashMap<MainItem, Boolean> checkedForItem = new HashMap<>();
public MenuAdapter(Context context, List<MainItem> linkedList) {
    this.mContext = context;
    this.linkedList = linkedList;
    itemsqty = new int[linkedList.size()];
    Arrays.fill(itemsqty,0);
    this.vi = (LayoutInflater)context.getSystemService(
            Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return linkedList.size();
}

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

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    final ViewHolder holder;
    if (convertView == null) {
        convertView = vi.inflate(R.layout.row_layout, parent, false);
        holder = new ViewHolder();
        holder.iname = (TextView) convertView.findViewById(R.id.tvname);
        holder.iprice = (TextView) convertView.findViewById(R.id.tvprice);
        holder.selectionBox = (CheckBox) convertView.findViewById(R.id.checkBox);
        holder.plus = (TextView)convertView.findViewById(R.id.tvplus);
        holder.minus = (TextView)convertView.findViewById(R.id.tvminus);
        holder.qty = (TextView)convertView.findViewById(R.id.tvqty);
        convertView.setTag(holder);

    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }

    final MainItem item = linkedList.get(position);
    checkBoxState = new boolean[linkedList.size()];

    holder.iname.setText(item.getItemname());
    holder.iprice.setText(item.getItemprice());

    /** checkBoxState has the value of checkBox ie true or false,
     * The position is used so that on scroll your selected checkBox maintain its state **/
    if(checkBoxState != null)
        holder.selectionBox.setChecked(checkBoxState[position]);
    //new added 1
    if(itemsqty!=null)
    {
        holder.qty.setText(String.valueOf(itemsqty[position]));


    }

    holder.selectionBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(((CheckBox)v).isChecked()) {
                checkBoxState[position] = true;
                ischecked(position,true);

            }
            else {
                checkBoxState[position] = false;
                ischecked(position,false);
            }
        }
    });
    holder.plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("Plus clicked","at"+position);
            if(itemsqty[position]<=10)
                itemsqty[position]+=1;
            holder.qty.setText(String.valueOf(itemsqty[position]));
        }
    });
    holder.minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("Minus clicked ","at"+position);
            if(itemsqty[position]>0)
            {
                itemsqty[position]-=1;
                holder.qty.setText(String.valueOf(itemsqty[position]));
            }
        }
    });



    if (checkedForItem.get(item) != null) {
        holder.selectionBox.setChecked(checkedForItem.get(item));
    }

    /**Set tag to all checkBox**/
    holder.selectionBox.setTag(item);

    return convertView;
}
private class ViewHolder {
    TextView iname;
    TextView iprice;
    CheckBox selectionBox;
    TextView plus;
    TextView minus;
    TextView qty;
}

public void ischecked(int position,boolean flag )
{
    checkedForItem.put(this.linkedList.get(position), flag);
}

public int[] getselectedquantity()
{
    return itemsqty;
}

public LinkedList<MainItem> getSelectedList(){
    LinkedList<MainItem> selectedlist = new LinkedList<>();
    LinkedList<String> List = new LinkedList<>();
    for (Map.Entry<MainItem, Boolean> pair : checkedForItem.entrySet()) {
        if(pair.getValue()) {
            //List.add(pair.getKey().getItemname());
            for(int j=0;j<linkedList.size();j++)
            {
                if(linkedList.get(j).getItemname().equals(pair.getKey().getItemname()))
                {
                    pair.getKey().setQuantity(itemsqty[j]);
                    Log.e("quantity ## ",String.valueOf(itemsqty[j]));
                }
            }
            selectedlist.add(pair.getKey());
        }
    }
    return selectedlist;
}

}




mercredi 30 mai 2018

How to get checkbox data as variable in Flask?

I'm trying to develop a web app using flask framework now am stuck with a problem .i have a list, Each item in this list needed to include the values of a checkbox and how to get the checkbox values as a variable?

pro.py

@app.route('/',methods=['POST'])
def ExcelEntery():
   Excel1=request.form['excel1']
   Excel2=request.form['excel2']
   print(Excel1)
   import ashi
   a,b=ashi.excelExtraxt(Excel1,Excel2)
   return render_template('Excel_feild_select.html',response=a,action=b)

@app.route('/Excel_feild_select',methods=['POST'])
def GetColumn():
   if request.method =='POST':
     val1=request.form.getlist('coloumn'))
     val2=request.values.get('coloumn2'))
     import Extract
     ans=Extract.add(val1,val2)

     return render_template('index.html')

sample.html`

     Liquid error: Unknown operator is




RSelenium click non-visible checkbox

I am trying to extract only the calendar with the most important events from the following page: https://www.investing.com/economic-calendar/. I have managed to select my time zone and tomorrow's calendat, but have difficulties selecting most important events.

This is what I have so far:

require(RSelenium)
remDr <- remoteDriver(port = 4445L)
remDr$open()
remDr$navigate("https://www.investing.com/economic-calendar/")
#Select the dropdown menu
option <- remDr$findElement("id", "timeZoneGmtOffsetFormatted")
option$clickElement()
remDr$executeScript("arguments[0].click();"
            , list(remDr$findElement("id", "liTz57")))

#Select tomorrow    
option <- remDr$findElement("id", "timeFrame_tomorrow")
option$clickElement()

As the javascript trick worked with the dropdown menu, I have tried the following to get the most important events:

option <- remDr$findElement("id", "filterStateAnchor")
option$clickElement()
remDr$executeScript("arguments[0].click();"
            , list(remDr$findElement("id", "importance3")))

The checkbox is not visible when the filter button is clicked, yet the same thing was not a problem when selecting my time zone. How can I click the checkbox to select only the most important events?




How to detect checked box in scanned form (PDF) using R?

My question is: Can I use optical mark recognition (OMR) in R to detect a checked box in a scanned standardized form like the one below?

I am familiar with OCR - e.g. tesseract - which has proven useless for the detection of a checked box as there is no distinguishable pattern between extracted characters (Varied from no characters being extracted to "[:]" to "EI" to "E1" to "%" and so on).

Standardized form example




How to check closest checkbox using jQuery

I have an foreach loop. In the foreach loop I have following code.

        <div class="col-md-2">
        <img alt="" class=" center-block developerlocationselection check" style="width:35%; margin-top:10%;" src="../../css/collecting/route-select.png">

       <input id="checkBox" type="checkbox" class="developernames" name="developernames">

       </div> 

I have an image and checkbox.

What i want to do is when i click the image, the closest checkbox to the image become checked.

This is my Javascript

   <script>
                        $(document).ready(function () {
                            //$(".developerlocationselection").on('click', function () {
                            $(".developerlocationselection").click( function () {

                                alert(2);

                                $(this).closest().find('input[type=checkbox]').prop('checked', true);



                            });
                        });

                    </script>

How I can check the closest checkbox on click of an image.




How to reduce the space occupied by an ipywidget checkbox below 100px?

No matter what I do, it seems the smallest width of an ipywidgets.Checkbox is 100px. Anything smaller and the widget doesn't show. It seems a waste of space when grouping with other widgets in an ipywidgets.HBox

import ipywidgets as ipyw
ly = dict(margin='0px', border='solid', max_width='100px')
w = ipyw.Checkbox(value=True, layout=ly)
display(w)

Also the widget is right-justified by default. I didn't figure out how to change the justification.

Has anyone come up with a way to decrease the occupying space?




Uncheck radio-button

So I'm quite new to programming in Python (I'm a highschooler) and I have this project where I need to have radio buttons in Pygame. The software that I'm creating is a calendar/reminder. So I created my own custom radio button on Illustrator instead of generating one from code from scratch. I have a blank radio button and on top of it, after clicking, an image of a checkmark appears like a real radio button except for its just an image. So far so good. But then I want it to disappear after I re-click on it. I can't find a way to do so. After I blit the picture what do I need to do to un-blit it? Here's the code (the pictures are on my computer):

import pygame as pg
import sys
import time

pg.init()

screen = pg.display.set_mode((600, 600))
picture = pg.image.load('light_gaussian_blur.jpg').convert()
picture = pg.transform.scale(picture, (600, 600))
rect = picture.get_rect()
screen.blit(picture, rect)

cal=pg.image.load('calendar_dos.png').convert_alpha()
cal=pg.transform.scale(cal, (450, 450))
screen.blit(cal,(80,83))

tick = pg.image.load('tick_red.png').convert_alpha()
tick = pg.transform.scale(tick, (25, 25))

pg.display.flip()

while True:
        for e in pg.event.get():
                if e.type == pg.QUIT:
                        pg.quit()
                        sys.exit()
                if e.type == pg.MOUSEBUTTONDOWN:
                        mx, my = pg.mouse.get_pos()
                        if my > 234 and my < 257:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,237))
                        if my > 277 and my < 296:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,275))
                        if my > 319 and my < 337:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,314))
                        if my > 358 and my < 375:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,354))
                        if my > 399 and my < 417:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,398))
                        if my > 441 and my < 459:
                                if mx > 134 and mx < 154:
                                        screen.blit(tick,(132,438))
        time.sleep(0.03)
        pg.display.update()




VB.Net updating access record

This is about a question/answer utility forum being built in VB.NET. The questions are getting saved in the access database, for the same question user has to pick a yes or no check button and then answer in a text box. This does not work. Error says

Error in Update syntax

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\myforum.accdb;"
    Dim Con As OleDbConnection = New OleDbConnection(constr)
    Con.Open()
    Dim com As OleDbCommand = New OleDbCommand
    com.Connection = Con
    Try
        Dim CheckedRows =
            (
                From Rows In DataGridView1.Rows.Cast(Of DataGridViewRow)()
                Where CBool(Rows.Cells("Answer").Value) = True
            ).ToList
        If CheckedRows.Count = 0 Then
            MessageBox.Show("Nothing checked")

        Else
            com = New OleDbCommand("UPDATE fquestions set reply VALUES('" & TextBox3.Text & "')", Con)
            Dim Num As Integer = com.ExecuteNonQuery
            If (Num <> 0) Then
                MessageBox.Show("Replied the question....", "Add Record", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.Close()
            Else
                MessageBox.Show("Record is not Added....", "Add Record Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End If
        Con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub




mardi 29 mai 2018

html checkbox unclick hides function variables

I have checkboxes created with labels:

<label><input type="checkbox" />ATL6101</label><br>

ATL6102
ATL6103
ATL6104
ATL6105

This corresponds to a function variable.

            Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {

getRoute('4200 N COMMERCE DR,30344-5707','822 RALPH MCGILL BLVD NE,30306','','','','','','','','','','','','','','','Green','ATL6101');

getRoute('4200 N COMMERCE DR,30344-5707','4575 WEBB BRIDGE RD,30005','','','','','','','','','','','','','','','Lime','ATL6102');

getRoute('4200 N COMMERCE DR,30344-5707','520 W PONCE DE LEON AVE,30030','','','','','','','','','','','','','','','Maroon','ATL6103');

getRoute('4200 N COMMERCE DR,30344-5707','575 OLYMPIC DR,30601','','','','','','','','','','','','','','','Navy','ATL6104');

getRoute('4200 N COMMERCE DR,30344-5707','3470 MCCLURE BRIDGE RD,30096','','','','','','','','','','','','','','','Lime','ATL6105');




        });
    }

How can I say if the checkbox is not clicked ignore the function variable? And is there a way I can replace the values in the function and dynamically create the checkboxes?




I have a retention window, but the data is not saved. How to store the value of boolean in the database?

Hello everybody. I'm trying to make an application that works with the database. I have a retention window, but the data is not saved. How to save the value boolean from check-box into the database?

How to resole this problem?

This is code of Database

public class DataBase extends SQLiteOpenHelper{
    public static final String DATABASE_NAME = "DataOfSchedule.db";
    public static final String TABLE_NAME = "DataOfSchedule_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "AGE";
    public static final String COL_4 = "SEX_MALE";
    public static final String COL_7 = "SEX_FEMALE";
    public static final String COL_5 = "WEIGHT";
    public static final String COL_6 = "HEIGHT";
    public static final String COL_8 = "TRAUMA";
    public DataBase(Context context){
        super(context, DATABASE_NAME, null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
                " NAME TEXT," +
                " AGE INTEGER NOT NULL DEFAULT 0 , " +
                "SEX_MALE  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
                "SEX_FEMALE  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\")," +
                "TRAUMA NOT NULL  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\")," +
                "WEIGHT INTEGER NOT NULL DEFAULT 0," +
                "HEIGHT INTEGER NOT NULL DEFAULT 0)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    }
    public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,age);
        contentValues.put(COL_4,sex_male);
        contentValues.put(COL_5,weight);
        contentValues.put(COL_6,height);
        contentValues.put(COL_7,sex_female);
        contentValues.put(COL_8,trauma);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();
        //To Check Whether Data is Inserted in DataBase
        if(result==-1){
            return false;
        }else{
            return true;
        }
    }
    public Cursor getALLData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
        return res;
    }
}

It is code of Activity which inserts data

public class InsertData extends AppCompatActivity {
    DataBase myDb;
    EditText txtName, txtAge , txtWeight, txtHeight;
    CheckBox boxSex_male,boxSex_female,boxTrauma;
    Button btnClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_data);
        myDb = new DataBase(this);
        txtName = (EditText) findViewById(R.id.name);
        txtAge = (EditText) findViewById(R.id.age);
        boxSex_male = (CheckBox) findViewById(R.id.sex_m);
        boxTrauma = (CheckBox) findViewById(R.id.trauma);
        boxSex_female = (CheckBox) findViewById(R.id.sex_f);
        txtWeight = (EditText) findViewById(R.id.weight);
        txtHeight = (EditText) findViewById(R.id.height);
        btnClick = (Button) findViewById(R.id.InsertBtn);
        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                ClickMe();
            }
        });
        if(boxTrauma.isChecked()){
            boxTrauma.setChecked(true);
        }else {
            boxTrauma.setChecked(false);
        }
        if(boxSex_female.isChecked()){
            boxSex_female.setChecked(true);
        }else {
            boxSex_female.setChecked(false);
        }
        if(boxSex_male.isChecked()){
            boxSex_male.setChecked(true);
        }else {
            boxSex_male.setChecked(false);
        }
    }
    private void ClickMe(){
        String name = txtName.getText().toString();
        String age = txtAge.getText().toString();
        String sex_male = boxSex_male.getText().toString();
        String trauma = boxTrauma.getText().toString();
        String sex_female = boxSex_female.getText().toString();
        String weight = txtName.getText().toString();
        String height = txtName.getText().toString();
        int weight_int = Integer.parseInt(weight);
        int age_int = Integer.parseInt(age);
        int height_int = Integer.parseInt(height);
        Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
        if (result == true){
            Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
        }
        Intent i = new Intent(this,ResultData.class);
        startActivity(i);
    }


}

It is my HTML

<ScrollView 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:padding="16dp"
    tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">
    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/insert_heading"
        android:layout_gravity="center"
        android:textSize="16dp"
        android:textColor="#021aee"/>

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_name"/>
    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_age"
        android:numeric="integer"/>
    <EditText
        android:id="@+id/weight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_weight"
        android:numeric="integer"/>
    <EditText
        android:id="@+id/height"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_height"
        android:numeric="integer"/>

    <TextView
        android:padding="10dp"
        android:text="@string/insert_sex"
        android:layout_gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/sex_m"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/male"/>
    <CheckBox
        android:id="@+id/sex_f"
        android:text="@string/female"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:padding="10dp"
        android:text="@string/insert_trauma"
        android:layout_gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/trauma"
        android:text="@string/insert_trauma_subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"/>

    <Button
        android:id="@+id/InsertBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="@string/insert_button"
        android:textColor="#f2fde4"
        android:layout_gravity="center"/>
</LinearLayout>

</ScrollView>




remove appended data if checkbox unchecked

I want to append data if checkbox is checked and remove appended data if checkbox is unchecked. Dynamic html list is generated as following

<label class="left col20">
  <input type="checkbox" id="newscat[]" name="newscat" value="<?php echo $row['cid']?>">
  <?php echo $row['title']?>
</label>

Data is appended as following when checkbox is checked. I want to remove appended this data or div after checkbox is unchecked.

$(document).ready(function(){
    $('input[name=newscat]').on('click', function(event) {
      if($('input[name=newscat]:checked').length) {
            var menuid = $(this).val();
            $.ajax({
                url:"submenufetch.php",
                method:"POST",
                dataType:"text",
                data:{menuid:menuid},
                success:function(data){
                    $('.submenu').append(data);
                }
            });
        }
        if(!$('input[name=newscat]:checked').length) {
            $('.submenu').append('');
            // need to remove appended element if this checkbox is unchecked
        }
    });
})




Show button when at lease 1 checkbox in a list checkboxes is checked

I have some code that works fine; it displays a button when a checkbox is checked. But now I want to change something and in that case there will be more checkboxes (they are generated by the content of a database so the number is not clear now).

But the solution is based on the ID of an element and having multiple the same ID's is not valid ánd it does not work.

I have the code here: https://codepen.io/anon/pen/jKOLew?editors=1111. As you can see only the first checkbox enables the div, the second doesn't.

Can somebody tell me how to solve this?

The code is this:

html:

<input type="checkbox" id="chkMessage" />Do you have Passport?<input type="checkbox" id="chkMessage" />Do you have Passport? <div id="dvMessage" style="display: none">Passport Number: <input type="text" /></div>`

And javascript:

`$(function() {  $("#chkMessage").click(function() {    if $(this).is(":checked")) {      $("#dvMessage").show();      $("#AddMessage").hide();    } else {      $("#dvMessage").hide();      $("#AddMessage").show();    }  });});`




Get checkbox within div value from java servlet

I can't get the checkbox value of "no_del_file" into the servlet.

here is my JSP:

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
 <html>
 <head>
  <title>List of Command menu</title>


 </head>
 <body>
<div><b>${reply}</b></div>
<div id="wrapper">
<div id="menu">
<form action="runButtonCommand" method="post" name="myform"> 
<a href="runButtonCommand?param1=list apps" >List1</a><br/><br/>
<a href="runButtonCommand?param1=list data" >List2</a><br/><br/>
<br/><br/>

no del: 

<%String test = (String)request.getParameter("no_del_file"); %>
<%String checked = "";%>

<% 
if ("on".equals(test)) {
    checked="checked=\"on\"";

} %>
<input type="checkbox" name="no_del_file" <%=checked%>>
<br />

</form>

</div>
<div id="output">
  <p>Output:</p>
  <textarea style="resize: none;" data-role="none" rows="40" cols="120" name="outputarea">
  ${data}
  </textarea>
  </div>

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

And here is the Servlet part where I try to get the checkbox value:

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String[] tester= request.getParameterValues("no_del_file");
    System.out.println("Start: "+tester);
    performTask(request, response);
}

However it doesn't matter if I use getParameterValues, getParameter or getAttribute I always get null if checked or unchecked. How can I get that value?

Thanks for your help.

Viking




Margin between checkboxes' labels when the input is hidden

I have some checkboxes styled to look like a select. I did this by setting the input to display:none and letting the label as the only visible element.

The problem is that I want some margin between the elements but it only seems to work when the checkbox is visible.

HTML:

<div class="dropdown">
    <span class="tag">
        <span class="tag-text">Talla</span>
        <span class="tag-caret">&#9660</span> 
    </span>
    <div class="dropdown-content">
        <input type="checkbox" name="talla[]" id="36" class="filtro">
        <label for="36" class="label">36</label>
        <br>
        <input type="checkbox" name="talla[]" id="37" class="filtro">
        <label for="37" class="label">37</label>
        <br>
        <input type="checkbox" name="talla[]" id="38" class="filtro">
        <label for="38" class="label">38</label>
        <br>
    </div>
</div>

CSS for the part I ask for:

input[type="checkbox"]
            {            
                display:none;
            }

label
        {   
            padding:3px;
            margin:10px;
            border:1px solid lightslategrey;
            border-radius: 1px;
        }




disable/enable button when checkboxes is not checked

I have a MVC application in C# and in a view that will have some checkboxes and on this list of checkboxes some checkboxes will come "checked and disable" from the database depends if I pass some or other value of ID.
But my problem is my button only can submit if i check a checkbox enable or if i have more than 2 enable and checked all the checkboxes enabled and not checked the checkbox disabled.

   <input type="checkbox" name="SelectAll" id="checkboxPrincipal" />SelectALL


@foreach (var item in Model)
    {

     @if (codigoUniversidad != -1) {
                UniversalTitulosEntities db = UniversalTitulos.App_Start.ConexionConfig.db(codigoUniversidad);
                TbEstadoLoteEST consulta = db.TbEstadoLoteEST.Where(e => e.IdEstadoLoteEST == item.EstadoLOT).SingleOrDefault();
                if (consulta.IdEstadoLoteEST == 7) {
                        <td><input type="checkbox" value="@item.LoteIdLOT" name="mycheckbox" id="mycheckbox"/></td>
                }
                if (consulta.IdEstadoLoteEST == 8) {
                        <td><input type="checkbox"  value="@item.LoteIdLOT" name="mycheckbox" id="mycheckbox" checked="checked" disabled="disabled"/></td>
                }
                if (consulta.IdEstadoLoteEST != 8 && consulta.IdEstadoLoteEST != 7) {
                        <td><input type="checkbox" value="@item.LoteIdLOT" name="mycheckbox" id="mycheckbox" disabled="disabled"/></td>
                }
            }



 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" id="myButton" name="myButton" >Update </button>


<script type="text/javascript">
        $(document).ready(function () {
            $('input[name=checkboxPrincipal]').click(function () {
                $('input[name=mycheckbox]:enabled').prop('checked', $(this).prop('checked'));
            });
            $('#myButton').click(function () {
                var listaIdLotes = [];
                $('#mycheckbox:checked').each(function () {
                    listaIdLotes.push(this.value);

             });

                $(function () {
                    var checkboxes = $(':checkbox:not(#checkboxPrincipal)').click(function (event) {
                        $('#Actualizar').prop("disabled", checkboxes.filter(':checked').length == 0);


                    });

                    $('#checkboxPrincipal').click(function (event) {
                        checkboxes.prop('checked', this.checked);
                        $('#Actualizar').prop("disabled", !this.checked)

                    });
                    $('input[type=checkbox]').each(function () {
                        var elem = $("#" + this.id);
                        if (!elem.attr("disabled")) {
                            this.checked = true;
                        }
                    });
                });




jquery check checkbox of a certain criteria is checked

I have a JQuery 1.12 script that displays a message if a set of checkbox inputs are not chosen.

The code from here works fine with:

var checked = $('input[type=checkbox]:checked').length;
        if(!checked) {
            $("#satNavCheckText").slideDown();
            $("#satNavCheckText").focus();
            return false;
        }
        else {
            $("#satNavCheckText").slideUp();
            return false;
        }

The above works fine

BUT I now have to add new checkboxes to the same form and so I want to clarify the above code to only check certain set of checkboxes; namely those with the name='MaddsatNavValid' reference.

I have tried:

var checked = $('input[name="MaddsatNavValid"]:checkbox:checked').length;

and also

var checked = $('input[name="MaddsatNavValid"][type="checkbox"]:checked').length;

But the result is that the page constantly runs the else{...} query when any checkbox is ticked; whereas the return value of var checked should always be non-positive unless a checkbox of that name has been ticked.

I have seen similar questions on counting ALL checkboxes on a page or on selecting checkboxes by class or by id, etc. but I've not seen anything about how to do this or more specifically if there's an issue in the code shown.

I'm sure my issue is relatively simple for someone who knows. I have javascript. Javascript hates me.




lundi 28 mai 2018

Auto check checkboxes in ListView

I am working on a listview control in Powershell Studio Windows Forms.

Group 1: Contains all groups which ADUser is already a member of.

Checkmarkbox | Name | Description

Groups 2: Contains all groups of the entire directory Checkmarkbox | Name | Description

I need your assistance with:

Group1 Items should be checked by default Group2 should filter out those in group1 When removing/adding a checkmark in Group1 or 2 it should automatically move up/down.

Problem is that i have never worked with the listview control before, so i really dont know where to start, except it has most likely something to do with the SelectedIndexChanged event :)

Any help is much appreciated.

Thanks in advance.




How to Uncheck all below Checkboxs when one checkbox is Unchecked

I have a dynamic check-boxes which are already mark. When I click one out of it then all the below check-boxes should be unchecked and if re mark again all the above checkbox mark again. Is there anyone who can help me on this Please?

Thank you.

                @for (int i = 0; i < Model.transportDate.Count(); i++)
                {
                    <tr>
                        <td>
                            @Html.CheckBoxFor(Model => Model.transportDate[i].selection)
                        </td>
                        <td>
                            @Html.TextBoxFor(Model => Model.transportDate[i].Date)
                        </td>
                    </tr>
                }

Overview of question




Larger check boxes that work cross-browser?

I've seen many attempts at a solution. I'm trying to make the size of a check box larger with support for IE9+ major browsers.

The closest solution I came to used the transform scale property which worked but it looks pretty bad.

Also many of the questions on this topic were outdated.

Anyone have any success this this?

Thanks




Type of Button- Android

Which is the type of button which displays the subtext(or in my case checkbox once clicked? There is nothing more to ask, I have added an image to show what I am Looking for. This is what I am looking for




simply Store checkbox state to sqlite database in android

I'm simply trying to store the state of checkbox in database but my application crashes when i click on submit button.I am trying to do this with a sqliteOpenHelper. After storing the state I also want to display it but first I'm not able to store it. Please guide me as I'm new to android. Here's my code..

    //MainActivity.java
    CheckBox ch1;
    Button btnSubmit;
    int checked=0;
    DatabaseHelper dbhelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ch1=(CheckBox)findViewById(R.id.checkBox);
    btnSubmit=(Button)findViewById(R.id.button);

    AddData();
    }

    public void AddData() {
    btnSubmit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ch1.setOnCheckedChangeListener(new 
      CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, 
         boolean isChecked) {
                    if(isChecked){
                        checked = 1;
                    }else{
                        checked = 0;
                    }
                }
            });


            boolean insertData = dbhelper.addData(checked);

            if (insertData == true) {
                Toast.makeText(MainActivity.this, "Order Placed!", 
       Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Something went wrong : 
      (.", Toast.LENGTH_LONG).show();
            }
        }
    });
    }

    //databasehelper.java
    public class DatabaseHelper extends SQLiteOpenHelper {

     public static final String DATABASE_NAME = "check.db";
      public static final String TABLE_NAME = "entry";
      public static final String COL1 = "SIZE";

     public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
     }

    @Override
    public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + "(SIZE INTEGER)";
    db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
   {
    db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
    onCreate(db);
   }

   public boolean addData(int s1){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(COL1, s1);

    long result  = db.insert(TABLE_NAME, null, contentValues);

    if(result == -1){
        return false;
    }else{
        return true;
    }
      }
    }




jquery function check all checkboxes if none checked

I have 2 checkboxes and I need one of them at least to be checked always. So how to automatically check them both if of none of them is checked.

thanks




How to change Checkbox UI Using Html and CSS?

<input type='checkbox' name='chkbox'/>

I want to change the checkbox height and width and also background color if possible




Checkboxes list shows flickering tick when checked or unchecked a single checkbox in list using react redux

I am using reactJs and redux and fetching routers via redux-action of some buildings, i got stuck in an issue of checkbox where clicked on checkbox show flickering tick with a list of check-boxes. you can see in gif. these check-boxes are placed in a react component called react-slick.

see flickering image here

Code Where the Routers fetched action call on Check true

this.props.fetchRouters(this.props.OneLinks, this.props.user.token)
    .then(()=>{

            let elements = document.getElementsByClassName("DefaultBox1");
            unselectedold.forEach(function(i) {
                for (let inp of elements) {
                    if (inp.type === "checkbox" && inp.name == i && inp.checked != false){
                        inp.checked = false;
                    }
                }
            });

    });

Code where the Router fetched action call on Check false

this.props.fetchRouters(this.props.OneLinks, this.props.user.token)
    .then(()=>{

            let elements = document.getElementsByClassName("DefaultBox1");
            unselected.forEach(function(idbldg) {
                for (let inp of elements) {
                    if (inp.type === "checkbox" && inp.name == idbldg && inp.checked != false){
                        inp.checked = false;
                    }
                }
            });

    });




dimanche 27 mai 2018

Jquey - Dynamic checkbox / radiobuttons - Add more options

I'm creating an app to build your own form with JQuery. I want to add more options on the checkbox and the radio tipe questions. For some reason the last function isn't working. It's meant to add a new option when clicking on the button created in the first function.

//Adding a checkbox question
$("#btn1").click( function(){
$("#rectangle").before("<br><input type='text'placeholder='Question'> <input type='checkbox'> <input type='text' placeholder='Opção'> <button class='btn newCheck'>+</button>");
});

//Adding a new option
$(".newCheck").click( function(){
console.log("+ radiobutton");
$(this).before("<input type='checkbox'> <input type='text' placeholder='Option'>");
});

I tried putting " onclick='' " directly on the button and do a normal javascript function and it worked fine. The problem with that is that if I have several checkbox tipe questions new options will only be added to the first question.




Rails 4 - Simple validation of check_box_tag fails

I have a support form where users can send messages. This support form should have a checkbox and the message sould only be sent if the check box has been activated. So far I have in my support.rb model (just the relevant part):

class Support
  include ActiveModel::Validations

  attr_accessor :dataprotection
  validates :dataprotection, :acceptance => true
end

As far as I understand I don't even need the attr_accessor reference since it creates a virtual attribute if :dataprotection is not part of my model, so after adding :dataprotection I have not done a migration. Anyhow, I do not save the message and the data in a database, it is just sent it to an email address.

The view is (again just the relevant part, I use haml):

= form_for :support, :url => { :action => "create" }, :html => { :method => :post } do |f|
  = render 'shared/error_messages_support'
    %div
      = check_box_tag 'dataprotection'
      = label_tag(:dataprotection, simple_format(t"support.dataprotection"))

The form is displayed correctly, also the check box appears and is clickable. But if the user does not check it the form is sent anyhow, there is no error message.

What do I need to change in order to get an error message in case the box is not ticked?

My controller is

class SupportsController < ApplicationController

  def new
    @support = Support.new(:id => 1) # id is used to deal with form
  end

  def create
    @support = Support.new(params[:support])
      if @support.save
        flash[:success] = t "support.flashsuccess"
        redirect_to(root_path)
      else
        render 'new'
      end
    end
  end

My Gemfile is:

ruby '2.0.0'

source 'http://rubygems.org'

gem 'rails', '4.0.0'
gem 'jquery-rails', '2.1.1'
gem 'capistrano', '2.14.1'
gem "therubyracer", '~> 0.11.4'
gem 'carrierwave', '0.8.0'
gem 'haml', '~> 4.0'
gem 'mysql2', '0.3.11'
gem 'rmagick', '2.13.2'
gem 'fancybox2-rails', '~> 0.2.8'
gem 'sitemap_generator', '3.4'
gem 'whenever', '0.7.3', :require => false
gem 'will_paginate', '3.0.5'
gem "friendly_id", "~> 5.0.3"
gem 'turbolinks'
gem 'jquery-turbolinks'
gem 'protected_attributes'
gem 'globalize', '~> 4.0.2'
gem 'sass-rails', '~> 4.0.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'

group :development do
  gem 'rspec-rails', '2.13.2'
  gem 'annotate', '~> 2.4.1.beta'
  gem 'faker', '0.9.5', :require => false
  gem "database_cleaner", "~> 1.0.1"
  gem 'debugger'
end




UITableView Checkbox ( Select a button when another button is pressed )

I have a button called btnChk2 . I want when the user press the btnChk2 that the button btnChk get selected. Here is my code what happens in my code is that when btnChk2 is pressed btnChk2 get selected and not btnChk.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckBoxCell")

    if let lbl = cell?.contentView.viewWithTag(1) as? UILabel {
        lbl.text = "item-\(1)"
    }

    if let btnChk = cell?.contentView.viewWithTag(2) as? UIButton {
        btnChk.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
    }

    if let btnChk2 = cell?.contentView.viewWithTag(100) as? UIButton {
        btnChk2.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
    }

    return cell!
}

@objc func checkboxClicked(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}




samedi 26 mai 2018

PHP:checked attribute in array of checkboxes

I have an array like this

$current_asset = [
    ['name'=>'Land,'id'=>1],
    ['name'=>'Building ,'id'=>2],
    ['name'=>'Machinery','id'=>3],
];

<?php 
 foreach($current_asset as $key=>$value){ ?>
 <input type="checkbox" name="current_asset[]" value="<?php echo $value['id'] ?>">

 <?php } ?>

My question how can I add checked attribute in if one of the value is checked.

I am getting the checkbox array like this on form submit

[current_asset] => Array
        (
            [0] => 1
            [1] => 2
        )




How to handle Checkbox click events

I am trying to handle check events of Checkbox, Checkbox is in custom listview, whenever I'm clicking on Checkbox my app is crashing with null pointer exception. I want to set checkbox checked by default but whenever I'm changing the state of checkbox my app is crashing. Here is the getView method

enter code here
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    convertView = inflater.inflate(R.layout.row, parent, false); 
    viewholder = new ViewHolder();
    viewholder.checkbox = (CheckBox) convertView.findViewById(R.id.cb);
    viewholder.texview = (TextView) convertView.findViewById(R.id.tvv);
    viewholder.texview.setText(modelItems.get(position));
    viewholder.checkbox.setChecked(true);
    viewholder.checkbox.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View p1)
            {
                // TODO: Implement this method
                Toast.makeText(context,"checkbox item"+modelItems.get(position),Toast.LENGTH_SHORT).show();
                if (((CheckBox) p1).isChecked())
                {
                    checkBoxState[position] = true;
                    }

                else
                {
                    checkBoxState[position] = false;
                }
            }
        });
    return convertView;
}

Logcat

enter code here
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           FATAL EXCEPTION: main
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           Process: com.sk.scdoenloader, PID: 7489
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           java.lang.NullPointerException
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at com.sk.scdoenloader.CustomAdapter$100000000.onClick(CustomAdapter.java:63)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.view.View.performClick(View.java:4463)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.widget.CompoundButton.performClick(CompoundButton.java:100)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.view.View$PerformClick.run(View.java:18789)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.os.Handler.handleCallback(Handler.java:808)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.os.Handler.dispatchMessage(Handler.java:103)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.os.Looper.loop(Looper.java:193)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at android.app.ActivityThread.main(ActivityThread.java:5299)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at java.lang.reflect.Method.invokeNative(Native Method)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at java.lang.reflect.Method.invoke(Method.java:515)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
05-26 21:55:09.937 7489 7489 E     AndroidRuntime com.sk.scdoenloader           at dalvik.system.NativeStart.main(Native Method)




Angular 2: Array with checkbox not working properly

I'm binding one array with Checkbox. However, When I try to change bool attribute for single element of array but it changes for all elements.

My HTML Component is as below.

<div class="col-sm-4" *ngFor="let karyalay of karyalayListFinal">
  <div class="checkbox-fade fade-in-primary">
    <label>
      <input formControlName="karyalay_group" type="checkbox" name="karyalaysCheckbox" value="" [(ngModel)]="karyalay.isChecked" 
      (click)="callEvents(karyalay.karyalayId)">
      <span></span>
    </label>
  </div>
</div>

Now I'm trying to change value of single or selected element as below.

for (let karyalay of this.karyalayListFinal) {
    let tempInd = _.findIndex(this.roleMasterEventList, {'KARYALAY_ID': karyalay.karyalayId});
    if (tempInd > -1) {
      this.karyalayListFinal[tempInd].isChecked = true;
    }
}

Actually, if tempInd > -1 then and then only that element's value should be changed. But it changes for all.

Don't know whether this is ngModel issue or what?

Thanks




vendredi 25 mai 2018

adding css to django checkbox multiselect

I managed to add css classes to my forms with

attrs={'class': 'form-control'}

For example in a Multiple Choice Field:

    CHOICES_NAT = (('None', 'None'),('Deutschland', 'Deutschland'), ('Amerika', 'Amerika'), ('Türkei','Türkei'), ('Frankreich', 'Frankreich'))
    Nationality = forms.ChoiceField(widget = forms.Select(attrs={'class': 'form-control'}), choices = CHOICES_NAT)

But i still fail to display the checkboxes of a Multiple Choice Field. The Choices are displayed only the Chechboxes are missing. Heres my code for the Ceckboxes:

    CHOICES_AGE = (('0-8', '0-8'),('8-14', '8-14'), ('14-21', '14-21'), ('21-60','21-60'), ('60-90', '60-90'))
    Target_Age = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(attrs={'class':'form-group', 'type':'checkbox',}), choices = CHOICES_AGE, )

As far as i can see the type is not added to the html - i might need to pass multiple attrs differently.

Thanks for your help! =)




Setting a checkbox's state according to column in gridview

I was just wondering how to either tick or untick a check box according to the value "TRUE" or "FALSE" in a gridview. Similar to writing the value in a textbox

textBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();

but for

checkBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();

if "TRUE" = Tick, if "FALSE" = Untick




jeudi 24 mai 2018

Implementing CRUD with checkbox for MVC in C#

Normally, when we add scatffolded item to implement CRUD functionality in MVC with EF, there will be 'Edit', 'Detail' and 'Delete' actionlink for each records/rows from table. How I would like to implement CRUD is that index view has one set of 'Edit', 'Detail' and 'Delete' actionlink or button at the top, apply checkbox for each record/row in the table. In this way, user can select one record/row (just one selection for my project) and 'Edit', 'Detail' and 'Delete' to selected record/row. I was only able to find checkbox which gets the ID for selected records with one submit button (in my case, it has to have multiple button for 'Edit', 'Detail', 'Delete' and etc) that pass the IDs to one of the action. After retrieving ID for selected record/row I would like to have multiple option for which action to pass ID to (to 'Edit', 'Detail', 'Delete' and etc) Any tip or advise will help. Thank you.




How to make an asking box with „yes” and „no”

I want to make a box that will ask for running an application. If user click „yes” it starts an process but if he clicks „no” it’s close and doesn’t do nothing. I want it in form app. Thanks




Checkboxgroup / HTML::FormFu::Model::DBIC / many_to_many selection (Catalyst/Perl)

I have a Checkboxgroup and I want to check the checkboxes based on my mysql db values.

Here's the relevant code of my first table 'dicos':

__PACKAGE__->has_many(
  "favorites",
  "accessidico::Schema::Result::Favorite",
  { "foreign.dico_id" => "self.id" },
  { cascade_copy => 0, cascade_delete => 0 },
);

Here's the relevant code of my second table 'favorites':

__PACKAGE__->belongs_to(
  "dico",
  "accessidico::Schema::Result::Dico",
  { id => "dico_id" },
  { is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);

And my tables descriptions:

'favorites'

+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| user_id | int(11) | NO   | PRI | NULL    |       |
| dico_id | int(11) | NO   | PRI | NULL    |       |
+---------+---------+------+-----+---------+-------+

'dicos'

+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| id         | int(11) | NO   | PRI | NULL    |       |
| name       | text    | YES  |     | NULL    |       |
| name_index | text    | YES  |     | NULL    |       |
+------------+---------+------+-----+---------+-------+

I want to have the labels of the checkboxes corespond to the 'name' of my dicos table and check the values based on the 'dico_id' of the 'favorites' table. The table 'favorites' is based on the current user of the web-app and his selection of favorites dictionnaries.

So far, the behaviour is: I have my checkboxes checked based on 'dico_id' but the labels correspond to the column 'dico_id' of 'favorites'. For example with this favorites table:

+---------+---------+
| user_id | dico_id |
+---------+---------+
|       1 |       2 |
|       2 |       1 |
|       2 |       2 |
+---------+---------+

If the current user have his user_id=2, my checkboxes look like this: []2 [X]1 [X]2

FormFu code (index.yml):

---
indicator: submit
action: /update_fav
elements:
    - type: Checkboxgroup
      name: dico_id
      model_config:
        model: DB
        resultset: Favorite
        default_column: dico_id 
        label_column: dico_id
    - type: Submit
      name: submit
      value: action

I tried different things with 'default_column' and 'label_column' with no success to display what I wanted.

Controller code (Favorites.pm):

sub index :Path :Args(0) :FormConfig {
    my ( $self, $c ) = @_;
    my $form = $c->stash->{form};
    my $user = $c->user->get('id');

    my @checked_objs =  $c->model('DB::Favorite')->search({user_id => $user});
    $form->process();

    if (!$form->submitted){
        $form->model->default_values(@checked_objs);
    }
    $c->stash(template => 'favorites.tt');
    $c->forward('View::HTML');
}

I also tried to change the resultset in the FormFu code:

---
indicator: submit
action: /update_fav
elements:
    - type: Checkboxgroup
      name: dico_id
      model_config:
        model: DB
        resultset: Dico
        default_column: name 
        label_column: name
    - type: Submit
      name: submit
      value: action

Again, I tried different things with 'default_column' and 'label_column'... Like this I have my labels corresponding to 'dicos' 's name but I only succeed to get one checkbox checked even when there is should be more. The controller code is the same.




How can I patch data to Check-boxes Array in Angular 4/5

I am using angular reactive form. how can i patch or set data to array of check-boxes.I have array like this

 departmentList = [
        {id: 1, name: 'Dermatolgy'},
        {id: 2, name: 'Surgery'},
        {id: 3, name: 'Dental'},
        {id: 4, name: 'SkinCareLaser'},
   ];

Let Suppose i want to set true or checked Surger .(on base of DB data).

I am using following code for adding data on registration user.

    <div *ngFor="let item of departmentList">
      <input type="checkbox" formControlName="departmentControl"
       name=
       value=""
      (change)="selectDepartment($event,item)">
      
     <span></span>
   </div>

Class.TS

selectedDepartment: any = [];
selectDepartment(event: any, item: any) {
    console.log(event.checked);

if (event.target.checked) {

        this.selectedDepartment.push(item.id);
    }
    else {
        let updateItem = this.selectedDepartment.find(this.findIndexToUpdate, item.id);

        let index = this.selectedDepartment.indexOf(updateItem);

        this.selectedDepartment.splice(index, 1);
    }
     console.log(this.selectedDepartment);

}

that's working fine.

Question : how can i patch or set data to array on Update Function on base of another arrays data that is fetched from server .




VB.net TreeView with checkboxes only on certain layers

Does anyone know of a way to set a TreeView control to only show checkboxes on particular nodes or layers?

I have a TreeView but I only want the checkbox's to appear at layer 3 and not on any of the parent checkboxes.

Kind regards




Solution for checking the checkboxes with php. Think I must use a value

The checkboxes query works offline, but not online. I think I have to work with a value. It should not be a selection, but all checkboxes must be selected to be able to send.

I can not find the right solution in PHP. The checkboxes are checked but not processed.

Can somebody help me with the php-code?

<form id="contact-form" action="#">

  <div class="row contact-row">
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input type="text" id="firstname" name="firstname" placeholder="Vorname" required>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input type="text" id="lastname" name="lastname" placeholder="Nachname" required>
    </div>
  </div>

  <div class="row contact-row">
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input name="telefon" id="telefon" type="text" placeholder="Telefon" required>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6 contact-email">
      <input name="email" id="email" type="email" placeholder="E-mail" required>
    </div>
  </div>

  <input name="subject" id="subject" type="text" placeholder="Anfrage zur Immobilie 2018_1400">
  <textarea name="message" id="message" placeholder="Nachricht" rows="5"></textarea>

  <div class="col-md-12 col-sm-12 col-xs-12 mb-30">
    <h6>Your Choose</h6>
    <ul class="checkboxes">
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox1" id="checkbox1" required>
        <label for="checkbox1">*&nbsp;&nbsp;Red</label>
      </li>
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox2" id="checkbox2" required>
        <label for="checkbox2">*&nbsp;&nbsp;White </label>
      </li>
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox3" id="checkbox3" required>
        <label for="checkbox3">*&nbsp;&nbsp;Blue</label>
      </li>
    </ul>
  </div>

  <input type="submit" class="btn btn-lg btn-color btn-submit" value="Nachricht senden" id="submit-message">
  <div id="msg" class="message"></div>
</form>

<?php
if ($_POST) {

    $to = "abcd.de"; // email here
    $subject = 'Kontaktformular '; // Subject message here

}

//Send mail function
function send_mail($to, $subject, $message, $headers)
{
    if (@mail($to, $subject, $message, $headers)) {
        echo json_encode(array('info' => 'success', 'msg' => "Message send. "));
    } else {
        echo json_encode(array('info' => 'error', 'msg' => "Message not send."));
    }
}

//Check if $_POST vars are set
if (!isset($_POST['firstname']) || !isset($_POST['lastname']) || !isset($_POST['telefon']) || !isset($_POST['email']) || !isset($_POST['message'])) {
    echo json_encode(array('info' => 'error', 'msg' => 'Fill out all fields.'));
}


//Sanitize input data, remove all illegal characters    
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);

$telefon = filter_var($_POST['telefon'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

$website = filter_var($_POST['website'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);


//Validation
if ($firstname == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Firstname please."));
    exit();
}
if ($lastname == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Lastname please."));
    exit();
}

if ($telefon == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Telefon?"));
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(array('info' => 'error', 'msg' => "Valid e-mail."));
    exit();
}

if ($message == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Message?"));
    exit();
}

if ($checkbox1 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 1."));
    exit();
}
if ($checkbox2 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 2."));
    exit();
}
if ($checkbox3 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 3."));
    exit();
}


//Send Mail
$headers = 'From: ' . $email . '' . "\r\n" .
    'Reply-To: ' . $email . '' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

send_mail($to, $subject, $message . "\r\n\n" . 'Vorname: ' . $firstname . "\r\n" . 'Nachname: ' . $lastname . "\r\n" . 'Telefon: ' . $telefon . "\r\n" . 'Email: ' . $email, $headers);
?>

(function($) {
  "use strict";
  var submitContact = $('#submit-message'),
    message = $('#msg');

  submitContact.on('click', function(e) {
    e.preventDefault();

    var $this = $(this);

    $.ajax({
      type: "POST",
      url: 'mail-send.php',
      dataType: 'json',
      cache: false,
      data: $('#contact-form').serialize(),
      success: function(data) {

        if (data.info !== 'error') {
          $this.parents('form').find('input[type=text],input[type=email],input[type=checkbox],textarea,select').filter(':visible').val('');
          message.hide().removeClass('success').removeClass('error').addClass('success').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
        } else {
          message.hide().removeClass('success').removeClass('error').addClass('error').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
        }
      }
    });
  });

});




setAttribute to checkbox with servlet

here is what I have:

JSP:

 <input type="checkbox" id="no_del_file" name="no_del_file" value="no_del_file" ><br />

Java:

 boolean cbState = request.getParameter( "no_del_file" ) != null;
            System.out.println("cbstate: "+cbState);
            if (cbState == true) {
                request.setAttribute("no_del_file", "checked");
                String checker=(String) request.getAttribute("no_del_file");
                System.out.println(checker);
            }

 RequestDispatcher dispatcher = request.getRequestDispatcher("/runButtonCommand.jsp");
            dispatcher.forward(request, response);

The problem is that the output is:

 cbstate: true
 checked

but the checkbox is not checked itself after the servlet returns the responds. The tick is removed for some reason.

Any ideas?




Change radio button to checkbox displays indeterminate in chrome

Im trying to make a radio button list appear as a checkbox list but with the benefits of a radio button list (i.e only 1 value can be submitted).

However the problem I am facing is that in Google Chrome a default value is set on 'indeterminate' while it should be set as 'false'. The first value of the list should be 'true' by default and that currently works. How can I prevent the second value from being set on indeterminate. The code can behave strange sometimes as refreshing the browser sometimes result in unchecking the indeterminate and sometime checking it back to indeterminate. I haven't found a pattern in this.

    <style type="text/css">input[type="radio"] {
        -moz-appearance: checkbox;
        -webkit-appearance: checkbox;
    }


}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>

 $( document ).ready(function() {    
        $("input[type=radio]:eq(0)").prop("checked", true);
        $("input[type=radio]:eq(0)").data("ischecked", true);
        $("input[type=radio]:eq(1)").prop("checked", false);
        $("input[type=radio]:eq(1)").addClass( "opt-in-radio" );



        $('form').on('click', ':radio', function() {
            var status = $(this).data('ischecked'); //get status
            status && $(this).prop("checked", false); //uncheck if checked
            $(this).data('ischecked', !status); //toggle status
            if (this.className == "opt-in-radio") $("input[type=radio]:eq(0)").prop("checked", !this.checked)
        });
    });
</script>




VB.NET Read 2 checkboxes status from file

I am trying to recover the status of 2 checkboxes. This 2 checkboxes i made them to work as radiobuttun: While one is checked, the another one uncheck.

I have an external file for the configuration of the program and i want that evrytime that I exit from the program, everything be saved in this file.

For do it I use this code:

   Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

    Dim thefile As String = Application.StartupPath & "\SafetyBox.cfg"
    Dim lines() As String = System.IO.File.ReadAllLines(thefile)

    lines(1) = "Language_file=" & ComboBox1.Text
    If CheckBox1.Checked = True Then
        lines(2) = "Status1=" & "1"
    Else
        lines(2) = "Status1=" & "0"
    End If
    If CheckBox2.Checked = True Then
        lines(3) = "Status2=" & "1"
    Else
        lines(3) = "Status2=" & "0"
    End If
    System.IO.File.WriteAllLines(thefile, lines)

End Sub`

And this part working great. Status1 should be the status of checkbox1, while status2 is the status of checkbox2.

The code that is not working is:

 Dim path As String = Application.StartupPath & "\SafetyBox.cfg"
    If File.Exists(path) Then

        Using sr As StreamReader = New StreamReader(path)

            Dim linenew As String = sr.ReadLine()
            If linenew.Contains("\") Then
                TextBox1.Text = linenew



            Else
                MsgBox("Configura il programma da usare")
            End If

            Dim lineN As String = sr.ReadLine()
            If lineN.Contains("Language_file=") Then
                ComboBox1.Text = lineN.Split("=").Last()
            End If
            If lineN.Contains("Status1=1") Then
                CheckBox1.Checked = True
                CheckBox2.Checked = False

            ElseIf lineN.contains("Status1=0") Then
                CheckBox1.Checked = False
                CheckBox2.Checked = True

            End If



            If lineN.Contains("Status2=1") Then
                CheckBox1.Checked = False
                CheckBox2.Checked = True

            ElseIf lineN.Contains("Status2=0") Then
                CheckBox1.Checked = True
                CheckBox2.Checked = False
            End If
                sr.ReadToEnd()
            sr.Close()
        End Using

Can yOu let me understnd where is my mistake? Why when in the .cfg file is wrote correctly Status1=0 and Status2=1, when loading the program i always see checkbox1 checkd and not checkbox2?

Thanks




mercredi 23 mai 2018

Why can't I limit the number of checked checkboxes?

I have 4 checkboxes and I want to limit the selection up to 3. Did my google search, found a working one:

http://jsfiddle.net/vVxM2/

This is my code:

<html>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        var limit = 3;
        $('input.ko_chk').on('change', function(evt) {
           if($(this).siblings(':checked').length >= limit) {
               this.checked = false;
           }
        });
    </script>
    <body>
        <input type="checkbox" class="ko_chk" name="first" value="1"><br>
        <input type="checkbox" class="ko_chk" name="second" value="2"><br>
        <input type="checkbox" class="ko_chk" name="third" value="3"><br>
        <input type="checkbox" class="ko_chk" name="fourth" value="4">
    </body>
</html>

Still...

enter image description here

So, how is my code different?




CheckBox.setChecked() is getting executed but not shown on screen

I am using an onClickListener on a textview to setCheck() on a checkbox and saving the one value while clearing the last checked item in itemStateArray which is a SparseBooleanArray. The code is getting executed but the check box being checked is not shown.

textView.setOnClickListener(v -> {
            int adapterPosition = getAdapterPosition();
            if (!itemStateArray.get(adapterPosition, false)) {
                if (first) {
                    checkBox.setChecked(true);
                    first = false;
                    lastChecked = checkBox;
                } else {
                    if (checkBox.isChecked() && lastChecked != null) {
                        lastChecked.setChecked(false);
                        checkBox.setChecked(true);
                        lastChecked = checkBox;
                    }
                }
                itemStateArray.clear();
                itemStateArray.put(adapterPosition, true);

            } else {
                checkBox.setChecked(false);
                itemStateArray.clear();
                itemStateArray.put(adapterPosition, false);

            }
        });

I am setting the listener on the textview as I want to click on the larger textview as compared the smaller checkbox on the side of the screen.

Upon clicking the item and scrolling down and back up, the item is shown as checked. I am setting the checkbox as checked in the onBindViewHolder with the following code:

holder.bind(position);

The bind function to which I am passing the checked positions:

void bind(int position) {
            if (!itemStateArray.get(position, false)) {
                checkBox.setChecked(false);
            } else {
                checkBox.setChecked(true);
                lastChecked = checkBox;
            }
        } 

the checkbox being animated is not shown on the screen.




Extend check zone of a checkbox

I'm programming a menu with two checkboxes inside (mat-menu from Angular with native Javascript checkboxes) and if I'm not clicking exactly in the box that doesn't work, the menu is closing and the box not checked ...

By the way with the mat-menu I haven't found how to block the automatic closure of the menu when I click on it.

Do you have a solution ?




Revert checkbox change under treeTable in Primefaces

My application has a treeTable under Primfaces 6.1.1. Currently the application is using RequestContext.getCurrentInstance().update("myFormId:myTabViewId:myTreeTableId") to update the whole treeTable when the events select or unselect are triggered by ajax.

Due to performance issue when the treeTable contains so many nodes, I would like to update just the nodes that are affected by unselecting and selecting. Through searching, I found that there is no way to update just a part of treeTable, so I decided to update the treeTable-UI cell by cell by their Ids. This workaround works fine but I have the following problem:

when the user unselects a checkbox, a dialog will be shown to ask for confirmation, if the user clicks "No", the dialog will disappear and the application shouldn't do anything BUT the checkbox is not reverted back to the state "checked" although the internal CheckboxTreeNode.selected is still true.

I couldn't manage to update the checkbox in the UI by this workaround because the checkboxes are icons having no Ids and they are not found in the .xhml file.

I would like to ask if there is any way to update the checkbox-UI one by one on treeTable? Thanks.




Flutter checkbox unwanted touch space

I tried to create a login screen using flutter, there I added remember me checkbox, but I could not align it correctly,

Flutter checkbox took unwanted space around itself, for the provide good touch user experience.

This is the how my layout show,

enter image description here

Check below code,

        new Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  new Row(
                    children: <Widget>[
                      new Checkbox(
                        activeColor: Colors.grey,
                        value: _isChecked,
                        onChanged: (bool value) {
                          _onChecked(value);
                        },
                      ),
                      new GestureDetector(
                        onTap: () => print("Remember me"),
                        child: new Text(
                          "Remember me",
                          style: new TextStyle(color: Colors.white70),
                        ),
                      )
                    ],
                  ),
                  new Text(
                    "Forgot password ?",
                    style: new TextStyle(color: Colors.white70),
                  )
                ],
              ),




How to get and save checkboxs names in a list with tkinter, python 3.6.5

I would like to to use tkinter and checkboxs to make a selection of files in a directory and save those files names in a list when I press a button :

import speech_recognition as sr
import playsound
import os
import glob
import unidecode
import pickle
import random
import tkinter
from tkinter.constants import *

ldv=os.listdir("D:/FFOutput/")
i=0
ldv1=[]
while i<len(ldv):
    ldv1.append(unidecode.unidecode(ldv[i]))
    i=i+1
print(ldv1)

tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=10)
frame.pack(fill=BOTH,expand=1)
label = tkinter.Label(frame, text="choose file(s)")
label.pack(fill=X, expand=1)


a=0
while a<len(ldv1):
    bouton=tkinter.Checkbutton(tk, text=ldv1[a], command=print(ldv1[a]))
    a=a+1
    bouton.pack()

button = tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)

lr=[]

buttonregister = tkinter.Button(tk,text="Register checked files names in list lr and close tk")
buttonregister.pack(side=BOTTOM)

print(lr)

tk.mainloop()

When i click on buttonregister i would like to append files names in the list lr and close the frame.

Exemple : enter image description here In that exemple, I wish to print(lr) "['alors soyez pret.mp3','c'est bien.mp3'] in the shell when i click on the button.

Thank you




If/Else with two checkboxes checked - Javascript

A real simple javascript function I'm getting stuck with... (Have googled alot and can't make it fully work!).

Basiclly, I have two check boxes. And I went my disclaimer to disappear, (only when both boxes have been checked. (See full code below).

If only one/none boxes are not checked, the disclaimer should still appear. And the form submit button is disabled.

Everything works fine. I can make the disclaimer disappear and deactivate the button, if one box is checked. But seems to not do anything, with my if/else statement below.

Basically, the "if" in my if/else statement, is not checking for the right logic.

I've googled and tried lots of variations. But can't get this one working.
Thank you!

  var formInput = document.querySelector("input[name=terms]");
  var marketingInput = document.querySelector("input[name=marketing]");
  var cvSubmitButton = document.querySelector("input[type=submit]");
  var checkBoxDiv = document.getElementById("checkboxRow");
  var scfSubmitButtonBorder = document.querySelector(".scfSubmitButtonBorder");

  cvSubmitButton.classList.add('disabled');
  scfSubmitButtonBorder.style.cursor = "not-allowed";

  var legalClause = document.createElement('div');
  legalClause.innerHTML = "<div id='disclaimer'><br /><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div>";
  checkBoxDiv.appendChild(legalClause);


  // EVENTLISTENER

    var boxes = document.querySelectorAll('input[type=checkbox]:checked').length;

    formInput.addEventListener("change", function(){

     if((formInput.checked) && (marketingInput.checked)) {

      cvSubmitButton.classList.remove('disabled');
      checkBoxDiv.removeChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "pointer";
      console.log('checked');
     } else {

      cvSubmitButton.classList.add('disabled');
      checkBoxDiv.appendChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "not-allowed";
      console.log('not checked');
     }
  });




Not able to send sms in loop properly, sending multiple sms to single person by mistake

I'm trying to send sms to the absentees number using gridview in asp.net. the functionality goes as follows: - out of all students in a class, as the user unchecked the the students will be marked as absent and vice versa. - now the problem is that when I'm trying to uncheck a student and submit,, it sends me around 50 messages at once even though only one student is absent. it should send only the message to the absentees. Kindly help me out referring the below code of mine. Thanks in advance:

protected void InsertAttendence()
{
    DateTime systemdate2 = DateTime.Today.Date;
    foreach (GridViewRow row in gvStudents.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkAttendance = row.FindControl("chkAttendence") as CheckBox;
            string attendanceStatus = chkAttendance.Checked ? "Present" : "Absent";
            string Class = ((row.FindControl("lblclass") as Label).Text.Trim());
            string StudentName = ((row.FindControl("lblname") as Label).Text.Trim());
            string STSNO = ((row.FindControl("lblstsno") as Label).Text.Trim());
            string Mobile = ((row.FindControl("lblmobile") as Label).Text.Trim());
            string Division = ((row.FindControl("lbldiv") as Label).Text.Trim());
            //string sttendenceDate = (this.txtDate.Text.Trim());
            string constring = ConfigurationManager.ConnectionStrings["stjosephconnect"].ConnectionString;
            using (SqlConnection conInsert = new SqlConnection(constring))
            {
                try
                {
                    string query = "INSERT INTO studentattendance(attdate, stsno, name, mobile, class, div, attendance, remarks, status, rem) "
                                   + "VALUES(@attdate, @stsno, @name, @mobile, @class, @div, @attendance, @remarks, @status, @rem)";
                    using (SqlCommand cmd = new SqlCommand(query, conInsert))
                    {
                        conInsert.Open();
                        cmd.Parameters.AddWithValue("@attdate", systemdate2);
                        cmd.Parameters.AddWithValue("@stsno", STSNO);
                        cmd.Parameters.AddWithValue("@name", StudentName);
                        cmd.Parameters.AddWithValue("@mobile", Mobile);
                        cmd.Parameters.AddWithValue("@class", Class);
                        cmd.Parameters.AddWithValue("@div", Division);
                        cmd.Parameters.AddWithValue("@attendance", attendanceStatus);
                        cmd.Parameters.AddWithValue("@remarks", "Test Remarks!");
                        cmd.Parameters.AddWithValue("@status", "1");
                        cmd.Parameters.AddWithValue("@rem", "0");
                        int i = cmd.ExecuteNonQuery();
                        if (i > 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Data saved successfully, Thank-You!');", true);
                            chkAttendance.Checked = false;
                            using (SqlConnection GetAbsentCon = new SqlConnection(constring))
                            {
                                string TodaysDate = DateTime.Now.ToString("yyyy-MM-dd");
                                GetAbsentCon.Open();
                                using (SqlCommand GetAbsentCmd = new SqlCommand("select mobile from studentattendance where  convert(varchar(10), attdate, 120) = '" + TodaysDate + "' and attendance='Absent'", GetAbsentCon))
                                {
                                    SqlDataReader dr = GetAbsentCmd.ExecuteReader();
                                    while (dr.Read())
                                    {
                                        numbers = dr["mobile"].ToString().TrimStart('0');
                                        SendSMS();
                                    }
                                    GetAbsentCon.Close();
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('There was some error in connection');", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("<script language='javascript'>alert('" + Server.HtmlEncode(ex.Message.ToString()) + "')</script>");
                }
                finally
                {
                    conInsert.Close();
                }
            }
        }
    }
}

Please help me out from this awkward situation..




How to make progress bar work on multiple checkbox checked?

I have made a progress bar increment on checkbox checked. It works fine with single group of checkboxes but with multiple group of checkboxes it does not work as aspected.




mardi 22 mai 2018

Select Checkbox on website dropdown.

I have this:

id="ctl32_ctl04_ctl07_divDropDown_ctl32" type="checkbox" name="ctl32$ctl04$ctl07$divDropDown$ctl32" onclick="$get('ctl32_ctl04_ctl07').control.OnValidValueClick(this, 'ctl32_ctl04_ctl07_divDropDown_ctl00');" /><label for="ctl32_ctl04_ctl07_divDropDown_ctl32">Product</label></span></td>

And I'm trying to select the checkbox.

I've tried everything I can to select it. At one point I got it clicked but it didn't really select it so much as appearing to put a check in the box.

This is something I found and had hopes for but maybe I'm using it wrong.

 Set elems = HTMLdoc.getElementById("ctl32_ctl04_ctl07_divDropDown_ctl00")

        For Each e In elems
            If (e.getAttribute("value") = "ctl32_ctl04_ctl07_divDropDown_ctl00") Then
                e.Click
                Exit For
            End If
        Next e

I'd appreciate any help.




How to get the value of unchecked and checked checkboxes

I have a list of checkboxes and want to return their values on submit. I can do this easily for the checked ones, but not for the unchecked? Here's my code so far:

<input type="checkbox" checked="checked" name="addressBooks[]" value="<?php echo $id; ?>">

<?php
if (isset($_POST['submit'])) {
    address_books();
}
function address_books() {
    $book = $_POST['addressBooks'];
    if (!isset($book)) {
        $N = count($book);

        echo("You did not select $N book(s): ");
        for ($i = 0; $i < $N; $i++) {
            echo($book[$i] . " ");
        }
    } else {
        $N = count($book);

        echo("You selected $N book(s): ");
        for ($i = 0; $i < $N; $i++) {
            echo($book[$i] . " ");
        }
    }
}




How to get the index of CheckBox inside a ListView?

I am trying to update a JFXListView of JFXCheckBoxes the problem is when i do listview.getItems().indexOf("checkbox1") it always return -1. If i cant get the index of each JFXCheckBox i can just do listview.getItems().remove(indexOfCheckBox) ?




Magetno how add checkbox in contact form?

I must add checkbox in Contact form in Magetno (Magento wer. 1.8.1), I searching tutorials on Google but I found solution ... It is easy way to do this ?

Many Thanks Wojtek




lundi 21 mai 2018

MVC Calendar pops up when checkbox clicked

The calendar control pops up when clicking the checkbox. This is a ASP.NET Zero, ASP.NET Boilerplate project. The latest date control selected will reappear when the checkbox is clicked. Any clue as to why the calendar pops up when the checkbox is clicked?

@Html.TextBoxFor(m => m.Date1, "{0:yyyy-MM-dd}", new { type = "date", @class = "form-control", id = "Date1"})
@Html.TextBoxFor(m => m.Date2, "{0:yyyy-MM-dd}", new { type = "date", @class = "form-control", id = "Date2" })
@Html.CheckBoxFor(m => m.ISChecked, new { @class = "icheck", id = "Checkbox1" })

I don't haven enough reputation points to embed picture links:

https://i.imgur.com/WroeuiD.jpg

https://i.imgur.com/wMMPIWz.jpg




Knockout disabling check boxes within a for loop upon change

I have a list of check boxes in an observable array and I want to control the enabling and disabling of the check boxes when they are selected, per row. For example, when entering for the first time in the dialog, only the "Copy Form" and "Unlink" would be enabled. If "Copy Form" is checked, then the "Workflow" and "Reporting" would be enabled, but the "Unlink" we would be disabled. If "Unlink" is checked, then all other check boxes would be cleared of values and disabled.

Here is a screen shot of what I am trying to accomplish:

enter image description here

The code (removed some stuff that just complicates what I am trying to describe):

Html:

<tbody data-bind="foreach: SubAccountsToCopy()">
<tr>
    <td class="col-sm-4" data-bind="text: linkedAccountName"></td>
    <td class="col-sm-1" data-bind="text: linkedVersion"></td>
    <td class="col-sm-1" data-bind="text: version"></td>
    <td>
        <input style="vertical-align: middle" id="copyForm" type="checkbox" data-bind="checked: copyForm, attr: { 'id': 'copyForm' + $index()}">&nbsp;
        <label data-bind="attr: { 'for': 'copyForm' + $index()}">Copy Form</label>
    </td>
    <td title="Also copy the Form Workflow " style="width:100px;">
        <input style="vertical-align: middle" type="checkbox" data-bind="checked: copyWorkflow, attr: { 'id': 'copyWorkflow' + $index()}" />&nbsp;
        <label data-bind="attr: { 'for': 'copyWorkflow' + $index()}">Workflow</label>
    </td>
    <td title="Also copy the Report Settings " style="width:100px;">
        <input style="vertical-align: middle" type="checkbox" data-bind="checked: copyReportSettings, attr: { 'id': 'copyReportSettings' + $index()}" />&nbsp;
        <label data-bind="attr: { 'for': 'copyReportSettings' + $index()}">Reports</label>
    </td>
    <td title="Will unlink the SubAccount form from the Master Account " style="width:100px;">
        <input style="vertical-align: middle" type="checkbox" data-bind="checked: unlink, attr: { 'id': 'unlink' + $index()}" />&nbsp;
        <label data-bind="attr: { 'for': 'unlink' + $index()}">Unlink</label>
    </td>
</tr>

The javascript side is an JSON array mapped to the observable.




disable textboxfor using a checkboxfor razor mvc and jquery

I am trying to disable/enable an @Html.TextBoxFor in razor using an @Html.CheckBoxFor

I have defined my CheckBoxFor in this manner:

@Html.CheckBoxFor(m => m.ResYearChecked, new { Name = "ResYearChecked", id = "ResYearChecked" })

@Html.TextBoxFor(m => m.SearchResYear, new { Name = "SearchResYear", id = "SearchResYear" })

and I am trying to call the script:

<script>
    $('ResYearChecked').change(function () {
        $("SearchResYear").prop("disabled", !$(this).is(':checked'));
    });
</script>

Do I need to add the onclick attribute to the CheckBoxFor?