samedi 31 mars 2018

Checkboxes in RecyclerView is unchecked when scrolled

Suppose I check an item's checkbox, that also updates the ischecked column in the database with the respective item's id. Then I scroll down and go back to the top, then the top most item's checkbox is automatically unchecked and database is also updated. Even suppose I check two items on the top, when I scroll down the two bottom most items' checkboxes are also checked automatically. How can I resolve this problem in recyclerView?

// costume adapter class
public class DataBeanAdapter extends RecyclerView.Adapter<DataBeanAdapter.ViewHolder> implements View.OnCreateContextMenuListener {
    public List<dataBean> items;
    public int itemLayout;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo contextMenuInfo) {
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
        menu.add(0, v.getId(), 0, "SMS");
    }

    public DataBeanAdapter(List<dataBean> items, int itemLayout) {
        this.items = items;
        this.itemLayout = itemLayout;
    }

    @Override
    public DataBeanAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        // On loading the activity recyclerview, setting properties to each list items

        // fetch id with the given item postition
        Cursor cc = myDB.getCursorByPosition(position);
        String idd = cc.getString(cc.getColumnIndex("_id"));


        String taskval = myDB.getTaskValue(idd);

        dataBean item = items.get(position); // trash
        holder.tasks.setText(taskval.trim());

        String iscGet = myDB.getischecked(idd); // false by default

        if (items.get(position).getChecked() == true) {
            holder.isc.setChecked(true);
            items.get(position).setChecked(true);
        } else if (items.get(position).getChecked() == false) {
            holder.isc.setChecked(false);
            items.get(position).setChecked(false);
        } else {
            //leave
        }


        // set inflated checkbox to null
        //   holder.isc.setOnCheckedChangeListener(null);
        //  holder.isc.setChecked(myAdapter.items.contains(items.get(position)));

        holder.isc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Boolean ischecked = items.get(position).getChecked();
                if (ischecked == false) {
                    Cursor cx = myDB.getCursorByPosition(position);
                    String idx = cx.getString(cx.getColumnIndex("_id"));
                    myDB.updateCheck(idx);
                    items.get(position).setChecked(true);

                } else {
                    Cursor cx = myDB.getCursorByPosition(position);
                    String idx = cx.getString(cx.getColumnIndex("_id"));
                    myDB.updateunCheck(idx);
                    items.get(position).setChecked(false);
                }
            }
        });


        holder.tasks.setOnCreateContextMenuListener(MainActivity.this);
        holder.more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Cursor c = myDB.getCursorByPosition(position);
                String id = c.getString(c.getColumnIndex("_id"));

                Intent intent = new Intent(MainActivity.this, edit.class);
                intent.putExtra("taskpos", Integer.toString(position));
                intent.putExtra("taskid", id);
                startActivity(intent);

            }
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tasks;
        public CheckBox isc;
        public ImageView more;

        public ViewHolder(View itemView) {
            super(itemView);
            tasks = (TextView) itemView.findViewById(R.id.taskline);
            isc = (CheckBox) itemView.findViewById(R.id.cbox);
            more = (ImageView) itemView.findViewById(R.id.more);
            // https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()
            //  this.setIsRecyclable(false); /// prevents checkbox misbehaving


        }

    }
}

public List<dataBean> getAllData() {
    List<dataBean> list = new ArrayList<>();
    Cursor cursor = myDB.SelectData();


    while (cursor.moveToNext()) {

        int tasks = cursor.getColumnIndex("tasklist");
        int ischecked = cursor.getColumnIndex("ischecked");
        String tasksv = cursor.getString(tasks);
        String ic = cursor.getString(ischecked);
        dataBean bean = new dataBean(tasksv, Boolean.parseBoolean(ic));
        list.add(bean);

    }

    return list;
}




TextBox data to CheckBox label

In my android app, I want to provide a text box to input a name and save it. Later I want to retrieve the text as checkbox label in other activity. So.. how can I do it? Like multiple names will generate multiple checkbox in next activity..

Thank you in advance..




vendredi 30 mars 2018

How to create a checkbox radio with JS only and a function to uncheck all boxes?

I want to create a checkbox radio like this: 1 div that contains 3 labels and their radio inputs. But, I want to create these HTML elements with JS only.

I tried this and I don't think my .checkboxradio(); worked when I did it.

I also have a button with an onclick function where I want to make all inputs unchecked, and for the whole radio to be refreshed. I couldn't figure this part out.

Help?




JavaFX: Checkbox labels in a GridPane are not visible

The container is a GridPane, where checkboxes are added with:

gridPane.add(checkbox, columnIndex, rowIndex);

Each checkbox was initialized with a label:

final CheckBox checkbox = new CheckBox(label);
checkbox.setDisable(true);

The result is that there are all crowded. How can I make them more expanded?

enter image description here

The whole thing does have a scrollbar ...




How can we create 2 dimensional checkbox view in a layout that adjust according to the screen size?

I have successfully created 2d checkboxes but i am facing orientation problem. I want to adjust every row accordingly to the portrait or landscape mode so that the heading and the checkbox rows are always alligned. Here is my screen2d CheckBox Screen




Laravel Sending email to all selected checkboxes

I am sending email to all members at once. Now i am trying to send emails to selected users. How can i do that?

This is my existing mailController

public function send_mail()
{
    $joinus = new Joinus;
    $mails = Joinus::all();
    $array = array();

    foreach ($mails as $mail)
    {
        array_push($array, $mail->email);

    };

    Mail::to($array)->send(new SendMail($joinus->email))->delay(60);

I am getting all users from Joinus model. Adding them to an array and sending emails to all arrays child. Am i need to add smt to SendMail? Or do i have to use jquery? If anyone give me code example i'll be gladful. This isn't to hard question. But i just didn't make it out.

Also this is the checkbox's place

@can('delete',app($dataType->model_name))
  <td>
    <input type="checkbox" name="row_id" id="checkbox_" value="">
   </td>
@endcan




ASP.NET Cannot uncheck checkbox

i have this so popular problem that i really cannot fix. I have not yet found a fix for this even if i searched a lot on the web, so please do not mark this as a duplicate since it is not. here is what i am trying to do: I create a GridView based on a XML file, so i create columns and rows based on it. Each cell has got a checkbox that might be check or not depending on some vaules in the xml. I can make the checkboxes already checked or uncheck but here comes a problem. While if a checkbox is not checked and i click it everything goes well, when it is checked and i want to uncheck it, the checkbox just change the check on it without performing action it should do (and it results that its state did not change). How can i fix this? it is really annoying.

Here is some code, sorry if it is not so readable or well made.

    public partial class AggiungiDisponibilita : System.Web.UI.Page
{
    string nomeProclamatore;
    string id;
    string colonna, colonna_c2, colonna_c3, riga, riga_c2, riga_c3;
    /// <summary>
    /// stringe per l'inserimento delle disponibilita
    /// </summary>
    string data, turno;

    string prog, name;
    string mese_prossimo = Home.mese_prossimo;

    protected void Home_Click(object sender, EventArgs e)
    {
        Response.Redirect("Home.aspx?Aggiorna=Nomi");
    }

    protected void selectAll_Click(object sender, EventArgs e)
    {
        var programma = new XmlDocument();
        programma.Load(Server.MapPath(Resources.DisponibilitaXML));
        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
        foreach (XmlNode giorno in mese)
            foreach (XmlElement turni in giorno)
            {
                turni.InnerText += nome.Text + ",";
            }
        programma.Save(Server.MapPath(Resources.DisponibilitaXML));
        Response.Redirect("AggiungiDisponibilita.aspx?Name=" + nomeProclamatore.Replace(" ", "+"));

    }

    protected void deselectAll_Click(object sender, EventArgs e)
    {
        var programma = new XmlDocument();
        programma.Load(Server.MapPath(Resources.DisponibilitaXML));
        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
        foreach (XmlNode giorno in mese)
            foreach (XmlElement turni in giorno)
            {
                string[] nomi = turni.InnerText.Split(',');
                var numero_volte_nomi = nomi.GroupBy(v => v);
                foreach (var nomep in numero_volte_nomi)
                    if (nomep.Count() >= 1 && nomep.Key.ToString() == nome.Text) //il nome appare più di una volta
                    {
                        //rimuoverlo tutte le volte tranne 1 
                        turni.InnerText = turni.InnerText.Replace(nomep.Key.ToString() + ",", "");
                    }
            }
        programma.Save(Server.MapPath(Resources.DisponibilitaXML));
        Response.Redirect("AggiungiDisponibilita.aspx?Name=" + nomeProclamatore.Replace(" ", "+"));
    }

    protected void Gestione_Click(object sender, EventArgs e)
    {
        Response.Redirect("GestioneFratelli.aspx");

    }

    protected void Modifica_Click(object sender, EventArgs e)
    {
        string nome = "";
        if (Session["UserName"] != null)
            try
            {
                nome = Convert.ToString(Session["UserName"]);
            }
            catch (HttpException ex)
            {
            }
        Response.Redirect("ModificaFratello.aspx?Name=" + nome.Replace(" ", "+"));
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["UserName"] != null)
        {

            if (!Session["UserName"].Equals("JonathanImperato"))
            {
                Gestione.Visible = false;
                Homes.Text = "Logout";
            }
            if (!Session["UserName"].Equals(Request.QueryString["Name"]))
            {
                Response.Redirect("Login.aspx", false);
            }
            prog = Server.MapPath(Resources.DisponibilitaXML);
            Mese.Text = "Disponibilita per il mese di: " + Variables.Mese_Succ(DateTime.Now.Month);
            name = Request.QueryString["Name"];
            id = name;

            nomeProclamatore = name.Replace("+", " ");

            nome.Text = nomeProclamatore;
        }
        else Response.Redirect("Login.aspx", false);

    }

    void loadData()
    {
        // instantiate XmlDocument and load XML from file
        XmlDocument doc = new XmlDocument();
        doc.Load(prog); //Percorso file xml



        DataTable dt = new DataTable();
        dt.Columns.Add("Data");
        foreach (XmlNode xns in doc.DocumentElement)
        {
            if (xns.Name == Variables.Mese_Succ(DateTime.Now.Month)) ///IMPLEMENTARE SELEZIONE AUTOMATICA DEL MESE IMPORTANTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 

                foreach (XmlNode xn in xns)
                {
                    string tagName = xn.Name;
                    dt.Rows.Add(tagName);

                }
        }


        dt.Columns.Add("Mattina Turno 1", typeof(Boolean));
        dt.Columns.Add("Mattina Turno 2", typeof(Boolean));
        dt.Columns.Add("Pomeriggio", typeof(Boolean));



        GridView1.DataSource = dt;
        GridView1.DataBind();

        //nascondo tutti i checkbox i cui turni non esistono una volta che tutti i checkbox sono stati inseriti nella GridView
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                foreach (CheckBox checks in row.Cells[i].Controls)
                {
                    int tooltip_lunghezza = checks.ToolTip.Split(',').Count();
                    if (tooltip_lunghezza != 2)
                    {
                        var programma = new XmlDocument();
                        programma.Load(Server.MapPath(Resources.ProgrammaXML));
                        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
                        // MOSTRA IN AUTOMATICO SOLO I TURNI CHE OGNI GIORNO HA NEL FILE XML, AUTOMATICITA SENZA CONTROLLO DI OGNI GIORNO, FA TUTTO SULLA BASE DELL'EXML
                        //FUNZIONA ANCHE CON I GIORNI AGGIUNTI SUCCESSIVAMENTE
                        string data2 = row.Cells[0].Text;
                        XmlNode giorno = mese.SelectSingleNode(data2);
                        checks.Visible = false;
                        foreach (XmlNode turni in giorno.ChildNodes)
                        {
                            string nome_turno = turni.Name;
                            if (checks.ToolTip.Contains(turni.Name.Replace("_", " ")) && checks.ToolTip.Contains(data2))
                                checks.Visible = true;
                        }
                    }
                    else checks.Visible = false; //nascondo quelli finti
                }
            }
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            prog = Server.MapPath(Resources.DisponibilitaXML);

            id = Request.QueryString["Name"];

            nomeProclamatore = id.Replace("%20", " ");

            nome.Text = nomeProclamatore;
            nome.Text = mese_prossimo;

            loadData();

        }
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        inserisciDisponibilitaGiaDate(e);

    }

    void inserisciDisponibilitaGiaDate(GridViewRowEventArgs e)
    {
        string test;
        CheckBox chk1 = new CheckBox();
        CheckBox chk2 = new CheckBox();
        CheckBox chk3 = new CheckBox();
        prog = Server.MapPath(Resources.DisponibilitaXML);
        var doc = XElement.Load(prog); //Percorso file xml
        //foreach(GridViewRow row in GridView1.Rows)
        // check if it's not a header and footer
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Variables.data_turno = test = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Data"));
            test = Variables.data_turno;

            Variables.row_index = Convert.ToInt32(e.Row.RowIndex);

            chk1.CausesValidation = false;
            chk1.AutoPostBack = true;
            chk1.Checked = false;

            chk1.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna = GridView1.HeaderRow.Cells[1].Text;
            chk1.ID = colonna + e.Row.RowIndex;
            chk1.ViewStateMode = ViewStateMode.Enabled;
            chk1.ToolTip = Variables.row_index + "," + test + "," + colonna + ",false";


            //se è gia stata data la disponibilita metto il checkbox su cliccato
            if (test.Length > 0 && colonna.Length > 0)
            {
                var saveGame = doc
                //.Element("Anno_"+DateTime.Now.Year.ToString())
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna.Replace(" ", "_"))
                .Single();

                string esiste_gia = saveGame.Value;
                if (esiste_gia.Contains(nomeProclamatore))
                {
                    chk1.Checked = true;
                    chk1.ToolTip = Variables.row_index + "," + test + "," + colonna + ",true";
                }
            }
            //-------------------------------------------- 

            chk2.CausesValidation = false;
            chk2.AutoPostBack = true;
            chk2.Checked = false;
            chk2.ViewStateMode = ViewStateMode.Enabled;


            chk2.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna_c2 = GridView1.HeaderRow.Cells[2].Text;

            chk2.ID = colonna_c2 + e.Row.RowIndex;
            chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c2 + ",false";

            //se è gia stata data la disponibilita metto il checkbox su cliccato 
            if (test.StartsWith("mer") && !test.Contains("B"))
            {
                var saveGame2 = doc
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna_c2.Replace(" ", "_"))
                .Single();
                if (saveGame2.Value != null && saveGame2.Value.Contains(nomeProclamatore))
                {
                    chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c2 + ",true";
                    chk2.Checked = true;
                }
            }
            //-------------------------------------------- 

            chk3.CausesValidation = false;
            chk3.AutoPostBack = true;
            chk3.ViewStateMode = ViewStateMode.Enabled;

            chk3.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna_c3 = GridView1.HeaderRow.Cells[3].Text;
            chk3.ID = colonna_c3 + e.Row.RowIndex;
            chk3.Checked = false;

            chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",false";

            if (test.StartsWith("sab") && !test.Contains("B") || test.StartsWith("dom") && !test.Contains("B"))
            {
                //se è gia stata data la disponibilita metto il checkbox su cliccato 
                var saveGame3 = doc
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna_c3.Replace(" ", "_"))
                .Single();

                if (saveGame3.Value != null && saveGame3.Value.Contains(nomeProclamatore))
                {
                    chk3.Checked = true;
                    chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                }
            }
            // if (!test.StartsWith("sab")) // aggiungo il terzo check 
            //     chk3.Enabled = false;

            //PER I GIORNI ECCEZIONALI, INSERISCO IL CHECKBOX ATTIVO SE è GIA STATA DATA LA DISPONIBILITA.........
            if (test.StartsWith("lun") || test.StartsWith("gio") || test.Contains("B")) //quindi sono giorni aggiunti manualmente
            {
                //VISUALIZZO CHE TURNI SONO STATI IMPOSTATI QUANDO è STATO AGGIUNTO IL GIORNO
                var programma = new XmlDocument();
                programma.Load(Server.MapPath(Resources.DisponibilitaXML));
                var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
                var giorno = mese.SelectSingleNode(test);
                foreach (XmlNode turni in giorno.ChildNodes)
                {
                    string nome_turno = turni.Name;
                    //se è gia stata data la disponibilita metto il checkbox su cliccato 
                    var saveGame4 = doc
                    .Element(Variables.Mese_Succ(DateTime.Now.Month))
                    .Elements(test.Replace(" ", "_"))
                    .Elements(nome_turno.Replace(" ", "_"))
                    .Single();
                    if (nome_turno == "Mattina_Turno_1" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk1.Checked = true;
                        chk1.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                    if (nome_turno == "Mattina_Turno_2" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk2.Checked = true;
                        chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                    if (nome_turno == "Pomeriggio" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk3.Checked = true;
                        chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                }
            }


            e.Row.Cells[1].Controls.Add(chk1); // add checkbox to second column
            e.Row.Cells[2].Controls.Add(chk2); // aggiungo il secondo check 
            e.Row.Cells[3].Controls.Add(chk3); //il terzo
        }

    }

    bool isFirstCheckClick = true;
    bool isXmlOpened = false; //variabile per vedere se sto già aggiungendo una disponibilita, serve a non mandare in crash

    private void Cb_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        bool isChecked = checkBox.Checked;
        nome.Text = checkBox.ToString() + isChecked.ToString();
        if (!isXmlOpened && sender != null)
        {
            {
                isXmlOpened = true;
                string info = ((CheckBox)sender).ToolTip.ToString();
                string[] selezione = info.Split(',');
                string data_selezione = selezione[0];

                string turno_selezione = selezione[2];
                id = Request.QueryString["Name"];
                id = id.Replace("+", " ");

                data_selezione = GridView1.Rows[Convert.ToInt32(data_selezione)].Cells[0].Text;
                turno_selezione = turno_selezione.Replace(" ", "_");

                //verifico che è un giorno che ha il pomeriggio se è stato selezionato il pomeriggio
                if (turno_selezione != "Pomeriggio" && turno_selezione != "Mattina_Turno_2" || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("dom") || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("sab") || turno_selezione == "Mattina_Turno_2" && data_selezione.StartsWith("mer"))
                {
                    //l'ho appena selezionato quindi voglio aggiungere il nome
                    if (isChecked || ((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        //da scegliere se usare metodo sopra o sotto 

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);
                        checkBox.Checked = true;
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else //if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    //else Cb_CheckedChanged(checkBox, null);
                    //    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else if (data_selezione.StartsWith("lun") || data_selezione.StartsWith("gio"))
                {
                    if (((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);

                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else
                {
                    //ClientScript.RegisterStartupScript(this.GetType(), "Non esiste", "alert('Non esiste il turno " + turno_selezione + " per il giorno "+ data_selezione +".')", true);

                    // loadData();
                    //   Response.Redirect(
                    //           "AggiungiDisponibilita.aspx?Name=" + id.Replace(" ", "+"));

                }
                isXmlOpened = false;
                // setCheckedAgain(((CheckBox)sender).ID);
            }

        }
    }
}

The checking part here:

        private void Cb_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        bool isChecked = checkBox.Checked;
        nome.Text = checkBox.ToString() + isChecked.ToString();
        if (!isXmlOpened && sender != null)
        {
            {
                isXmlOpened = true;
                string info = ((CheckBox)sender).ToolTip.ToString();
                string[] selezione = info.Split(',');
                string data_selezione = selezione[0];

                string turno_selezione = selezione[2];
                id = Request.QueryString["Name"];
                id = id.Replace("+", " ");

                data_selezione = GridView1.Rows[Convert.ToInt32(data_selezione)].Cells[0].Text;
                turno_selezione = turno_selezione.Replace(" ", "_");

                //verifico che è un giorno che ha il pomeriggio se è stato selezionato il pomeriggio
                if (turno_selezione != "Pomeriggio" && turno_selezione != "Mattina_Turno_2" || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("dom") || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("sab") || turno_selezione == "Mattina_Turno_2" && data_selezione.StartsWith("mer"))
                {
                    //l'ho appena selezionato quindi voglio aggiungere il nome
                    if (isChecked || ((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        //da scegliere se usare metodo sopra o sotto 

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);
                        checkBox.Checked = true;
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else //if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    //else Cb_CheckedChanged(checkBox, null);
                    //    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else if (data_selezione.StartsWith("lun") || data_selezione.StartsWith("gio"))
                {
                    if (((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);

                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else
                {
                    //ClientScript.RegisterStartupScript(this.GetType(), "Non esiste", "alert('Non esiste il turno " + turno_selezione + " per il giorno "+ data_selezione +".')", true);

                    // loadData();
                    //   Response.Redirect(
                    //           "AggiungiDisponibilita.aspx?Name=" + id.Replace(" ", "+"));

                }
                isXmlOpened = false;
                // setCheckedAgain(((CheckBox)sender).ID);
            }

        }
    }

Thanks in advance.




return select box and checkbox through ajax

I want to show select boxes and check boxes(as checked), from an AJAX response. I am passing a string and then exploding to get array results for select boxes. How can I do this with checkboxes too.

in escalation_ajax,

echo '<option value="'.$id.'">'.$reporting_head.'</option>'.",".'<option value="'.$des_id.'">'.$des_name.'</option>'.",".'<option value="'.$designation_email.'">'.$rep_head.'</option>' ;

and escalation.php

 <b>CC To:</b><br>
     <?php 

           $sqlrep = mysql_query("SELECT id, reporting_head FROM tbl where level > 0  GROUP BY reporting_head");
                  while ($rows1 = mysql_fetch_assoc($sqlrep)){   
                          $rep_id2    = $rows1['id']; 
                     $repname2    = $rows1['reporting_head'] ;

             echo "<input type='checkbox' name='cc2' value='".$rep_id2."'> ". $repname2 ."<br>";
         }

?>

<script type="text/javascript">
$(document).ready(function()
{  

$("#desig").change(function()
{
var designationname2 = $(this).find("option:selected").text()
var id=$(this).val();
var dataString = { 'id': id , 'designationname2': designationname2};

$.ajax
({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html)
{

var data = html.split(",");
$("#rephead").html("");
$('#rephead').append(data[0]);
$("#rephead1").html("");
$('#rephead1').append(data[0]);
$("#rephead2").html("");
$('#rephead2').append(data[0]);
$('#dd').html("");
$('#dd').append(data[1]);
$('#rephead3').html("");
$('#rephead3').append(data[2]);

}
});
});
});
</script>




jeudi 29 mars 2018

Checkboxes have a slightly different position in Firefox

Here's the Codepen link: https://codepen.io/karlomajer/pen/pLajad

My problem is that when you add some todos, in Chrome you can see that the checkboxes are properly aligned with the toggle all button (the ❯ symbol rotated by 90 degrees) but in Firefox they aren't and you can clearly see that the checkbox in Firefox isn't properly centered inside it's grid cell while in Chrome it is.

I noticed that <div class="pretty p-icon p-round"> (the checkbox) is 22.5 x 20 in Chrome but 30 x 20 in Firefox.

My todos are stored inside ul as a div (I wasn't thinking clearly while forming them and I will re do it properly later).

I'm using pretty-checkbox to make my checkboxes.

Todos:

ul > div {
  display: grid;
  grid-template-columns: 50px 1fr 50px;
  border-bottom: 1px solid #ededed;
  align-items: center;
}

Checkbox styling:

ul > div > div {
  justify-self: center;
  transform: scale(1.25);
}

I had to set the margins of .pretty to 0 because by default it has a margin-right of 1em:

.pretty {
  margin: 0;
}

Here's the checkbox structure for pretty-checkbox that I'm using:

<div class="pretty p-icon p-round">
  <input type="checkbox" class="checkbox">
  <div class="state">
    <i class="icon mdi mdi-check"></i>
    <label></label>
  </div>
</div>




android OptionsMenu checkable item: change without clicking

I have an options menu which contains one checkable item besides other items.

This is how I set that item checked and store the value inside onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_uploadCurrList) {
        return true;
    } else if (id == R.id.action_downloadCurrList) {
        return true;
    } else if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_sort_cat) {
        item.setChecked(!item.isChecked());
        catSort = item.isChecked();
        saveSortState(catSort);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

The value of catSort is set inside onCreateOptionsMenu. That's working fine.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_shopping_list, menu);
    menu.findItem(R.id.action_sort_cat).setChecked(catSort);
    return true;
}

But now, I want to update the isChecked() of that menu item if catSort changed at runtime. I want to do that before the user opens menu. How can I do that? It seems like I can't call setChecked() anywhere else but I have to update that checkbox if my boolean variable changes.




I need to unlock button when ckechbox is cheked

i need to block the button and unlock it when the checkbox is checkedenter image description here

here is a code enter image description here

but it doesnt work. Pls help guys i need the guaranted solution. PS ty for help




JavaScript conditions for checkbox OnLoad

I have a checkbox which determins to hide or make elements vidible. My question is there a way to also include if the checkbox was Originally unchecked on the page load to permanantly remove those elements so they can't be recalled, otherwise continue what is currently below? Hope that makes sense.

function myEmail() {
    var emailBox = document.getElementById("checkemail");
    var emailradios = document.getElementById("emailradios");
    var emailOptOutSix = document.getElementById("emailOptOutSix");
    var emailOptOutForever = document.getElementById("emailOptOutForever");

    if (emailBox.checked == true){
        emailradios.style.visibility = "hidden";
        emailforever.style.visibility = "hidden";
        emailOptOutSix.checked = false;
        emailOptOutForever.checked = false;

    } else {
       emailradios.style.visibility = "visible";
       emailforever.style.visibility = "visible";
    }
}




CheckBox and TextBox Control

I have an checkbox and textbox and DataGridView, I do not want to send data to the DataGridView when I click the CheckBox When I click on the button, send other text boxes, but even if the textbox is full when I click on the textbox. anyone help me please?




change default "true" / "false" values of a checkbox after form submiting

I would love to get rid of the standard "true" or "false" value of a checkbox when it is checked / unchecked and sent through a form... I wrote this little script but can't make it working, I am obviousliy new to code :)

In short: for a checked checkbox, instead of "true" I would love to have "Réservé" and instead of "false" I would love to have "Non Réservé"... is that possible ?

Have a look at my jsfiddle if you want:

http://jsfiddle.net/anthonysalamin/JySSN/207/

jquery

// wait for DOM to be ready
$(document).ready(function() {

  //define the variable for the checkboxes on the page
  var allCheckboxes = $("input:checkbox[class=outsider]");

  //calls the append function on form submission
  $("#form-element").submit(function(event) {

    $(allCheckboxes).on('click', function() {

    $(this).val(this.checked ? Réservé : Non Réservé);

      alert($(this).val()); 
      event.preventDefault();
    });
  });
});

HTML

<form id="form-element">
  <input type="checkbox" class="outsider" />
  <input type="submit" value="Send" data-wait="Wait..." />
</form>




How to remove a div containing a checkbox with a specific id?

I have different checkboxes generated dynamically. Each checkboxes are contained within a div.

I would like to do the following action with jquery:

If a checkbox has an id="aucune", then remove its container (the div containing the checkbox with the id="aucune") from the html page.

I tried the following code:

// wait for DOM to be ready
$(document).ready(function() {
  var empty = $("input:checkbox[id=aucune]");
  if (empty == true) {
    $(this).parent().remove();
  }
});

Here is a the very simplified html:

<div class="wrapper-checkbox">
  <input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
    <label for="xxx">xxx</label>
</div>

<div class="wrapper-checkbox">
  <input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
    <label for="aucune">aucune</label>
</div>

Here is my codepen: I am quite new to code, I apologize for my silly simple question.




iTextSharp Checkbox disappers in pdf when saving

I'm using itext sharp to fill my form fields on my template with values. Some of this fields should be flatten so that the user can't edit it. The rest of the fields should be filled by the user and my program can read out the data and insert it in the database.

My Solution works fine with Abobe Reader DC, but i have problems with Adobe Reader X An update of the version on the clients isn't possible.

So i enabled usage rights in the pdf template. Problem is that with itextsharp i have to enable append on the PdfStamper If this is enabled it's not possible to flatten a part of the form because of the Adobe signature on the document.

Now i have following idea: I split my template in two documents. The first document is filled by my code and Formflattening is true.

Following Code:

            MemoryStream outstream = new MemoryStream();

            Document document = new Document();
            PdfSmartCopy writer = new PdfSmartCopy(document, outstream);
            document.Open();

            //newFileStream is the flattend Form
            pdfReader = new PdfReader(newFileStream.ToArray());
            writer.AddDocument(pdfReader);

            PdfReader reader = new PdfReader(Properties.Resources.PdfForm);
            writer.AddDocument(reader);

            reader.Close();
            writer.Close();
            document.Close();

            return outstream.ToArray();

Now i merge the document with my second template and save it. Now i have the document that i want. First page ist 'readonly' and the second page has formfields.

My problem is now that the user can fill the document (checkboxes and textboxes) but if the user save the document the filled checkboxes disappears. So if the user send me back the document thera a no checkboxes in it.

I don't understand why only checkboxes disappear.




How to move extra checkbox to the bottom left corner in QFileDialog window in QT3

I have problem with moving checkbox from middle to the left:

 #include <qfiledialog.h>
    #include <qcheckbox.h>
    class FileDialog : public QFileDialog
    {
    public:
    QCheckBox* checkbox
    FileDialog() : QFileDialog(0)
    {
        checkbox = new QCheckBox(this);
        checkbox->setText("checkbox");
        addWidgets( 0, checkbox, 0 );
    }
    };

Looks like it: enter image description here

I need to move it like this(better option): enter image description here

or like this: enter image description here

I can't use this method:

#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>
class CheckBox : public QLabel
{
  QCheckBox* checkbox;
public:
  CheckBox(QWidget * parent) : QLabel(parent)
  {
    QGridLayout * box = new QGridLayout(this);
    checkbox = new QCheckBox(this);
    checkbox->setText("checkbox");
    box->addWidget(checkbox, 0, 0, Qt::AlignLeft);
  }
  void paintEvent ( QPaintEvent * ){}
};



class FileDialog : public QFileDialog
{
public:
  FileDialog() : QFileDialog(0)
  {
    addWidgets(new CheckBox(this), 0, 0);
  }
};

I need other way to solve this problem. Somebody can help me? :)




Ajax JQuery PHP Multiple Checkbox POST Method

I want to create web like this https://hisense.com.au/electronics/tv/all/, how the step ?

or if you have a link that allow me to get example source code...

Thanks




mercredi 28 mars 2018

C++ | Change value of string based on checkbox that is checked

I am trying to make a simple password generator and have a selection of checkboxes that change the type of items that can be generated into the password. How can I put the right value when a certain check box is checked. Below is my attempt at doing this. Thanks!

if(CheckBox1->Checked == true){
    letters = "abcdefghijklmnopqrstuvwxyz";
    amount = 26;
    if(CheckBox2->Checked == true){
        letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        amount = 52;
        if(CheckBox4->Checked == true){
            letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            amount = 62;
            if(CheckBox3->Checked == true){
                letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()";
                amount = 72;
            }
        }
    }
}




Checkbox needs to be pressed twice for onclick to work

I have a checkbox which is made with a DOM repeat:

<paper-listbox id="afgerondtitel">
      <paper-item id="check1">Afgerond</paper-item>
      <template is="dom-repeat" items="" count="[[num_box]]">
      <paper-item id="item_[[index]]"><paper-checkbox checked="" on-click="click"></paper-checkbox></paper-item>
      </template>
    </paper-listbox>

And I try to remove an variable from an ArrayList with this function:

click(){
        for(var i = this.gerechten.length - 1; i >= 0; i--) {
          if(this.gerechten[i].checked) {
            this.gerechten.splice(i, 1);
          }
          }
      }

The problem is that the checkbox needs to be pressed twice (so checked and then unchecked) to remove the variabele from the list.

I want to check the checkbox so the code immediately removes de variabele from the list.

Thanks in advance!




Checkboxes in DT shiny

I'm trying to make checkboxs into DT table and collect information about checked rows.
My code below

shinyApp(
  ui = fluidPage(
    fluidRow(
      verbatimTextOutput("value1"),
      column(12,
             DT::dataTableOutput('table'),  tags$script(HTML('$(document).on("click", "input", function () {
                       var checkboxes = document.getElementsByName("selected");
                       var checkboxesChecked = [];
                       for (var i=0; i<checkboxes.length; i++) {
                       if (checkboxes[i].checked) {
                       checkboxesChecked.push(checkboxes[i].value);
                      }
                      }
                     Shiny.onInputChange("checked_rows",checkboxesChecked);  })'))
      ))),
  server = function(input, output) {
    library(DT)
    library(glue)
    output$value1 <- renderPrint({ input$checked_rows }) 

    output$table <- DT::renderDataTable({
      iris$checked<-''
      iris$checked[2:5]<-'checked=\"checked\"'
      iris[["Select"]]<-glue::glue('<input type="checkbox" name="selected" {iris$checked} value="{1:nrow(iris)}"><br>')
      datatable(iris,escape=F,rownames=F,  class = 'cell-border compact', 
                options=list(ordering=T,autowidth=F,scrollX = TRUE,
                columnDefs = list(list(className = 'dt-center', targets = "_all"))
                ),
                selection="none"
      ) })})

enter image description here

All looking good, but:
1. when I make a choice in checkboxes and change the page, all data from the previous page disappears.
2. Also, as you can see on verbatimTextOutput ("value1"), it's worth selecting only checkboxes from the current page. How can I poll the entire table, and not just the page that I see?

Thanks!




Getting "checked" on checkbox if exists in database pdo

I have to look for help over here because I don't have the patience anymore.

In the database I have a table: "colours" and there is a list of colours.

The second table is products, in "additional" row I have json data like:

{"size":["47"],"color":["yellow","green","orange"]}

I want to "check" boxes if they exist in an additional row, but the problem is when I have 2 boxes checked, input fields will be duplicated 2 times. If I have 3 boxes selected, it will be three times.

This is my code:

$sveBoje = colors::find_all();
$data = json_decode($produkt[0]->opis);
foreach($sveBoje as $key => $value){
    foreach($data->boja as $key2 => $value2){
        if($value->name == $value2){
            $checked = "checked ";
        }else{
            $checked = "";
        }
        echo "
            <div class='checkbox checkbox-success checkbox-inline checkbox-circle'>
                <input ".$checked." type='checkbox' id='".$value->name."' name='boja[]' value='".$value->name."'>
                <label for='".$value->name."'> 
                    <span style='background:".$value->color.";' class='colorBox'></span>
                </label>
            </div>
        ";
    }
}




Get all unchecked boxes value

I wanted to ask if it is possible with php to show all checkboxes value that is empty efter the form have been submited.

Right now i get all the non empty values like this wich i understand but i want to do the apposite:

enter image description here

Code:

 <form method="post" action="">
<input type="checkbox" name="cars[]" value="Bmw">Bmw
<input type="checkbox" name="cars[]" value="Audi">Audi
<input type="submit">

if(empty($_POST['cars'])){
  echo "<pre>";
  var_dump($_POST['cars']);
  echo "</pre>";


}




adding multiple checkboxes to a form element

Let's suppose: a page with some dynamically generated checkboxes outside of a form element.

After the user has checked some of the checkboxes, I would love to append all those checkboxes (either checked or unchecked) into the form element so that when the user click the "submit" button, the form takes into account the checkboxes, their ids, names, data-names and their status (checked or unchecked). Is that possible ?

I have tried a codpen here: https://codepen.io/anthonysalamin/pen/ZxvZpP?editors=1010 but was unsuccessful sofar.

The jQuery code:

//insert all checkbox input elements into the form id="reservation"
  $("#reservation").submit(function(evt) {
  // should append all checkboxes to the form
  $("<input type='checkbox' />").append("#reservation");
});

Screenshot of my codpen here




checkbox should be always checked

I have a checkbox and I want to be checked always and it must be unchecked only if we wish to.

here is the html

<input type="checkbox" 
    class="custom-control-input" 
    [(ngModel)]="productDetails.iscanRetrunable" 
    name="iscanRetrunable" checked>

Is it because I'm binding some value to it ?




JQuery - multiple checkboxes actions

I have a form with multiple checkboxes and I would like to get this behavior:

  • The background of the "my_class" parent div changes when a checkbox is checked
  • The top button can Check or Uncheck all checkboxes
  • The background of all the "my_class" divs change when button clicked

CSS, HTML and JS code

$(document).ready(function() {
  $(".check_all:button").toggle(function() {
    $("input:checkbox").attr("checked", "checked");
    $("input:checkbox").closest(".my_class").addClass("checked_bg");
    $(this).val("Uncheck All")
  },
  function() {
    $("input:checkbox").removeAttr("checked");
    $("input:checkbox").closest(".my_class").removeClass("checked_bg");
    $(this).val("Check All");
  });

  $("input:checkbox").on("change", function() {
    var that = this;
    $(this).closest(".my_class").css("background-color", function() {
       return that.checked ? "#bcfab9" : "#ffffff";
    });
  });
});
.checked_bg {
  background-color: #bcfab9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="check_all" value="Check All">
<br>
<br>
<label for="checkbox_1">
      <div class="my_class">
        <input type="checkbox" id="checkbox_1" name="Box[]" value="1">
        <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
        <div>Duis sit amet malesuada ligula.</div>
      </div>
    </label>

<label for="checkbox_2">
      <div class="my_class">
        <input type="checkbox" id="checkbox_2" name="Box[]" value="2">
        <div>Quisque magna est, blandit ac laoreet eu, consectetur eget turpis.</div>
        <div>Fusce nisi tortor, suscipit sed luctus eu, varius eget massa.</div>
      </div>
    </label>

Test page: (JSFiddle)[https://jsfiddle.net/o4h97eae/18/]

It doesn't work, would you please help me to sort this out?




How to achieve this type of functionality in tableview IOS swift4

enter image description here

Hello, I want this type functionality using swift3 language.




How to save checkbox State in other activity

In this MainActivity.java I am trying to call a checkbox which is in other layout. Purpose: I want to save the state of the CheckBox even when the activity is closed it should the state of the CheckBox. If someone of you have different method for adding the CheckBox in the ListView please add that code. I am trying to make a todo list app.

package com.vivekraja07.vivekatgt;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; 

import com.vivekraja07.vivekatgt.db.Task;
import com.vivekraja07.vivekatgt.db.TaskHelper;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private TaskHelper mHelper;
private ListView mTaskListView;

private ArrayAdapter<String> mAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mHelper = new TaskHelper(this);

    CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
    boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
            .getBoolean("checkBox", false);
    checkBox1.setChecked(checked);
    mTaskListView = (ListView) findViewById(R.id.list_todo);
    mTaskListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    updateUI();
}
public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();
    switch(view.getId()) {
        case R.id.checkBox:
            PreferenceManager.getDefaultSharedPreferences(this).edit()
                    .putBoolean("checkBox", checked).commit();
            break;
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_add_task:
            final EditText taskEditText = new EditText(this);
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("New Task")
                    .setMessage("Add a new task")
                    .setView(taskEditText)
                    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogue, int which) {
                            String task = String.valueOf(taskEditText.getText());
                            if (task.length() == 0) {
                                return;
                            }
                            SQLiteDatabase db = mHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put(Task.TaskEntry.COL_TASK_TITLE, task);
                            db.insertWithOnConflict(Task.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                            db.close();
                            updateUI();
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create();
            dialog.show();
            return true;
        case R.id.menu_item_delete:
            Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
        case R.id.menu_item_select:
            Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
        default:
            return super.onOptionsItemSelected(item);

    }
}

private void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(Task.TaskEntry.TABLE,
            new String[] {Task.TaskEntry.COL_TASK_TITLE}, null, null, null, null, null);

    while (cursor.moveToNext()) {
        int index = cursor.getColumnIndex(Task.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(index));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(this, R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);

    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void deleteTask(View view) {
    View parent = (View) view.getParent();
    TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
    String task = String.valueOf(taskTextView.getText());
    SQLiteDatabase db = mHelper.getWritableDatabase();
    taskTextView.setPaintFlags(taskTextView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    db.close();
    updateUI();

}
}

here is the code for item_todo.xml from where the Checkbox is called.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_gravity="center_vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/task_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/checkBox"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="15dp"
    android:text="Hi"
    android:textSize="20sp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="CheckBox"
    android:onClick="deleteTask"/>

</RelativeLayout>




Salesforce Visualforce checkbox not clickable

enter code here( <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <span class="slds-checkbox">

{!$Label.SendEmailNotificationToCaseCreator} enter image description here )

In this code if i remove only then the checkbox is clickable and that too without any styles. How to make it work normally? I added the screenshot of checkbox without having span class and which is working not according to the styles. I have other checkbox on the same vf page which have the exactly same code but they work properly.




mardi 27 mars 2018

HTML checkbox to Javascript form

I am (still) working on creating sidebar input for a Sheets add-on I'm developing. My current challenge is allowing a textbox and a checkbox to be passed from the form to my function.

The textbox works and successfully passes the variable. The checkbox I'm not as clear on. I need to turn the checkbox into a boolean.

The relevant html:

<p>
  <input type="text" id="datepicker">
  </p>
  <p>
  Include pledge?<br>
    <input type="checkbox" name="pledge[]" id="pledgeCheck" value="true">Yes<br>
  <input type="radio" name="pledge" id="Off">No
  </p>
          <p>
            <input type="button" name="createdate" value="Create" onClick="google.script.run.create(document.getElementById('datepicker').value,document.getElementById('pledgeCheck').value)" />
          </p>
function create(datepicker,pledge) {

  //important vars
  var responses = ss.getSheetByName("Form Responses");
  var bulletin = ss.getSheetByName(todayDate);
  var todayDate=datepicker;
  var pledgeCheck=pledge;
  Logger.log(pledgeCheck);
  

currently the pledge feeds back as undefined.




categorical rows and checkbox inputs

I'm looking to make something like this:

I need to make rows like the image above that will populate depending on a selectinput and then produce three columns that can be checked and unchecked. Each checkbox will manipulate values in a graph so I'll need to be able to call out the true false values from the check boxes to update the graph. Has anyone done anything similar or know how I can do this in shiny?




Grading logic for checkboxes with multiple correct

[Quiz app1

I have problem with grading logic. I cannot determine why the points are count incorrectly. The code worked fine when I count points in one method. My mentor suggested to check points in separate methods and now I do not get how the app counts the points and how to solve it.




Android - Is it ok to have too many OnCheckedChangeListeners?

I'm doing this Android App that has a lot of EditText fields, and each one of them has a checkbox next to it.

I'm implementing listeners to those checkbox:

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {...});

Those listeners enable/disable the possibility to edit those EditTexts.

The thing is, i'm creating a new listener for EVERY checkbox, right? I have 34 checkboxes, so there are 34 instances of OnCheckedChangeListener running at the same time...

My questions are: Should I use another approach to this situation(better design pattern maybe)? Can I use only 1 instance, and reuse it in every checkbox?

Thank you for your future answers.




Why checkbox is not binding value of object field (Angular 4)

I want to bind field value in current object and switch checkbox depend on it value.

My checkbox:

<label class="checkbox-inline checbox-switch switch-success">
<input
  #livingRoom
  type="checkbox"
  name="livingRoom"
  id="livingRoom"
  [checked]="showDefaultTypeRoom.isExistLivingRoom"
/>
<span></span>
</label>

I change showDefaultTypeRoom object and isExistLivingRoom but my checkbox is not switching depend on isExistLivingRoom value.

How fix it?




Adding “Accept Terms” Checkbox to WordPress Registration Form [duplicate]

This question is an exact duplicate of:

I want to add “Accept Terms” Checkbox to WordPress Registration Form. I have tried some code in function.php but unable to fix. Please help me. My website link are - http://inikao.com/registration/#




lundi 26 mars 2018

c# WPF Checkbox delete in Listview Grid

how do i delete specific row by select few checkbox and delete them same time? and also update the XML file im using sharp serialize

image

in the image you cant see how it should look like

Xaml:

<ListView  Name="Trilogi" HorizontalAlignment="Left" Height="201" Margin="265,10,0,0" VerticalAlignment="Top" Width="240" SelectionChanged="ListView_SelectionChanged">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="" Width="30">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Name="Chck" Checked="Chck_Checked"  Command="{Binding Check}" Width="50" ></CheckBox>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="ID" Width="40" DisplayMemberBinding="{Binding Veh_Key}"/>
                <GridViewColumn Header="Plate Number" Width="80" DisplayMemberBinding="{Binding Veh_Value}"/>

            </GridView>
        </ListView.View>
    </ListView>
    <Button Name="Del" Content="Delete" HorizontalAlignment="Left" Height="27" Margin="523,17,0,0" VerticalAlignment="Top" Width="102" Click="Button_Click"/>

the add is work fine only the select items in the checkbox cs:

private void Chck_Checked(object sender, RoutedEventArgs e)
    {

        foreach (var item in Trilogi.SelectedItem.ToString())
        {
            i   
            veh[item].Veh_Is_Checked = true;
            MessageBox.Show(veh[item].Veh_Key.ToString());
        }
    }


private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach(var item in Trilogi.Items)
        {
            veh.Remove(item as Car);
        }
    }




JQuery validation of radio buttons and check boxes on same form

I have a form that creates a set of radio buttons and a set of checkboxes from the database. These are fixed at six radio and six checkboxes. They are for a questionnaire and a new version of the form opens when the user clicks the next button. In some cases, there will be four radio buttons and sometimes three. The same applies to the checkboxes, sometimes six or sometimes four.

I am really struggling to do JQuery validation on the form as it posts. I can get the radio buttons to works, but I cannot do the checkboxes successfully.

The Razor View is as follows:

 @if (Model.fldAnswerType == "Radio") { @Html.Label("", String.Format(Model.fldQuestion, 1))
<br /> if (Model.fldOption1 != null) {
<label class="containers">
    @Model.fldOption1
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption1">
    <span class="radios"></span>
</label>
} if (Model.fldOption2 != null) {
<label class="containers">
    @Model.fldOption2
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption2">
    <span class="radios"></span>
</label>
} if (Model.fldOption3 != null) {
<label class="containers">
    @Model.fldOption3
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption3">
    <span class="radios"></span>
</label>
} if (Model.fldOption4 != null) {
<label class="containers">
    @Model.fldOption4
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption4">
    <span class="radios"></span>
</label>
} if (Model.fldOption5 != null) {
<label class="containers">
    @Model.fldOption5
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption5">
    <span class="radios"></span>
</label>
} if (Model.fldOption6 != null) {
<label class="containers">
    @Model.fldOption6
    <input type="radio" name="Radio" id="Radio" value="@Model.fldOption6">
    <span class="radios"></span>
</label>
} }

<fieldset class="chkGroup">
    @if (Model.fldAnswerType == "Check") { @Html.Label("", String.Format(Model.fldQuestion, 1))
    <br /> if (Model.fldOption1 != null) {
    <label class="containers">
        @Model.fldOption1
        <input type="checkbox" value="@Model.fldOption1" name="chkGroup[]" id="Check1" class="Check">
        <span class="checkmark"></span>
    </label>
    } if (Model.fldOption2 != null) {
    <label class="containers">
        @Model.fldOption2
        <input type="checkbox" value="@Model.fldOption2" name="chkGroup[]" id="Check2" class="Check">
        <span class="checkmark"></span>
    </label>
    } if (Model.fldOption3 != null) {
    <label class="containers">
        @Model.fldOption3
        <input type="checkbox" value="@Model.fldOption3" name="chkGroup[]" id="Check3" class="Check">
        <span class="checkmark"></span>
    </label>
    } if (Model.fldOption4 != null) {
    <label class="containers">
        @Model.fldOption4
        <input type="checkbox" value="@Model.fldOption4" name="chkGroup[]" id="Check4" class="Check">
        <span class="checkmark"></span>
    </label>
    } if (Model.fldOption5 != null) {
    <div id="Checks"></div>
    <label class="containers">
        @Model.fldOption5
        <input type="checkbox" value="@Model.fldOption5" name="chkGroup[]" id="Check5" class="Check">
        <span class="checkmark"></span>
    </label>
    } if (Model.fldOption6 != null) {
    <label class="containers">
        @Model.fldOption6
        <input type="checkbox" value="@Model.fldOption6" name="chkGroup[]" id="Check6" class="Check">
        <span class="checkmark"></span>
    </label>
    } 
  }
</fieldset>
<p class="control-error" name="control-error" id="control-error">You must select an answer.</p>
<p class="checkerror" name="checkerror" id="checkerror">You must select an answer chk.</p>
<input type="submit " value="Next " id="btn " class="btn btn-sm btn-primary " />

My JQuery for the different elements is working at the same time and not individually depending on the type of element on the form.

 $(document).ready(function () {
        $('#myForm').submit(function () {
            if ($('#Radio').length) {
                console.log("Radio")
                if (!$("input[name='Radio']:checked").val()) {
                    $('#control-error').show();
                    return false;
                } else {
                    $('#control-error').hide();
                }
            } else {
                $('#control-error').hide();
            }

            //If chk exists do the following
            if (!$("input[name='chkGroup[]']:checked").val()) {
                $('.chkGroup').each(function () {
                    console.log("Check")
                    if ($(this).find('input[type=checkbox]:checked').length == 0) {
                        $('#checkerror').show();
                        return false;
                    }
                    else {
                        $('#checkerror').show();
                    }
                });
            } else {
                $('#control-error').hide();
            }
        });
    });




Android - How to get checked state of CheckBoxes in dynamically added LinearLayouts?

I was wondering, I have a vertical LinearLayout where I dynamically add horizontal LinearLayouts. Each horizontal LinearLayout contains a CheckBox. I would like to know, how would I retrieve the checked state of each CheckBox in each dynamically added LinearLayout?

   for (int i = 0; i < array.size(); i++) {
            LayoutInflater layoutInflater = (LayoutInflater)
                    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout testView = (LinearLayout) layoutInflater.inflate(R.layout.balance_test_layout, null);
            for (int j = 0; j < customConditions.size(); j++) {
                TextView checkView = new TextView(BalanceActivity.this);
                checkView.setPadding(padding, padding, padding, padding);
                checkView.setTextSize(20);

                checkView.setGravity(Gravity.CENTER);

                LinearLayout.LayoutParams checkTextParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics())));

                checkTextParams.gravity = Gravity.CENTER;
                checkView.setLayoutParams(checkTextParams);

                testView.addView(checkView);


            }


            CheckBox option = (CheckBox) testView.findViewById(R.id.testCheckBox);
            option.setId(i);
            option.setText(array.get(i));

        //code for of rest of LinearLayout
   }

     okButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //need to get values of CheckBoxes in here
                    }
     });




deselect checkmarks from the Collectionview in swift4

I am showing collocation view with multiple checkmarks in main view controller.its working fine

enter image description here

after select checkmarks data showing into next view controller. it is also working. when i back to main view controller which I selected check marks are not unchecked. how to uncheck selected checkmarks.

I used this reference https://github.com/maximbilan/CheckMarkView

@IBOutlet weak var checkMarkViews: CheckMarkView!


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)as! CustomCollectionViewCell

        let row = indexPath.row

        cell.CoutnryImages.downloadImageFrom(link: imagesarray[row] , contentMode: .scaleToFill)

        cell.countrynmae.text = itemsarray[row]

        cell.checkMarkViews.setNeedsDisplay()

      return cell

    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let cell = CollectionView.cellForItem(at: indexPath) as! CustomCollectionViewCell

        var indexpathvalues = indexPath.row   

        cell.checkMarkViews.checked = !cell.checkMarkViews.checked

        if cell.checkMarkViews.checked == true
        {

           PassedID.append(idarray[indexpathvalues])
            _selectedcell.add(indexpathvalues)

        }
        else
        {
        if PassedID.isEmpty
            {
                print("no Item found ")
            }
            else
            {
                 _selectedcell.remove(indexpathvalues)
                PassedID.removeLast()
            }

        }

    }

    @IBAction func Addbutton(_ sender: UIBarButtonItem) {

              performSegue(withIdentifier: "next", sender: self)

    }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let vc = segue.destination as? nextViewController

        vc?.arrayvalues = self.PassedID

        _ = navigationController?.popViewController(animated: true)       

    }

how to uncheck the multiple selection after back to main view controller  




Duplicate the Woocommerce T&C checkbox in checkout page and use for Privacy Policy

Hi I have been trying to add an additional Conditional Check Box to my Woocommerce checkout page, the same as the Terms and Conditions one but with information about the new GDPR (data protection) and a link to my Privacy Policy. They must tick the box before they can check out.

I have been using various snippets of code put together from what I have found here and have managed to add a conditional check box and some text but have not been able to add a link to the Privacy Policy. I have to add it below the Checkout Box. Ideally I would like to have the link alongside the check box like it appears on the Terms and Conditions one. Here's what I have so faar, any help to get the Privacy page link within the checkout box would be appreciated.

Conditional Checkbox Privacy policy Link

//Here is the function for adding the checkbox:
function cw_custom_checkbox_fields( $checkout ) {

    echo '<div class="cw_custom_class"><h3>'.__('Give Sepration Heading: ').'</h3>';

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',
        'label'         => __('Agreegation Policy.'),
        'required'  => true,
    ), $checkout->get_value( 'custom_checkbox' ));

    echo '</div>';
}
add_action('woocommerce_checkout_after_terms_and_conditions', 'checkout_additional_checkboxes');
function checkout_additional_checkboxes( ){
    $checkbox1_text = __( "I have read and accept the Privacy Policy and understand how you manage my Data under GDPR", "woocommerce" );
       ?>
    <p class="form-row custom-checkboxes">
        <label class="woocommerce-form__label checkbox custom-one">
            <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_one" > <span><?php echo  $checkbox1_text; ?></span> <span class="required">*</span>
        </label>
            </p>
    <?php
}

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['custom_one'] )
        wc_add_notice( __( 'You must accept "I have read and accept the Privacy Policy and understand how you manage my Data under GDPR".' ), 'error' );
  }




add_filter('comment_form_defaults','isa_comment_reform');
add_action( 'woocommerce_after_checkout_form', 'wnd_checkout_message_bottom', 10 );

function wnd_checkout_message_bottom( ) {
 echo '<div class="wnd-checkout-message"><h3> <a href="http://127.0.0.1/protest/privacy-policy/" target="_blank">Privacy Policy</a><br/></h3>
</div>';
}



OnCheckChanged not fired on CheckBox uncheck

I know this question may have been asked already, but none of the answers work so I'm asking to see if anyone has any better ideas. Very simply, I have an asp:CheckBox as such:

<asp:CheckBox runat="server" ID="IsPrimarySigning" Font-Size="Large" CssClass="signer-margin" OnCheckedChanged="SignRemotely_Checked" AutoPostBack="true"/>

And the OnCheckedChange handler method:

protected void SignRemotely_Checked(object sender, EventArgs e) {}

The code inside it is irrelevant because I put a breakpoint on the first open curly brace and it's never hit by unchecking IsPrimarySigning. However, it works and the breakpoint is hit when I check IsPrimarySigning. Any ideas?




wxPython widget not centered vertically

I am trying to center a CheckBox widget vertically inside a panel. I cannot figure out why it's aligned to the top.

I had to create a Panel for the CheckBox because without that the background looks ugly (Windows 10 -- see second image)

Thanks for suggestions!

class wxUIE(wx.Frame):

    def __init__(self, parent, title):


        wx.Frame.__init__(self, parent, size=(800, 400), title=title)

        self.editorText = wx.TextCtrl (self, style=wx.TE_MULTILINE+wx.SUNKEN_BORDER+wx.TE_BESTWRAP)

        self.myBar = wx.TextCtrl (self, -1)
        # Checkbox
        self.myCheckBoxPanel = wx.Panel(self, size=(-1, 25))
        self.myCheckBox = wx.CheckBox(self.myCheckBoxPanel, label="Highlight",  style=wx.ALIGN_CENTER_VERTICAL)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)

        self.sizer.Add(self.editorText, 1, wx.EXPAND)

        self.sizer.Add(self.sizer2, 0, wx.EXPAND)
        self.sizer2.Add(self.myBar, 10, wx.EXPAND)
        self.sizer2.Add(self.myCheckBoxPanel, 0, wx.EXPAND)

        self.SetSizeHints(800,400)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        self.Show()


# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = wxUIE(None, "My Edit Control")
    frame.Show()
    app.MainLoop()

CheckBox aligned to top of panel

CheckBox is aligned vertically correctly but the background sucks.




bootstrap 4 checkbox inside list-group-item as collapse not functioning

I have created a bootstrap 4 list-group-item together with the collapse function.

My issue, is that the list-group-item interferes with a checkbox within it, such that the checkbox itself when clicked activates the collapse function as well, but also does not respond to being selected/unselected.

If a checkbox/radio is in the list-group-item, how can I make the checkbox work independently within the list-group-item, if the list-group-item is a collapsible button?

I need it to work like it does, but it there someway I can make the checkbox work without it triggering the collapse?

please review code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>



<div class="container">
  <div class="row">
    <div class="col">
      <div class="list-group mt-5">
        <a href="#" class="list-group-item list-group-item-action" data-toggle="collapse" data-target="#sample1" aria-expanded="false" aria-controls="sample1">
        <div class="custom-control custom-checkbox float-left">
  <input type="checkbox" class="custom-control-input" id="customCheck1">
  <label class="custom-control-label" for="customCheck1"></label>
</div>
    Cras justo odio
  </a>
  <div class="collapse mb-2" id="sample1">
  <div class="card card-body">
    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>
        <a href="#" class="list-group-item list-group-item-action">Dapibus ac facilisis in</a>
        <a href="#" class="list-group-item list-group-item-action">Morbi leo risus</a>
        <a href="#" class="list-group-item list-group-item-action">Porta ac consectetur ac</a>
        <a href="#" class="list-group-item list-group-item-action disabled">Vestibulum at eros</a>
      </div>
    </div>
  </div>
</div>



get array of checked and unchecked checkboxes

I have checkbox input fields that are added to DOM dynamically. I want to get all checked and unchecked values as mentioned here.

HTML:

<input type="checkbox" name="lead_check[]" value="1">

Javascript:

$('#includes').click(function(e)
{
  e.preventDefault();
  $('#include-fields').append('<div class="holder-includes"><a href="#" class="remove-includes"><i class="fa fa-trash-o pull-right"></i></a>' +
    '<select name="team[]" class="form-control team">'+
    '<input type="checkbox" name="lead_check[]" value="1"></div>');

  var items = "";
  $.post("teamFetch", function(data)
  {
    $.each(data,function(index,item) 
    {
      items+="<option value='"+item.id+"'>"+item.title+"</option>";
    });

    $(".team:last").html(items); 
  }, "json");



});

I am getting only checked values in lead_check[] array.

[lead_check] => Array ( [0] => 1 [1] => 1 [2] => 1 ).

I need to get all unchecked values too.

[lead_check] => Array ( [0] => 1 [1] => 0 [2] => 1 [3] => 0).

I tried adding hidden input fields too. But they didn't help either.

How do I achieve desired output in case of dynamically generated checkbox input fields.

Any help is very much appreciated. Thanks.




PHP Calc number of checkboxes ticked & Add their Values + Tax

I need to write a PHP script that computes the total cost of the ordered light bulbs and battery packs after adding 17.5 percent VAT. The program must inform the buyer of exactly what was ordered in a table, and what credit card was chosen to make payment.

Here is my code so far (it is a form with checkboxes and radio buttons to order light bulbs

bulbs.html

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<script>
function formSubmit() {
    document.forms["myForm"].submit();
}
</script>
</head>
<body>

<form name="myForm" action="calc.php" method="post">
Name: <input type="text" name="fullname"><br>

  <input type="checkbox" name="bulb[]" value="Bulb1"> Four 100-watt light bulbs for $2.39<br>
  <input type="checkbox" name="bulb[]" value="Bulb2"> Eight 100-watt light bulbs for $4.29<br>
  <input type="checkbox" name="bulb[]" value="Bulb3"> Four 100-watt long-life light bulbs for $3.95<br>
  <input type="checkbox" name="bulb[]" value="Bulb4"> Eight 100-watt long-life light bulbs for $7.49<br>


Number of battery packs you would like for $10.42 each: <input type="text" name="batterypacks"><br>

  <input type="radio" name="card" value="Card1"> Visa<br>
  <input type="radio" name="card" value="Card2"> Mastercard<br>
  <input type="radio" name="card" value="Card3"> American Express<br>

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


</body>
</html>

this is my calc.php

<?php

echo $_POST;

echo "<br>";

echo $_POST['bulb'];




if(isset($_POST['bulb'])){
  if (is_array($_POST['bulb'])) {
    foreach($_POST['bulb'] as $value){
        $bulb1=2.39;
        $bulb2=4.29;
        $bulb3=3.95;
        $bulb4=7.49;
        $totalCost;
      echo $value;
    }
  } else {
    $value = $_POST['bulb'];
    echo $value;
  }
}



$price = 0;

foreach( $_POST['bulb'] as $key => $value ) {
   switch( $value ) {
      case 'Bulb1':
        $price = $price + 2.39;
        break;
      case 'Bulb2':
        $price = $price + 4.29;
        break;
      case 'Bulb3':
        $price = $price + 3.95;
        break;  
      case 'Bulb4':
        $price = $price + 7.49;
        break;
      
}
echo $price; // Total price

$afterTax = 0;

$price * .175 = $afterTax;

echo $afterTax;



$name = $_GET['card'];


foreach ($name as $card){ 
    echo $card."<br />";
}



?>

// if bulb 1 is selcted, add to total price
//compare checkedItem==Bulb1

else
checkedItem==Bulb2

else
checkedItem==Bulb3

I feel like I'm really close! However, whenever I click "submit" on bulbs.html, it just leads me to the code for calc.php and doesn't show any values at all. What am I missing in terms of calculating the checked boxes and adding tax?




dimanche 25 mars 2018

Rails Checkbox boolean values not passing to database

Can't seem to get the checkbox to pass true to my database

this is the middle part of my devise sign-up form.

      <div class="form-group">
    <%= check_box_tag :admin, checked = true %>
    <%= label_tag :admin %>
  </div>

I've set the admin field to default to false in my schema.rb when Null

I don't know where else to start.

If you guys need any screenshots of controllers, etc.

Please comment :)




set max value of input box based on the selected checkbox in angular js

I have created a table which displays units, amounts , checkbox1forunits , checkbox2foramounts , input. the table has four records. the value of units and amounts come from the json array.

I want to set the max of input box based on the selected checkbox. for each input box there is different max value. if checkbox1forunits is selected then set max of input box to the corresponding given unit. if checkbox2foramounts is selected then set max of input box to the corresponding given amount.

please suggest me what condition should I write to achieve this. I am understanding the logic but getting difficulty writing it in angular js.the code is given below.

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
            $scope.IsVisible = false;
            $scope.GenerateTable = function () {
                $scope.Customers = [
                {unit: 100, amount: 1000},
                { unit: 200,amount: 2000},
                {unit: 300,amount: 3000},
                { unit: 400,amount: 4000}
               ];

                $scope.IsVisible = true;



              };




        });

        app.directive("limitToMax", function() {
  return {
    link: function(scope, element, attributes) {
      element.on("keydown keyup", function(e) {

    if (Number(element.val()) > Number(attributes.max) &&
          e.keyCode != 46 // delete
          &&
          e.keyCode != 8 // backspace
        ) {
          scope.val=true;
          e.preventDefault();
          element.val(attributes.max);
        }
      });
    }
  };
});

    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Generate Table" ng-click="GenerateTable()" />
        <hr />
        <table cellpadding="0" cellspacing="0" ng-show="IsVisible">
            <tr>
                <th>Unit</th>
                <th>Amount</th>
                <th>Checkbox1</th>
                <th>Checkbox2</th>
            </tr>
            <tbody ng-repeat="m in Customers">
                <tr>
                    <td></td>
                    <td></td>
                    <td><input type="checkbox"ng-model="checkbox1[$m]"</td>
                    <td><input type="checkbox"ng-model="checkbox2[$m]"</td>
                    <td><input type="number" ng-model="myVar[$m]" min="1" max="" limit-to-max /></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>




RWD flexbox form not working

I have one simple question :

html {
        box-sizing: border-box;
        
  }
  
  *,
  *:before,
  *:after {
        box-sizing: inherit;
  }
  
body  {
        background-image: url("IMG/tlo.jpg");
        background-size: cover;
        font-family: "Titillium Web", sans-serif; 
}                       

.top-container {
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0.42; 
        margin-top: 1rem;
}

.main-container {
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
        max-height: 1200px;
        align-items: center;
        align-content: center;
        margin-top: 1.25rem;
        margin-bottom: 1.25rem;
        margin: 0 -5px;
 }

 .h2 {
        font-size: 2rem;
        text-shadow: 1px 2px 2px #2b0100;
        color: #FFFFFF;
 }

.rf-container  {
        display: flex;
        margin: 0 55px;
        width: 380px;
        background-color: #f4f4f4;
        padding: 20px 20px;
        box-shadow: 0px 0px 0px 20px rgba(0,0,0,0.24);
 }

 .form-rf {
        display: flex;
        flex-direction: column;
        flex: 1;
 }

.rf-element  {
        display:flex;
        background-color: #f8f8f8;
        border: 1px solid #c6c6c6;
        border-radius: 2px;
        margin-bottom: 1.25rem;
        height: 2.5rem;
        width: 340px;
}

.rf-element:hover {
        border-color: #88c814;
}

.main-icon {
        width: 45px;
        flex: 2;
        color: #dedede;
        font-size: 1.375rem;
        text-align: center;
        padding-top: 1%;
}

.main_field {
        flex: 10;
        height: 100%;
        border: none;
        background-color: #f8f8f8;
        font-family: 'Titillium Web', sans-serif;
        font-size: 1rem;
        color: #afafaf;
        padding-left: 3%;
        outline: none;
        border-style: none;
}

.main_field:focus {
        color: #428c42;
        box-shadow: 0 0 10px 2px rgba(204,204,204,0.9);
        border: 2px solid #a5cda5;
        background-color: #e9f3e9;
}

.separator {
        display: flex;
        width: 5px;
        min-height: 100%;
        background-color: #dedede;
        border-top: 0.1875rem solid #f8f8f8;
        border-bottom: 0.1875rem solid #f8f8f8;
}

 /*  checkbox */
.checkbox-custom {
    opacity: 0;
    position: absolute;   
}

.checkbox-custom, .checkbox-custom-label {
    display: inline-block;
    vertical-align: middle;
    margin: 0.3125rem;
    cursor: pointer;
}

.checkbox-custom-label{
    position: relative;
}

.checkbox-custom + .checkbox-custom-label:before{
    content: '';
    background: #fff;
    border: 0.125rem solid #ddd;
    display: inline-block;
    vertical-align: middle;
    width:1.25rem;
    height: 1.25rem;
    padding: 0.125rem;
    margin-right: 0.625rem;
    text-align: center;
}

.checkbox-custom:checked + .checkbox-custom-label:before {
    content: "";
    background: #428c42; 
}
 /*  checkbox end */

.main_green_button {
        margin-top: 0.5rem;     
        width: 100%;
        border: 0.0625rem solid #3b9a00;
        border-radius: 0.125rem;
        font-size: 1.5rem;
        font-family: 'Titillium Web', sans-serif;
        color: #FFFFFF;
        text-shadow: 0.0625rem 0.0625rem #51850e;
        background: linear-gradient(#a3d840, #73b618);
        height: 3rem;
        box-shadow: 0.0625rem 0.0625rem 0.0625rem 0px #FFFFFF;
        cursor: pointer;
}

.main_green_button:hover {
        background: linear-gradient(#AAE650, #7DC323);
}

.main_green_button_smaller {
        height: 2.1875rem;
        font-size: 1rem;
        width: 45%;
        
}

.main_green_button_smaller-disabled {
        opacity: 0.5;
        cursor: no-drop;
}

.main_green_button_smaller-warning {
        background: linear-gradient(#f65e70, #f03747);
        border: 1px rgba(209, 18, 18, 0.616);
}

.main_green_button_smaller-warning:hover {
        background: linear-gradient(#FF697D, #FA4155);
}

 /*  button  end */

 /*  text area*/

 .textarea {
        width: 100%;
        margin-bottom: 1.25rem;
        background-color: #f8f8f8;
        border: 0.0625rem solid #c6c6c6;
        border-radius: 1.5px;
        font-family: 'Titillium Web', sans-serif;
        font-size: 1rem;
        color: #afafaf;
        resize: none;
 }

 .doublebtn {
    display: flex;
        justify-content: space-between;
        align-items: center;
 }


.footer {
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        opacity: 0.5;
}

.footer_top {
  margin: 3.125rem 0px 0.5rem 0px;
  
}


 /*  MEDIA*/

 @media only screen and (max-width: 945px) {
        
        .main-container {
        
        max-height: 3100px;
        }
} 

@media only screen and (max-width: 480px) {

 .main-container {
   margin: 0 auto;
 }

 .rf-container {
        margin: 0 auto;

 }
 .rf-element {
   
 }

 .main_field {
        
 }
 .doublebtn {
        
 }

}
<section class="main-container">
         <!-- REGISTER FORM -->
                                
         <h2 class="h2">Register Form</h2>
                <div class="rf-container">
         
                        <form action="" class="form-rf">
                                
                                <!-- REGISTER FORM / 1 row -->
                                        <div class="rf-element">
                                                <div class="main-icon">
                                                        <i class="fa fa-user" aria-hidden="true"></i>
                                                </div>
                                                <div class="separator"></div>
                                                <input class="main_field" type="text" name="username"placeholder="Username" onfocus="this.placeholder=''" onblur="this.placeholder='Username'" required>
                                        </div>
                                <!-- REGISTER FORM / 2 row -->          
                                        <div class="rf-element">
                                                <div class="main-icon">
                                                        <i class="fa fa-lock" aria-hidden="true"></i>
                                                </div>
                                                <div class="separator"></div>
                                                <input class="main_field" type="password" name="password"placeholder="Password"
                                                onfocus="this.placeholder=''" onblur="this.placeholder='Password'"  required>
                                        </div>                            
                                <!-- REGISTER FORM / 3 row --> 
                                        <div class="rf-element">
                                                <div class="main-icon">
                                                        <i class="fa fa-lock" aria-hidden="true"></i>
                                                </div>
                                                <div class="separator"></div>
                                                <input class="main_field" type="password" name="Confirm Password"placeholder="Confirm Password" onfocus="this.placeholder=''" onblur="this.placeholder='Confirm Password'"  required>
                                        </div>                            
                                <!-- REGISTER FORM / 4 row --> 
                                        <div class="rf-element">
                                                <div class="main-icon">
                                                        <i class="fa fa-envelope" aria-hidden="true"></i>
                                                </div>
                                                <div class="separator"></div>
                                                <input class="main_field" type="email" name="Email"placeholder="Email" onfocus="this.placeholder=''" onblur="this.placeholder='Email'"  required>
                                        </div>    
                                <!-- REGISTER FORM / 5 row --> 
                                        <div class="rf-element">
                                                <div class="main-icon">
                                                        <i class="fa fa-map-marker" aria-hidden="true"></i>
                                                </div>
                                                <div class="separator"></div>
                                                <select class="main_field" name="location" required>
                                                        <option value="" disabled selected>Your Location</option>
                                                        <option value="gdansk">Gdańsk</option>
                                                        <option value="krakow">Kraków</option>
                                                        <option value="poznan">Poznań</option>
                                                        <option value="warszawa">Warszawa</option>
                                                        <option value="wroclaw">Wrocław</option>
                                                </select>                                         
                                        </div>                                    
                                <!-- REGISTER FORM / 6 row --> 
                                
                                <input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" >
                                <label for="checkbox-1" class="checkbox-custom-label">I have read and accept the terms of use.</label>

                                <!-- REGISTER FORM / sign in -->  
                                        <input class="main_green_button" type="submit" value="Sign up">                                                   
                                
         </form>
         
      </div>
        </section>        

codepen all

when I try make responsive,u see that forms do not fit on the page. In fact, no element is responsive despite the use FLEXBOX.

I tried to combine using values flex: 1 1 auto; or flex: 1 1 80% an excuse for .main-field input .

In short - I would like to receive responsive forms, but at the moment I have no idea how to deal with it.